View Javadoc
1   ///////////////////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code and other text files for adherence to a set of rules.
3   // Copyright (C) 2001-2026 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.api;
21  
22  import java.text.MessageFormat;
23  import java.util.Arrays;
24  import java.util.Locale;
25  import java.util.Objects;
26  
27  import javax.annotation.Nullable;
28  
29  import com.puppycrawl.tools.checkstyle.LocalizedMessage;
30  
31  /**
32   * Represents a violation that can be localised. The translations come from
33   * message.properties files. The underlying implementation uses java.text.MessageFormat.
34   *
35   * @noinspection ClassWithTooManyConstructors
36   * @noinspectionreason ClassWithTooManyConstructors - immutable nature of class requires a
37   *      bunch of constructors
38   */
39  public final class Violation implements Comparable<Violation> {
40  
41      /** The default severity level if one is not specified. */
42      private static final SeverityLevel DEFAULT_SEVERITY = SeverityLevel.ERROR;
43  
44      /** The line number. */
45      private final int lineNo;
46      /** The column number. */
47      private final int columnNo;
48      /** The column char index. */
49      private final int columnCharIndex;
50      /** The token type constant. See {@link TokenTypes}. */
51      private final int tokenType;
52  
53      /** The severity level. */
54      private final SeverityLevel severityLevel;
55  
56      /** The id of the module generating the violation. */
57      private final String moduleId;
58  
59      /** Key for the violation format. */
60      private final String key;
61  
62      /** Arguments for MessageFormat. */
63      private final Object[] args;
64  
65      /** Name of the resource bundle to get violations from. */
66      private final String bundle;
67  
68      /** Class of the source for this Violation. */
69      private final Class<?> sourceClass;
70  
71      /** A custom violation overriding the default violation from the bundle. */
72      @Nullable
73      private final String customMessage;
74  
75      /**
76       * Creates a new {@code Violation} instance. The column number defaults to 0.
77       *
78       * @param lineNo line number associated with the violation
79       * @param bundle name of a resource bundle that contains audit event violations
80       * @param key the key to locate the translation
81       * @param args arguments for the translation
82       * @param moduleId the id of the module the violation is associated with
83       * @param sourceClass the name of the source for the violation
84       * @param customMessage optional custom violation overriding the default
85       */
86      public Violation(
87          int lineNo,
88          String bundle,
89          String key,
90          Object[] args,
91          String moduleId,
92          Class<?> sourceClass,
93          @Nullable String customMessage) {
94          this(lineNo, 0, bundle, key, args, DEFAULT_SEVERITY, moduleId,
95                  sourceClass, customMessage);
96      }
97  
98      /**
99       * Creates a new {@code Violation} instance.
100      *
101      * @param lineNo line number associated with the violation
102      * @param columnNo column number associated with the violation
103      * @param bundle resource bundle name
104      * @param key the key to locate the translation
105      * @param args arguments for the translation
106      * @param moduleId the id of the module the violation is associated with
107      * @param sourceClass the Class that is the source of the violation
108      * @param customMessage optional custom violation overriding the default
109      * @noinspection ConstructorWithTooManyParameters
110      * @noinspectionreason ConstructorWithTooManyParameters - immutable class requires a large
111      *      number of arguments
112      */
113     // -@cs[ParameterNumber] Class is immutable, we need that amount of arguments.
114     public Violation(int lineNo,
115                             int columnNo,
116                             String bundle,
117                             String key,
118                             Object[] args,
119                             String moduleId,
120                             Class<?> sourceClass,
121                             @Nullable String customMessage) {
122         this(lineNo,
123                 columnNo,
124              bundle,
125              key,
126              args,
127              DEFAULT_SEVERITY,
128              moduleId,
129              sourceClass,
130              customMessage);
131     }
132 
133     /**
134      * Creates a new {@code Violation} instance.
135      *
136      * @param lineNo line number associated with the violation
137      * @param bundle resource bundle name
138      * @param key the key to locate the translation
139      * @param args arguments for the translation
140      * @param severityLevel severity level for the violation
141      * @param moduleId the id of the module the violation is associated with
142      * @param sourceClass the source class for the violation
143      * @param customMessage optional custom violation overriding the default
144      * @noinspection ConstructorWithTooManyParameters
145      * @noinspectionreason ConstructorWithTooManyParameters - immutable class requires a large
146      *      number of arguments
147      */
148     // -@cs[ParameterNumber] Class is immutable, we need that amount of arguments.
149     public Violation(int lineNo,
150                             String bundle,
151                             String key,
152                             Object[] args,
153                             SeverityLevel severityLevel,
154                             String moduleId,
155                             Class<?> sourceClass,
156                             @Nullable String customMessage) {
157         this(lineNo, 0, bundle, key, args, severityLevel, moduleId,
158                 sourceClass, customMessage);
159     }
160 
161     /**
162      * Creates a new {@code Violation} instance.
163      *
164      * @param lineNo line number associated with the violation
165      * @param columnNo column number associated with the violation
166      * @param bundle resource bundle name
167      * @param key the key to locate the translation
168      * @param args arguments for the translation
169      * @param severityLevel severity level for the violation
170      * @param moduleId the id of the module the violation is associated with
171      * @param sourceClass the Class that is the source of the violation
172      * @param customMessage optional custom violation overriding the default
173      * @noinspection ConstructorWithTooManyParameters
174      * @noinspectionreason ConstructorWithTooManyParameters - immutable class requires a large
175      *      number of arguments
176      */
177     // -@cs[ParameterNumber] Class is immutable, we need that amount of arguments.
178     public Violation(int lineNo,
179                             int columnNo,
180                             String bundle,
181                             String key,
182                             Object[] args,
183                             SeverityLevel severityLevel,
184                             String moduleId,
185                             Class<?> sourceClass,
186                             @Nullable String customMessage) {
187         this(lineNo, columnNo, 0, bundle, key, args, severityLevel, moduleId, sourceClass,
188                 customMessage);
189     }
190 
191     /**
192      * Creates a new {@code Violation} instance.
193      *
194      * @param lineNo line number associated with the violation
195      * @param columnNo column number associated with the violation
196      * @param tokenType token type of the event associated with violation. See {@link TokenTypes}
197      * @param bundle resource bundle name
198      * @param key the key to locate the translation
199      * @param args arguments for the translation
200      * @param severityLevel severity level for the violation
201      * @param moduleId the id of the module the violation is associated with
202      * @param sourceClass the Class that is the source of the violation
203      * @param customMessage optional custom violation overriding the default
204      * @noinspection ConstructorWithTooManyParameters
205      * @noinspectionreason ConstructorWithTooManyParameters - immutable class requires a large
206      *      number of arguments
207      */
208     // -@cs[ParameterNumber] Class is immutable, we need that amount of arguments.
209     public Violation(int lineNo,
210                             int columnNo,
211                             int tokenType,
212                             String bundle,
213                             String key,
214                             Object[] args,
215                             SeverityLevel severityLevel,
216                             String moduleId,
217                             Class<?> sourceClass,
218                             @Nullable String customMessage) {
219         this(lineNo, columnNo, columnNo, tokenType, bundle, key, args, severityLevel, moduleId,
220                 sourceClass, customMessage);
221     }
222 
223     /**
224      * Creates a new {@code Violation} instance.
225      *
226      * @param lineNo line number associated with the violation
227      * @param columnNo column number associated with the violation
228      * @param columnCharIndex column char index associated with the violation
229      * @param tokenType token type of the event associated with violation. See {@link TokenTypes}
230      * @param bundle resource bundle name
231      * @param key the key to locate the translation
232      * @param args arguments for the translation
233      * @param severityLevel severity level for the violation
234      * @param moduleId the id of the module the violation is associated with
235      * @param sourceClass the Class that is the source of the violation
236      * @param customMessage optional custom violation overriding the default
237      * @noinspection ConstructorWithTooManyParameters
238      * @noinspectionreason ConstructorWithTooManyParameters - immutable class requires a large
239      *      number of arguments
240      */
241     // -@cs[ParameterNumber] Class is immutable, we need that amount of arguments.
242     public Violation(int lineNo,
243                             int columnNo,
244                             int columnCharIndex,
245                             int tokenType,
246                             String bundle,
247                             String key,
248                             Object[] args,
249                             SeverityLevel severityLevel,
250                             String moduleId,
251                             Class<?> sourceClass,
252                             @Nullable String customMessage) {
253         this.lineNo = lineNo;
254         this.columnNo = columnNo;
255         this.columnCharIndex = columnCharIndex;
256         this.tokenType = tokenType;
257         this.key = key;
258 
259         if (args == null) {
260             this.args = null;
261         }
262         else {
263             this.args = copyOfArray(args, args.length);
264         }
265         this.bundle = bundle;
266         this.severityLevel = severityLevel;
267         this.moduleId = moduleId;
268         this.sourceClass = sourceClass;
269         this.customMessage = customMessage;
270     }
271 
272     /**
273      * Creates a copy of array.
274      *
275      * @param <T> The type of array
276      * @param array Array to create a copy of
277      * @param length length of array
278      * @return copy of array
279      */
280     private static <T> T[] copyOfArray(T[] array, int length) {
281         return Arrays.copyOf(array, length);
282     }
283 
284     /**
285      * Gets the line number.
286      *
287      * @return the line number
288      */
289     public int getLineNo() {
290         return lineNo;
291     }
292 
293     /**
294      * Gets the column number.
295      *
296      * @return the column number
297      */
298     public int getColumnNo() {
299         return columnNo;
300     }
301 
302     /**
303      * Gets the column char index.
304      *
305      * @return the column char index
306      */
307     public int getColumnCharIndex() {
308         return columnCharIndex;
309     }
310 
311     /**
312      * Gets the token type.
313      *
314      * @return the token type
315      */
316     public int getTokenType() {
317         return tokenType;
318     }
319 
320     /**
321      * Gets the severity level.
322      *
323      * @return the severity level
324      */
325     public SeverityLevel getSeverityLevel() {
326         return severityLevel;
327     }
328 
329     /**
330      * Returns id of module.
331      *
332      * @return the module identifier.
333      */
334     public String getModuleId() {
335         return moduleId;
336     }
337 
338     /**
339      * Returns the violation key to locate the translation, can also be used
340      * in IDE plugins to map audit event violations to corrective actions.
341      *
342      * @return the violation key
343      */
344     public String getKey() {
345         return key;
346     }
347 
348     /**
349      * Gets the name of the source for this Violation.
350      *
351      * @return the name of the source for this Violation
352      */
353     public String getSourceName() {
354         return sourceClass.getName();
355     }
356 
357     /**
358      * Indicates whether some other object is "equal to" this one.
359      * Suppression on enumeration is needed so code stays consistent.
360      *
361      * @noinspection EqualsCalledOnEnumConstant
362      * @noinspectionreason EqualsCalledOnEnumConstant - enumeration is needed to keep
363      *      code consistent
364      */
365     // -@cs[CyclomaticComplexity] equals - a lot of fields to check.
366     @Override
367     @SuppressWarnings("OverlyComplexBooleanExpression")
368     public boolean equals(Object object) {
369         if (this == object) {
370             return true;
371         }
372         if (object == null || getClass() != object.getClass()) {
373             return false;
374         }
375         final Violation violation = (Violation) object;
376         return lineNo == violation.lineNo
377                 && columnNo == violation.columnNo
378                 && columnCharIndex == violation.columnCharIndex
379                 && tokenType == violation.tokenType
380                 && Objects.equals(severityLevel, violation.severityLevel)
381                 && Objects.equals(moduleId, violation.moduleId)
382                 && Objects.equals(key, violation.key)
383                 && Objects.equals(bundle, violation.bundle)
384                 && Objects.equals(sourceClass, violation.sourceClass)
385                 && Objects.equals(customMessage, violation.customMessage)
386                 && Arrays.equals(args, violation.args);
387     }
388 
389     @Override
390     public int hashCode() {
391         return Objects.hash(lineNo, columnNo, columnCharIndex, tokenType, severityLevel, moduleId,
392                 key, bundle, sourceClass, customMessage, Arrays.hashCode(args));
393     }
394 
395     ////////////////////////////////////////////////////////////////////////////
396     // Interface Comparable methods
397     ////////////////////////////////////////////////////////////////////////////
398 
399     /**
400      * {@inheritDoc}
401      *
402      * <p>The same fields as in {@link #equals(Object)} take part in the
403      * comparison, so that a result of zero is consistent with equality, as the
404      * {@link Comparable} contract recommends. Line, column, module id, source
405      * class, and the rendered violation stay the leading criteria; the
406      * remaining fields only break a tie between violations that would
407      * otherwise be reported at the same place with the same text.
408      */
409     @Override
410     public int compareTo(Violation other) {
411         int result = compareLocation(other);
412         if (result == 0) {
413             result = compareContent(other);
414         }
415         return result;
416     }
417 
418     /**
419      * Compares the place and the text a violation is reported with.
420      *
421      * @param other the violation to compare against
422      * @return the value {@code 0} if the violations are reported the same way
423      */
424     private int compareLocation(Violation other) {
425         int result = Integer.compare(lineNo, other.lineNo);
426         if (result == 0) {
427             result = Integer.compare(columnNo, other.columnNo);
428         }
429         if (result == 0) {
430             result = compareNullable(moduleId, other.moduleId);
431         }
432         if (result == 0) {
433             result = compareNullable(getSourceClassName(), other.getSourceClassName());
434         }
435         if (result == 0) {
436             result = getViolation().compareTo(other.getViolation());
437         }
438         return result;
439     }
440 
441     /**
442      * Compares the fields that two violations reported at the same place with
443      * the same text can still differ in.
444      *
445      * @param other the violation to compare against
446      * @return the value {@code 0} if the violations carry the same content
447      */
448     private int compareContent(Violation other) {
449         int result = Integer.compare(columnCharIndex, other.columnCharIndex);
450         if (result == 0) {
451             result = Integer.compare(tokenType, other.tokenType);
452         }
453         if (result == 0) {
454             result = severityLevel.compareTo(other.severityLevel);
455         }
456         if (result == 0) {
457             result = compareNullable(key, other.key);
458         }
459         if (result == 0) {
460             result = compareNullable(bundle, other.bundle);
461         }
462         if (result == 0) {
463             result = compareNullable(customMessage, other.customMessage);
464         }
465         if (result == 0) {
466             result = Arrays.deepToString(args).compareTo(Arrays.deepToString(other.args));
467         }
468         return result;
469     }
470 
471     /**
472      * Compares two values that may be {@code null}, ordering {@code null} before any other value.
473      *
474      * @param first the first value
475      * @param second the second value
476      * @return a negative integer, zero, or a positive integer as the first
477      *     value is less than, equal to, or greater than the second
478      */
479     private static int compareNullable(@Nullable String first, @Nullable String second) {
480         final int result;
481         if (first == null) {
482             if (second == null) {
483                 result = 0;
484             }
485             else {
486                 result = -1;
487             }
488         }
489         else if (second == null) {
490             result = 1;
491         }
492         else {
493             result = first.compareTo(second);
494         }
495         return result;
496     }
497 
498     /**
499      * Gets the source class name or {@code null} when no source class is set.
500      *
501      * @return the source class name or {@code null}
502      */
503     @Nullable
504     private String getSourceClassName() {
505         final String name;
506         if (sourceClass == null) {
507             name = null;
508         }
509         else {
510             name = sourceClass.getName();
511         }
512         return name;
513     }
514 
515     /**
516      * Gets the translated violation.
517      *
518      * @return the translated violation
519      */
520     public String getViolation() {
521         final String violation;
522 
523         if (customMessage != null) {
524             violation = new MessageFormat(customMessage, Locale.ROOT).format(args);
525         }
526         else {
527             violation = new LocalizedMessage(bundle, sourceClass, key, args).getMessage();
528         }
529 
530         return violation;
531     }
532 
533 }