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