001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2016 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import java.util.BitSet; 023import java.util.List; 024import java.util.Map; 025import java.util.regex.Pattern; 026 027import com.google.common.collect.Lists; 028import com.google.common.collect.Maps; 029import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 030import com.puppycrawl.tools.checkstyle.api.DetailAST; 031import com.puppycrawl.tools.checkstyle.api.TokenTypes; 032import com.puppycrawl.tools.checkstyle.utils.CommonUtils; 033import com.puppycrawl.tools.checkstyle.utils.TokenUtils; 034 035/** 036 * Checks for multiple occurrences of the same string literal within a 037 * single file. 038 * 039 * @author Daniel Grenner 040 */ 041public class MultipleStringLiteralsCheck extends AbstractCheck { 042 043 /** 044 * A key is pointing to the warning message text in "messages.properties" 045 * file. 046 */ 047 public static final String MSG_KEY = "multiple.string.literal"; 048 049 /** 050 * The found strings and their positions. 051 * {@code <String, ArrayList>}, with the ArrayList containing StringInfo 052 * objects. 053 */ 054 private final Map<String, List<StringInfo>> stringMap = Maps.newHashMap(); 055 056 /** 057 * Marks the TokenTypes where duplicate strings should be ignored. 058 */ 059 private final BitSet ignoreOccurrenceContext = new BitSet(); 060 061 /** 062 * The allowed number of string duplicates in a file before an error is 063 * generated. 064 */ 065 private int allowedDuplicates = 1; 066 067 /** 068 * Pattern for matching ignored strings. 069 */ 070 private Pattern pattern; 071 072 /** 073 * Construct an instance with default values. 074 */ 075 public MultipleStringLiteralsCheck() { 076 setIgnoreStringsRegexp("^\"\"$"); 077 ignoreOccurrenceContext.set(TokenTypes.ANNOTATION); 078 } 079 080 /** 081 * Sets the maximum allowed duplicates of a string. 082 * @param allowedDuplicates The maximum number of duplicates. 083 */ 084 public void setAllowedDuplicates(int allowedDuplicates) { 085 this.allowedDuplicates = allowedDuplicates; 086 } 087 088 /** 089 * Sets regular expression pattern for ignored strings. 090 * @param ignoreStringsRegexp 091 * regular expression pattern for ignored strings 092 * @throws org.apache.commons.beanutils.ConversionException 093 * if unable to create Pattern object 094 */ 095 public final void setIgnoreStringsRegexp(String ignoreStringsRegexp) { 096 if (ignoreStringsRegexp == null || ignoreStringsRegexp.isEmpty()) { 097 pattern = null; 098 } 099 else { 100 pattern = CommonUtils.createPattern(ignoreStringsRegexp); 101 } 102 } 103 104 /** 105 * Adds a set of tokens the check is interested in. 106 * @param strRep the string representation of the tokens interested in 107 */ 108 public final void setIgnoreOccurrenceContext(String... strRep) { 109 ignoreOccurrenceContext.clear(); 110 for (final String s : strRep) { 111 final int type = TokenUtils.getTokenId(s); 112 ignoreOccurrenceContext.set(type); 113 } 114 } 115 116 @Override 117 public int[] getDefaultTokens() { 118 return getAcceptableTokens(); 119 } 120 121 @Override 122 public int[] getAcceptableTokens() { 123 return new int[] {TokenTypes.STRING_LITERAL}; 124 } 125 126 @Override 127 public int[] getRequiredTokens() { 128 return getAcceptableTokens(); 129 } 130 131 @Override 132 public void visitToken(DetailAST ast) { 133 if (!isInIgnoreOccurrenceContext(ast)) { 134 final String currentString = ast.getText(); 135 if (pattern == null || !pattern.matcher(currentString).find()) { 136 List<StringInfo> hitList = stringMap.get(currentString); 137 if (hitList == null) { 138 hitList = Lists.newArrayList(); 139 stringMap.put(currentString, hitList); 140 } 141 final int line = ast.getLineNo(); 142 final int col = ast.getColumnNo(); 143 hitList.add(new StringInfo(line, col)); 144 } 145 } 146 } 147 148 /** 149 * Analyses the path from the AST root to a given AST for occurrences 150 * of the token types in {@link #ignoreOccurrenceContext}. 151 * 152 * @param ast the node from where to start searching towards the root node 153 * @return whether the path from the root node to ast contains one of the 154 * token type in {@link #ignoreOccurrenceContext}. 155 */ 156 private boolean isInIgnoreOccurrenceContext(DetailAST ast) { 157 for (DetailAST token = ast; 158 token.getParent() != null; 159 token = token.getParent()) { 160 final int type = token.getType(); 161 if (ignoreOccurrenceContext.get(type)) { 162 return true; 163 } 164 } 165 return false; 166 } 167 168 @Override 169 public void beginTree(DetailAST rootAST) { 170 super.beginTree(rootAST); 171 stringMap.clear(); 172 } 173 174 @Override 175 public void finishTree(DetailAST rootAST) { 176 for (Map.Entry<String, List<StringInfo>> stringListEntry : stringMap.entrySet()) { 177 final List<StringInfo> hits = stringListEntry.getValue(); 178 if (hits.size() > allowedDuplicates) { 179 final StringInfo firstFinding = hits.get(0); 180 final int line = firstFinding.getLine(); 181 final int col = firstFinding.getCol(); 182 log(line, col, MSG_KEY, stringListEntry.getKey(), hits.size()); 183 } 184 } 185 } 186 187 /** 188 * This class contains information about where a string was found. 189 */ 190 private static final class StringInfo { 191 /** 192 * Line of finding. 193 */ 194 private final int line; 195 /** 196 * Column of finding. 197 */ 198 private final int col; 199 200 /** 201 * Creates information about a string position. 202 * @param line int 203 * @param col int 204 */ 205 StringInfo(int line, int col) { 206 this.line = line; 207 this.col = col; 208 } 209 210 /** 211 * The line where a string was found. 212 * @return int Line of the string. 213 */ 214 private int getLine() { 215 return line; 216 } 217 218 /** 219 * The column where a string was found. 220 * @return int Column of the string. 221 */ 222 private int getCol() { 223 return col; 224 } 225 } 226 227}