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