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.ArrayList; 027import java.util.Collections; 028import java.util.Enumeration; 029import java.util.List; 030import java.util.Properties; 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>Detects if keys in properties files are in correct order.</p> 040 * <p> 041 * Rationale: Sorted properties make it easy for people to find required properties by name 042 * in file. It makes merges more easy. While there are no problems at runtime. 043 * This check is valuable only on files with string resources where order of lines 044 * does not matter at all, but this can be improved. 045 * E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.properties 046 * You may suppress warnings of this check for files that have an logical structure like 047 * build files or log4j configuration files. See SuppressionFilter. 048 * {@code 049 * <suppress checks="OrderedProperties" 050 * files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/> 051 * } 052 * </p> 053 * <p>Known limitation: The key should not contain a newline. 054 * The string compare will work, but not the line number reporting.</p> 055 * <ul> 056 * <li>Property {@code fileExtensions} - Specify file type extension of the files to check. 057 * Default value is {@code .properties}.</li> 058 * </ul> 059 * <p>To configure the check:</p> 060 * <pre><module name="OrderedProperties"/></pre> 061 * <p>Example properties file:</p> 062 * <pre> 063 * A =65 064 * a =97 065 * key =107 than nothing 066 * key.sub =k is 107 and dot is 46 067 * key.png =value - violation 068 * </pre> 069 * <p>We check order of key's only. Here we would like to use an Locale independent 070 * order mechanism, an binary order. The order is case insensitive and ascending.</p> 071 * <ul> 072 * <li>The capital A is on 65 and the lowercase a is on position 97 on the ascii table.</li> 073 * <li>Key and key.sub are in correct order here, because only keys are relevant. 074 * Therefore on line 5 you have only "key" an nothing behind. 075 * On line 6 you have "key." The dot is on position 46 which is higher than nothing. 076 * key.png will reported as violation because "png" comes before "sub".</li> 077 * </ul> 078 * 079 * @since 8.22 080 */ 081@StatelessCheck 082public class OrderedPropertiesCheck extends AbstractFileSetCheck { 083 084 /** 085 * Localization key for check violation. 086 */ 087 public static final String MSG_KEY = "properties.notSorted.property"; 088 /** 089 * Localization key for IO exception occurred on file open. 090 */ 091 public static final String MSG_IO_EXCEPTION_KEY = "unable.open.cause"; 092 /** 093 * Pattern matching single space. 094 */ 095 private static final Pattern SPACE_PATTERN = Pattern.compile(" "); 096 097 /** 098 * Construct the check with default values. 099 */ 100 public OrderedPropertiesCheck() { 101 setFileExtensions("properties"); 102 } 103 104 /** 105 * Processes the file and check order. 106 * @param file the file to be processed 107 * @param fileText the contents of the file. 108 * @noinspection EnumerationCanBeIteration 109 */ 110 @Override 111 protected void processFiltered(File file, FileText fileText) { 112 final SequencedProperties properties = new SequencedProperties(); 113 try (InputStream inputStream = Files.newInputStream(file.toPath())) { 114 properties.load(inputStream); 115 } 116 catch (IOException | IllegalArgumentException ex) { 117 log(1, MSG_IO_EXCEPTION_KEY, file.getPath(), ex.getLocalizedMessage()); 118 } 119 120 String previousProp = ""; 121 int startLineNo = 0; 122 123 final Enumeration<Object> keys = properties.keys(); 124 125 while (keys.hasMoreElements()) { 126 127 final String propKey = (String) keys.nextElement(); 128 129 if (String.CASE_INSENSITIVE_ORDER.compare(previousProp, propKey) > 0) { 130 131 final int lineNo = getLineNumber(startLineNo, fileText, previousProp, propKey); 132 log(lineNo + 1, MSG_KEY, propKey, previousProp); 133 // start searching at position of the last reported validation 134 startLineNo = lineNo; 135 } 136 137 previousProp = propKey; 138 } 139 } 140 141 /** 142 * Method returns the index number where the key is detected (starting at 0). 143 * To assure that we get the correct line it starts at the point 144 * of the last occurrence. 145 * Also the previousProp should be in file before propKey. 146 * 147 * @param startLineNo start searching at line 148 * @param fileText {@link FileText} object contains the lines to process 149 * @param previousProp key name found last iteration, works only if valid 150 * @param propKey key name to look for 151 * @return index number of first occurrence. If no key found in properties file, 0 is returned 152 */ 153 private static int getLineNumber(int startLineNo, FileText fileText, 154 String previousProp, String propKey) { 155 final int indexOfPreviousProp = getIndex(startLineNo, fileText, previousProp); 156 return getIndex(indexOfPreviousProp, fileText, propKey); 157 } 158 159 /** 160 * Inner method to get the index number of the position of keyName. 161 * 162 * @param startLineNo start searching at line 163 * @param fileText {@link FileText} object contains the lines to process 164 * @param keyName key name to look for 165 * @return index number of first occurrence. If no key found in properties file, 0 is returned 166 */ 167 private static int getIndex(int startLineNo, FileText fileText, String keyName) { 168 final Pattern keyPattern = getKeyPattern(keyName); 169 int indexNumber = 0; 170 final Matcher matcher = keyPattern.matcher(""); 171 for (int index = startLineNo; index < fileText.size(); index++) { 172 final String line = fileText.get(index); 173 matcher.reset(line); 174 if (matcher.matches()) { 175 indexNumber = index; 176 break; 177 } 178 } 179 return indexNumber; 180 } 181 182 /** 183 * Method returns regular expression pattern given key name. 184 * 185 * @param keyName 186 * key name to look for 187 * @return regular expression pattern given key name 188 */ 189 private static Pattern getKeyPattern(String keyName) { 190 final String keyPatternString = "^" + SPACE_PATTERN.matcher(keyName) 191 .replaceAll(Matcher.quoteReplacement("\\\\ ")) + "[\\s:=].*"; 192 return Pattern.compile(keyPatternString); 193 } 194 195 /** 196 * Private property implementation that keeps order of properties like in file. 197 * 198 * @noinspection ClassExtendsConcreteCollection, SerializableHasSerializationMethods 199 */ 200 private static class SequencedProperties extends Properties { 201 202 private static final long serialVersionUID = 1L; 203 204 /** 205 * Holding the keys in the same order than in the file. 206 */ 207 private final List<Object> keyList = new ArrayList<>(); 208 209 /** 210 * Returns a copy of the keys. 211 */ 212 @Override 213 public synchronized Enumeration<Object> keys() { 214 return Collections.enumeration(keyList); 215 } 216 217 /** 218 * Puts the value into list by its key. 219 * @noinspection UseOfPropertiesAsHashtable 220 * 221 * @param key the hashtable key 222 * @param value the value 223 * @return the previous value of the specified key in this hashtable, 224 * or null if it did not have one 225 * @throws NullPointerException - if the key or value is null 226 */ 227 @Override 228 public synchronized Object put(Object key, Object value) { 229 keyList.add(key); 230 231 return super.put(key, value); 232 } 233 } 234}