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