001///////////////////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code and other text files for adherence to a set of rules.
003// Copyright (C) 2001-2024 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 * <p>
040 * Detects duplicated keys in properties files.
041 * </p>
042 * <p>
043 * Rationale: Multiple property keys usually appear after merge or rebase of
044 * several branches. While there are no problems in runtime, there can be a confusion
045 * due to having different values for the duplicated properties.
046 * </p>
047 * <ul>
048 * <li>
049 * Property {@code fileExtensions} - Specify the file extensions of the files to process.
050 * Type is {@code java.lang.String[]}.
051 * Default value is {@code .properties}.
052 * </li>
053 * </ul>
054 * <p>
055 * Parent is {@code com.puppycrawl.tools.checkstyle.Checker}
056 * </p>
057 * <p>
058 * Violation Message Keys:
059 * </p>
060 * <ul>
061 * <li>
062 * {@code properties.duplicate.property}
063 * </li>
064 * <li>
065 * {@code unable.open.cause}
066 * </li>
067 * </ul>
068 *
069 * @since 5.7
070 */
071@StatelessCheck
072public class UniquePropertiesCheck extends AbstractFileSetCheck {
073
074    /**
075     * Localization key for check violation.
076     */
077    public static final String MSG_KEY = "properties.duplicate.property";
078    /**
079     * Localization key for IO exception occurred on file open.
080     */
081    public static final String MSG_IO_EXCEPTION_KEY = "unable.open.cause";
082
083    /**
084     * Pattern matching single space.
085     */
086    private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
087
088    /**
089     * Construct the check with default values.
090     */
091    public UniquePropertiesCheck() {
092        setFileExtensions("properties");
093    }
094
095    @Override
096    protected void processFiltered(File file, FileText fileText) {
097        final UniqueProperties properties = new UniqueProperties();
098        try (InputStream inputStream = Files.newInputStream(file.toPath())) {
099            properties.load(inputStream);
100        }
101        catch (IOException ex) {
102            log(1, MSG_IO_EXCEPTION_KEY, file.getPath(),
103                    ex.getLocalizedMessage());
104        }
105
106        for (Entry<String, AtomicInteger> duplication : properties
107                .getDuplicatedKeys().entrySet()) {
108            final String keyName = duplication.getKey();
109            final int lineNumber = getLineNumber(fileText, keyName);
110            // Number of occurrences is number of duplications + 1
111            log(lineNumber, MSG_KEY, keyName, duplication.getValue().get() + 1);
112        }
113    }
114
115    /**
116     * Method returns line number the key is detected in the checked properties
117     * files first.
118     *
119     * @param fileText
120     *            {@link FileText} object contains the lines to process
121     * @param keyName
122     *            key name to look for
123     * @return line number of first occurrence. If no key found in properties
124     *         file, 1 is returned
125     */
126    private static int getLineNumber(FileText fileText, String keyName) {
127        final Pattern keyPattern = getKeyPattern(keyName);
128        int lineNumber = 1;
129        final Matcher matcher = keyPattern.matcher("");
130        for (int index = 0; index < fileText.size(); index++) {
131            final String line = fileText.get(index);
132            matcher.reset(line);
133            if (matcher.matches()) {
134                break;
135            }
136            ++lineNumber;
137        }
138        // -1 as check seeks for the first duplicate occurrence in file,
139        // so it cannot be the last line.
140        if (lineNumber > fileText.size() - 1) {
141            lineNumber = 1;
142        }
143        return lineNumber;
144    }
145
146    /**
147     * Method returns regular expression pattern given key name.
148     *
149     * @param keyName
150     *            key name to look for
151     * @return regular expression pattern given key name
152     */
153    private static Pattern getKeyPattern(String keyName) {
154        final String keyPatternString = "^" + SPACE_PATTERN.matcher(keyName)
155                .replaceAll(Matcher.quoteReplacement("\\\\ ")) + "[\\s:=].*$";
156        return Pattern.compile(keyPatternString);
157    }
158
159    /**
160     * Properties subclass to store duplicated property keys in a separate map.
161     *
162     * @noinspection ClassExtendsConcreteCollection
163     * @noinspectionreason ClassExtendsConcreteCollection - we require custom
164     *      {@code put} method to find duplicate keys
165     */
166    private static final class UniqueProperties extends Properties {
167
168        /** A unique serial version identifier. */
169        private static final long serialVersionUID = 1L;
170        /**
171         * Map, holding duplicated keys and their count. Keys are added here only if they
172         * already exist in Properties' inner map.
173         */
174        private final Map<String, AtomicInteger> duplicatedKeys = new HashMap<>();
175
176        /**
177         * Puts the value into properties by the key specified.
178         */
179        @Override
180        public synchronized Object put(Object key, Object value) {
181            final Object oldValue = super.put(key, value);
182            if (oldValue != null && key instanceof String) {
183                final String keyString = (String) key;
184
185                duplicatedKeys.computeIfAbsent(keyString, empty -> new AtomicInteger(0))
186                        .incrementAndGet();
187            }
188            return oldValue;
189        }
190
191        /**
192         * Retrieves a collections of duplicated properties keys.
193         *
194         * @return A collection of duplicated keys.
195         */
196        public Map<String, AtomicInteger> getDuplicatedKeys() {
197            return new HashMap<>(duplicatedKeys);
198        }
199
200    }
201
202}