1 package com.puppycrawl.tools.checkstyle.checks.coding; 20 21 import java.util.ArrayList ; 22 import java.util.HashMap ; 23 import java.util.Iterator ; 24 import java.util.Set ; 25 import java.util.regex.Pattern ; 26 27 import com.puppycrawl.tools.checkstyle.api.Check; 28 import com.puppycrawl.tools.checkstyle.api.DetailAST; 29 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 30 import com.puppycrawl.tools.checkstyle.api.Utils; 31 32 38 public class MultipleStringLiteralsCheck extends Check 39 { 40 44 private final HashMap mStringMap = new HashMap (); 45 49 private int mAllowedDuplicates = 1; 50 51 55 public void setAllowedDuplicates(int aAllowedDuplicates) 56 { 57 mAllowedDuplicates = aAllowedDuplicates; 58 } 59 60 63 private Pattern mPattern; 64 65 68 public MultipleStringLiteralsCheck() 69 { 70 setIgnoreStringsRegexp("^\"\"$"); 71 } 72 73 77 public void setIgnoreStringsRegexp(String aIgnoreStringsRegexp) 78 { 79 if ((aIgnoreStringsRegexp != null) 80 && (aIgnoreStringsRegexp.length() > 0)) 81 { 82 mPattern = Utils.getPattern(aIgnoreStringsRegexp); 83 } 84 else { 85 mPattern = null; 86 } 87 } 88 89 90 public int[] getDefaultTokens() 91 { 92 return new int[] {TokenTypes.STRING_LITERAL}; 93 } 94 95 96 public void visitToken(DetailAST aAST) 97 { 98 final String currentString = aAST.getText(); 99 if ((mPattern == null) || !mPattern.matcher(currentString).find()) { 100 ArrayList hitList = (ArrayList ) mStringMap.get(currentString); 101 if (hitList == null) { 102 hitList = new ArrayList (); 103 mStringMap.put(currentString, hitList); 104 } 105 final int line = aAST.getLineNo(); 106 final int col = aAST.getColumnNo(); 107 hitList.add(new StringInfo(line, col)); 108 } 109 } 110 111 112 public void beginTree(DetailAST aRootAST) 113 { 114 super.beginTree(aRootAST); 115 mStringMap.clear(); 116 } 117 118 119 public void finishTree(DetailAST aRootAST) 120 { 121 final Set keys = mStringMap.keySet(); 122 final Iterator keyIterator = keys.iterator(); 123 while (keyIterator.hasNext()) { 124 final String key = (String ) keyIterator.next(); 125 final ArrayList hits = (ArrayList ) mStringMap.get(key); 126 if (hits.size() > mAllowedDuplicates) { 127 final StringInfo firstFinding = (StringInfo) hits.get(0); 128 final int line = firstFinding.getLine(); 129 final int col = firstFinding.getCol(); 130 final Object [] args = 131 new Object []{key, new Integer (hits.size())}; 132 log(line, col, "multiple.string.literal", args); 133 } 134 } 135 } 136 137 140 private static final class StringInfo 141 { 142 145 private final int mLine; 146 149 private final int mCol; 150 155 private StringInfo(int aLine, int aCol) 156 { 157 mLine = aLine; 158 mCol = aCol; 159 } 160 161 165 private int getLine() 166 { 167 return mLine; 168 } 169 170 174 private int getCol() 175 { 176 return mCol; 177 } 178 } 179 180 } 181 | Popular Tags |