View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2024 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ///////////////////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle.checks;
21  
22  import java.io.File;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.nio.file.Files;
26  import java.util.HashMap;
27  import java.util.Map;
28  import java.util.Map.Entry;
29  import java.util.Properties;
30  import java.util.concurrent.atomic.AtomicInteger;
31  import java.util.regex.Matcher;
32  import java.util.regex.Pattern;
33  
34  import com.puppycrawl.tools.checkstyle.StatelessCheck;
35  import com.puppycrawl.tools.checkstyle.api.AbstractFileSetCheck;
36  import com.puppycrawl.tools.checkstyle.api.FileText;
37  
38  /**
39   * <p>
40   * Detects duplicated keys in properties files.
41   * </p>
42   * <p>
43   * Rationale: Multiple property keys usually appear after merge or rebase of
44   * several branches. While there are no problems in runtime, there can be a confusion
45   * due to having different values for the duplicated properties.
46   * </p>
47   * <ul>
48   * <li>
49   * Property {@code fileExtensions} - Specify the file extensions of the files to process.
50   * Type is {@code java.lang.String[]}.
51   * Default value is {@code .properties}.
52   * </li>
53   * </ul>
54   * <p>
55   * Parent is {@code com.puppycrawl.tools.checkstyle.Checker}
56   * </p>
57   * <p>
58   * Violation Message Keys:
59   * </p>
60   * <ul>
61   * <li>
62   * {@code properties.duplicate.property}
63   * </li>
64   * <li>
65   * {@code unable.open.cause}
66   * </li>
67   * </ul>
68   *
69   * @since 5.7
70   */
71  @StatelessCheck
72  public class UniquePropertiesCheck extends AbstractFileSetCheck {
73  
74      /**
75       * Localization key for check violation.
76       */
77      public static final String MSG_KEY = "properties.duplicate.property";
78      /**
79       * Localization key for IO exception occurred on file open.
80       */
81      public static final String MSG_IO_EXCEPTION_KEY = "unable.open.cause";
82  
83      /**
84       * Pattern matching single space.
85       */
86      private static final Pattern SPACE_PATTERN = Pattern.compile(" ");
87  
88      /**
89       * Construct the check with default values.
90       */
91      public UniquePropertiesCheck() {
92          setFileExtensions("properties");
93      }
94  
95      @Override
96      protected void processFiltered(File file, FileText fileText) {
97          final UniqueProperties properties = new UniqueProperties();
98          try (InputStream inputStream = Files.newInputStream(file.toPath())) {
99              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 }