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