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