View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.nio.file.Files;
26  import java.util.ArrayList;
27  import java.util.Collections;
28  import java.util.Enumeration;
29  import java.util.Iterator;
30  import java.util.List;
31  import java.util.Properties;
32  import java.util.regex.Matcher;
33  import java.util.regex.Pattern;
34  
35  import com.puppycrawl.tools.checkstyle.StatelessCheck;
36  import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
37  import com.puppycrawl.tools.checkstyle.api.FileText;
38  
39  /**
40   * <p>Detects if keys in properties files are in correct order.</p>
41   * <p>
42   *   Rationale: Sorted properties make it easy for people to find required properties by name
43   *   in file. This makes it easier to merge. While there are no problems at runtime.
44   *   This check is valuable only on files with string resources where order of lines
45   *   does not matter at all, but this can be improved.
46   *   E.g.: checkstyle/src/main/resources/com/puppycrawl/tools/checkstyle/messages.properties
47   *   You may suppress warnings of this check for files that have a logical structure like
48   *   build files or log4j configuration files. See SuppressionFilter.
49   *   {@code
50   *   &lt;suppress checks="OrderedProperties"
51   *     files="log4j.properties|ResourceBundle/Bug.*.properties|logging.properties"/&gt;
52   *   }
53   * </p>
54   * <p>Known limitation: The key should not contain a newline.
55   * The string compare will work, but not the line number reporting.</p>
56   * <ul><li>
57   * Property {@code fileExtensions} - Specify the file extensions of the files to process.
58   * Type is {@code java.lang.String[]}.
59   * Default value is {@code .properties}.
60   * </li></ul>
61   * <p>
62   * Parent is {@code com.puppycrawl.tools.checkstyle.Checker}
63   * </p>
64   * <p>
65   * Violation Message Keys:
66   * </p>
67   * <ul>
68   * <li>
69   * {@code properties.notSorted.property}
70   * </li>
71   * <li>
72   * {@code unable.open.cause}
73   * </li>
74   * </ul>
75   *
76   * @since 8.22
77   */
78  @StatelessCheck
79  public class OrderedPropertiesCheck extends AbstractFileSetCheck {
80  
81      /**
82       * Localization key for check violation.
83       */
84      public static final String MSG_KEY = "properties.notSorted.property";
85      /**
86       * Localization key for IO exception occurred on file open.
87       */
88      public static final String MSG_IO_EXCEPTION_KEY = "unable.open.cause";
89      /**
90       * Pattern matching single space.
91       */
92      private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
93  
94      /**
95       * Construct the check with default values.
96       */
97      public OrderedPropertiesCheck() {
98          setFileExtensions("properties");
99      }
100 
101     /**
102      * Processes the file and check order.
103      *
104      * @param file the file to be processed
105      * @param fileText the contents of the file.
106      */
107     @Override
108     protected void processFiltered(File file, FileText fileText) {
109         final SequencedProperties properties = new SequencedProperties();
110         try (InputStream inputStream = Files.newInputStream(file.toPath())) {
111             properties.load(inputStream);
112         }
113         catch (IOException | IllegalArgumentException ex) {
114             log(1, MSG_IO_EXCEPTION_KEY, file.getPath(), ex.getLocalizedMessage());
115         }
116 
117         String previousProp = "";
118         int startLineNo = 0;
119 
120         final Iterator<Object> propertyIterator = properties.keys().asIterator();
121 
122         while (propertyIterator.hasNext()) {
123 
124             final String propKey = (String) propertyIterator.next();
125 
126             if (String.CASE_INSENSITIVE_ORDER.compare(previousProp, propKey) > 0) {
127 
128                 final int lineNo = getLineNumber(startLineNo, fileText, previousProp, propKey);
129                 log(lineNo + 1, MSG_KEY, propKey, previousProp);
130                 // start searching at position of the last reported validation
131                 startLineNo = lineNo;
132             }
133 
134             previousProp = propKey;
135         }
136     }
137 
138     /**
139      * Method returns the index number where the key is detected (starting at 0).
140      * To assure that we get the correct line it starts at the point
141      * of the last occurrence.
142      * Also, the previousProp should be in file before propKey.
143      *
144      * @param startLineNo start searching at line
145      * @param fileText {@link FileText} object contains the lines to process
146      * @param previousProp key name found last iteration, works only if valid
147      * @param propKey key name to look for
148      * @return index number of first occurrence. If no key found in properties file, 0 is returned
149      */
150     private static int getLineNumber(int startLineNo, FileText fileText,
151                                      String previousProp, String propKey) {
152         final int indexOfPreviousProp = getIndex(startLineNo, fileText, previousProp);
153         return getIndex(indexOfPreviousProp, fileText, propKey);
154     }
155 
156     /**
157      * Inner method to get the index number of the position of keyName.
158      *
159      * @param startLineNo start searching at line
160      * @param fileText {@link FileText} object contains the lines to process
161      * @param keyName key name to look for
162      * @return index number of first occurrence. If no key found in properties file, 0 is returned
163      */
164     private static int getIndex(int startLineNo, FileText fileText, String keyName) {
165         final Pattern keyPattern = getKeyPattern(keyName);
166         int indexNumber = 0;
167         final Matcher matcher = keyPattern.matcher("");
168         for (int index = startLineNo; index < fileText.size(); index++) {
169             final String line = fileText.get(index);
170             matcher.reset(line);
171             if (matcher.matches()) {
172                 indexNumber = index;
173                 break;
174             }
175         }
176         return indexNumber;
177     }
178 
179     /**
180      * Method returns regular expression pattern given key name.
181      *
182      * @param keyName
183      *            key name to look for
184      * @return regular expression pattern given key name
185      */
186     private static Pattern getKeyPattern(String keyName) {
187         final String keyPatternString = "^" + SPACE_PATTERN.matcher(keyName)
188                 .replaceAll(Matcher.quoteReplacement("\\\\ ")) + "[\\s:=].*";
189         return Pattern.compile(keyPatternString);
190     }
191 
192     /**
193      * Private property implementation that keeps order of properties like in file.
194      *
195      * @noinspection ClassExtendsConcreteCollection
196      * @noinspectionreason ClassExtendsConcreteCollection - we require order from
197      *      file to be maintained by {@code put} method
198      */
199     private static final class SequencedProperties extends Properties {
200 
201         /** A unique serial version identifier. */
202         private static final long serialVersionUID = 1L;
203 
204         /**
205          * Holding the keys in the same order as 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 Enumeration<Object> keys() {
214             return Collections.enumeration(keyList);
215         }
216 
217         /**
218          * Puts the value into list by its key.
219          *
220          * @param key the hashtable key
221          * @param value the value
222          * @return the previous value of the specified key in this hashtable,
223          *      or null if it did not have one
224          * @throws NullPointerException - if the key or value is null
225          */
226         @Override
227         public synchronized Object put(Object key, Object value) {
228             keyList.add(key);
229 
230             return null;
231         }
232     }
233 }