001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2020 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; 021 022import java.io.File; 023import java.io.IOException; 024import java.io.InputStream; 025import java.nio.file.Files; 026import java.util.HashMap; 027import java.util.Map; 028import java.util.Map.Entry; 029import java.util.Properties; 030import java.util.concurrent.atomic.AtomicInteger; 031import java.util.regex.Matcher; 032import java.util.regex.Pattern; 033 034import com.puppycrawl.tools.checkstyle.StatelessCheck; 035import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck; 036import com.puppycrawl.tools.checkstyle.api.FileText; 037 038/** 039 * <p> 040 * Detects duplicated keys in properties files. 041 * </p> 042 * <p> 043 * Rationale: Multiple property keys usually appear after merge or rebase of 044 * several branches. While there are no problems in runtime, there can be a confusion 045 * due to having different values for the duplicated properties. 046 * </p> 047 * <ul> 048 * <li> 049 * Property {@code fileExtensions} - Specify file type extension of the files to check. 050 * Type is {@code java.lang.String[]}. 051 * Default value is {@code .properties}. 052 * </li> 053 * </ul> 054 * <p> 055 * To configure the check: 056 * </p> 057 * <pre> 058 * <module name="UniqueProperties"> 059 * <property name="fileExtensions" value="properties" /> 060 * </module> 061 * </pre> 062 * <p> 063 * Parent is {@code com.puppycrawl.tools.checkstyle.Checker} 064 * </p> 065 * <p> 066 * Violation Message Keys: 067 * </p> 068 * <ul> 069 * <li> 070 * {@code properties.duplicate.property} 071 * </li> 072 * <li> 073 * {@code unable.open.cause} 074 * </li> 075 * </ul> 076 * 077 * @since 5.7 078 */ 079@StatelessCheck 080public class UniquePropertiesCheck extends AbstractFileSetCheck { 081 082 /** 083 * Localization key for check violation. 084 */ 085 public static final String MSG_KEY = "properties.duplicate.property"; 086 /** 087 * Localization key for IO exception occurred on file open. 088 */ 089 public static final String MSG_IO_EXCEPTION_KEY = "unable.open.cause"; 090 091 /** 092 * Pattern matching single space. 093 */ 094 private static final Pattern SPACE_PATTERN = Pattern.compile(" "); 095 096 /** 097 * Construct the check with default values. 098 */ 099 public UniquePropertiesCheck() { 100 setFileExtensions("properties"); 101 } 102 103 @Override 104 protected void processFiltered(File file, FileText fileText) { 105 final UniqueProperties properties = new UniqueProperties(); 106 try (InputStream inputStream = Files.newInputStream(file.toPath())) { 107 properties.load(inputStream); 108 } 109 catch (IOException ex) { 110 log(1, MSG_IO_EXCEPTION_KEY, file.getPath(), 111 ex.getLocalizedMessage()); 112 } 113 114 for (Entry<String, AtomicInteger> duplication : properties 115 .getDuplicatedKeys().entrySet()) { 116 final String keyName = duplication.getKey(); 117 final int lineNumber = getLineNumber(fileText, keyName); 118 // Number of occurrences is number of duplications + 1 119 log(lineNumber, MSG_KEY, keyName, duplication.getValue().get() + 1); 120 } 121 } 122 123 /** 124 * Method returns line number the key is detected in the checked properties 125 * files first. 126 * 127 * @param fileText 128 * {@link FileText} object contains the lines to process 129 * @param keyName 130 * key name to look for 131 * @return line number of first occurrence. If no key found in properties 132 * file, 1 is returned 133 */ 134 private static int getLineNumber(FileText fileText, String keyName) { 135 final Pattern keyPattern = getKeyPattern(keyName); 136 int lineNumber = 1; 137 final Matcher matcher = keyPattern.matcher(""); 138 for (int index = 0; index < fileText.size(); index++) { 139 final String line = fileText.get(index); 140 matcher.reset(line); 141 if (matcher.matches()) { 142 break; 143 } 144 ++lineNumber; 145 } 146 // -1 as check seeks for the first duplicate occurrence in file, 147 // so it cannot be the last line. 148 if (lineNumber > fileText.size() - 1) { 149 lineNumber = 1; 150 } 151 return lineNumber; 152 } 153 154 /** 155 * Method returns regular expression pattern given key name. 156 * 157 * @param keyName 158 * key name to look for 159 * @return regular expression pattern given key name 160 */ 161 private static Pattern getKeyPattern(String keyName) { 162 final String keyPatternString = "^" + SPACE_PATTERN.matcher(keyName) 163 .replaceAll(Matcher.quoteReplacement("\\\\ ")) + "[\\s:=].*$"; 164 return Pattern.compile(keyPatternString); 165 } 166 167 /** 168 * Properties subclass to store duplicated property keys in a separate map. 169 * 170 * @noinspection ClassExtendsConcreteCollection, SerializableHasSerializationMethods 171 */ 172 private static class UniqueProperties extends Properties { 173 174 private static final long serialVersionUID = 1L; 175 /** 176 * Map, holding duplicated keys and their count. Keys are added here only if they 177 * already exist in Properties' inner map. 178 */ 179 private final Map<String, AtomicInteger> duplicatedKeys = new HashMap<>(); 180 181 /** 182 * Puts the value into properties by the key specified. 183 * 184 * @noinspection UseOfPropertiesAsHashtable 185 */ 186 @Override 187 public synchronized Object put(Object key, Object value) { 188 final Object oldValue = super.put(key, value); 189 if (oldValue != null && key instanceof String) { 190 final String keyString = (String) key; 191 192 duplicatedKeys.computeIfAbsent(keyString, empty -> new AtomicInteger(0)) 193 .incrementAndGet(); 194 } 195 return oldValue; 196 } 197 198 /** 199 * Retrieves a collections of duplicated properties keys. 200 * 201 * @return A collection of duplicated keys. 202 */ 203 public Map<String, AtomicInteger> getDuplicatedKeys() { 204 return new HashMap<>(duplicatedKeys); 205 } 206 207 } 208 209}