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