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