SeverityMatchFilter

Description

Since Checkstyle 3.2

Filter SeverityMatchFilter decides audit events according to the severity level of the event.

Properties

name description type default value since
severity the severity level of this filter Severity error 3.2
acceptOnMatch If acceptOnMatch is true, then the filter accepts an audit event if and only if there is a match between the event's severity level and property severity. If acceptOnMatch is false, then the filter accepts an audit event if and only if there is not a match between the event's severity level and property severity. Boolean true 3.2

Examples

For example, the following configuration fragment directs the Checker to not report audit events with severity level info:

<module name="SeverityMatchFilter">
  <property name="severity" value="info"/>
  <property name="acceptOnMatch" value="false"/>
</module>
          

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker

SuppressionCommentFilter

Description

Since Checkstyle 3.5

Filter SuppressionCommentFilter uses pairs of comments to suppress audit events.

Rationale: Sometimes there are legitimate reasons for violating a check. When this is a matter of the code in question and not personal preference, the best place to override the policy is in the code itself. Semi-structured comments can be associated with the check. This is sometimes superior to a separate suppressions file, which must be kept up-to-date as the source file is edited.

Note that the suppression comment should be put before the violation. You can use more than one suppression comment each on separate line.

Properties

name description type default value since
offCommentFormat comment pattern to trigger filter to begin suppression Regular Expression "CHECKSTYLE:OFF" 3.5
onCommentFormat comment pattern to trigger filter to end suppression Regular Expression "CHECKSTYLE:ON" 3.5
checkFormat check pattern to suppress Regular Expression ".*" 3.5
messageFormat message pattern to suppress Regular Expression null 3.5
checkCPP whether to check C++ style comments (//) Boolean true 3.5
checkC whether to check C style comments (/* ... */) Boolean true 3.5

offCommentFormat and onCommentFormat must have equal paren counts.

Examples

To configure a filter to suppress audit events between a comment containing CHECKSTYLE:OFF and a comment containing CHECKSTYLE:ON:

<module name="TreeWalker">
              ...
  <module name="SuppressionCommentFilter"/>
              ...
</module>
          

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CODE and a comment containing line END GENERATED CODE:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="BEGIN GENERATED CODE"/>
  <property name="onCommentFormat" value="END GENERATED CODE"/>
</module>
          
//BEGIN GENERATED CODE
@Override
public boolean equals(Object obj) { ... } // No violation events will be reported

@Override
public int hashCode() { ... } // No violation events will be reported
//END GENERATED CODE
. . .
          

To configure a filter so that // stop constant check and // resume constant check marks legitimate constant names:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="stop constant check"/>
  <property name="onCommentFormat" value="resume constant check"/>
  <property name="checkFormat" value="ConstantNameCheck"/>
</module>
          
//stop constant check
public static final int someConstant; // won't warn here
//resume constant check
public static final int someConstant; // will warn here as constant's name doesn't match the
// pattern "^[A-Z][A-Z0-9]*$"
          

To configure a filter so that UNUSED OFF: var and UNUSED ON: var marks a variable or parameter known not to be used by the code by matching the variable name in the message:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="UNUSED OFF\: (\w+)"/>
  <property name="onCommentFormat" value="UNUSED ON\: (\w+)"/>
  <property name="checkFormat" value="Unused"/>
  <property name="messageFormat" value="^Unused \w+ '$1'.$"/>
</module>
          
private static void foo(int a, int b) // UNUSED OFF: b
{
System.out.println(a);
}

private static void foo1(int a, int b) // UNUSED ON: b
{
System.out.println(a);
}
          

To configure a filter so that name of suppressed check mentioned in comment CSOFF: regexp and CSON: regexp mark a matching check:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/>
  <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/>
  <property name="checkFormat" value="$1"/>
</module>
          
public static final int lowerCaseConstant; // CSOFF: ConstantNameCheck
public static final int lowerCaseConstant1; // CSON: ConstantNameCheck
          

To configure a filter to suppress all audit events between a comment containing CHECKSTYLE_OFF: ALMOST_ALL and a comment containing CHECKSTYLE_OFF: ALMOST_ALL except for the EqualsHashCode check:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="CHECKSTYLE_OFF: ALMOST_ALL"/>
  <property name="onCommentFormat" value="CHECKSTYLE_ON: ALMOST_ALL"/>
  <property name="checkFormat" value="^((?!(EqualsHashCode)).)*$"/>
</module>
          
public static final int array []; // CHECKSTYLE_OFF: ALMOST_ALL
private String [] strArray;
private int array1 []; // CHECKSTYLE_ON: ALMOST_ALL
          

To configure a filter to suppress Check's violation message which matches specified message in messageFormat (so suppression will be not only by Check's name, but by message text additionally, as the same Check could report different by message format violations) between a comment containing stop and comment containing resume:

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="stop"/>
  <property name="onCommentFormat" value="resume"/>
  <property name="checkFormat" value="IllegalTypeCheck"/>
  <property name="messageFormat" value="^Declaring variables, return values or parameters of type 'GregorianCalendar' is not allowed.$"/>
</module>
          

Code before filter above is applied with Check's audit events:

...
GregorianCalendar calendar; // Warning here: Declaring variables, return values or parameters of type 'GregorianCalendar' is not allowed.
HashSet hashSet; // Warning here: Declaring variables, return values or parameters of type 'HashSet' is not allowed.
...
          

Code after filter is applied:

...
//stop
GregorianCalendar calendar; // No warning here as it is suppressed by filter.
HashSet hashSet; // Warning here: Declaring variables, return values or parameters of type 'HashSet' is not allowed.
//resume
...
          

It is possible to specify an ID of checks, so that it can be leveraged by the SuppressionCommentFilter to skip validations. The following examples show how to skip validations near code that is surrounded with // CSOFF <ID> (reason) and // CSON <ID>, where ID is the ID of checks you want to suppress.

Examples of Checkstyle checks configuration:

<module name="RegexpSinglelineJava">
  <property name="id" value="ignore"/>
  <property name="format" value="^.*@Ignore\s*$"/>
  <property name="message" value="@Ignore should have a reason."/>
</module>

<module name="RegexpSinglelineJava">
  <property name="id" value="systemout"/>
  <property name="format" value="^.*System\.(out|err).*$"/>
  <property name="message" value="Don't use System.out/err, use SLF4J instead."/>
</module>
          

Example of SuppressionCommentFilter configuration (checkFormat which is set to '$1' points that ID of the checks is in the first group of offCommentFormat and onCommentFormat regular expressions):

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="CSOFF (\w+) \(\w+\)"/>
  <property name="onCommentFormat" value="CSON (\w+)"/>
  <property name="checkFormat" value="$1"/>
</module>
          
// CSOFF ignore (test has not been implemented yet)
@Ignore // should NOT fail RegexpSinglelineJava
@Test
public void testMethod() { }
// CSON ignore

// CSOFF systemout (debug)
public static void foo() {
    System.out.println("Debug info."); // should NOT fail RegexpSinglelineJava
}
// CSON systemout
          

Example of how to configure the check to suppress more than one checks.

<module name="SuppressionCommentFilter">
  <property name="offCommentFormat" value="@cs-\: ([\w\|]+)"/>
  <property name="checkFormat" value="$1"/>
</module>
          
// @cs-: ClassDataAbstractionCoupling
// @cs-: MagicNumber
@Service // no violations from ClassDataAbstractionCoupling here
@Transactional
public class UserService {
  private int value = 10022; // no violations from MagicNumber here
}
          

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

TreeWalker

SuppressionFilter

Description

Since Checkstyle 3.2

Filter SuppressionFilter rejects audit events for Check errors according to a suppressions XML document in a file. If there is no configured suppressions file or the optional is set to true and suppressions file was not found the Filter accepts all audit events.

Properties

name description type default value since
file the location of the suppressions XML document file. The order the location is checked is:
  1. as a filesystem location
  2. if no file found, and the location starts with either http:// or https://, then it is interpreted as a URL
  3. if no file found, then passed to the ClassLoader.getResource() method.
string none 3.2
optional Tells what to do when the file is not existing. If optional is set to false the file must exist, or else it ends with error. On the other hand if optional is true and file is not found, the filter accept all audit events. Boolean false 6.15

Examples

For example, the following configuration fragment directs the Checker to use a SuppressionFilter with suppressions file config/suppressions.xml:

<module name="SuppressionFilter">
  <property name="file" value="config/suppressions.xml"/>
  <property name="optional" value="false"/>
</module>
          

A suppressions XML document contains a set of suppress elements, where each suppress element can have the following attributes:

  • files - a Regular Expression matched against the file name associated with an audit event. It is mandatory.
  • checks - a Regular Expression matched against the name of the check associated with an audit event. Optional if id is specified.
  • id - a string matched against the ID of the check associated with an audit event. Optional if checks is specified.
  • lines - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.
  • columns - a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. It is optional.

Each audit event is checked against each suppress element. It is suppressed if all specified attributes match against the audit event.

You can download template of empty suppression filter here.

The following suppressions XML document directs a SuppressionFilter to reject JavadocStyleCheck errors for lines 82 and 108 to 122 of file AbstractComplexityCheck.java, and MagicNumberCheck errors for line 221 of file JavadocStyleCheck.java:

<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
"-//Puppy Crawl//DTD Suppressions 1.1//EN"
"http://checkstyle.sourceforge.net/dtds/suppressions_1_1.dtd">

<suppressions>
<suppress checks="JavadocStyleCheck"
  files="AbstractComplexityCheck.java"
  lines="82,108-122"/>
<suppress checks="MagicNumberCheck"
  files="JavadocStyleCheck.java"
  lines="221"/>
</suppressions>
          

As another example to suppress Check by module id:

<module name="DescendantToken">
  <property name="id" value="stringEqual"/>
  <property name="tokens" value="EQUAL,NOT_EQUAL"/>
  <property name="limitedTokens" value="STRING_LITERAL"/>
  <property name="maximumNumber" value="0"/>
  <property name="maximumDepth" value="1"/>
</module>

<module name="DescendantToken">
  <property name="id" value="switchNoDefault"/>
  <property name="tokens" value="LITERAL_SWITCH"/>
  <property name="maximumDepth" value="2"/>
  <property name="limitedTokens" value="LITERAL_DEFAULT"/>
  <property name="minimumNumber" value="1"/>
</module>
          

Then the following can be used to suppress only the first check and not the second by using the id attribute:

<suppress id="stringEqual" files="SomeTestCode.java"/>
          

Suppress checks for hidden files and folders:

<suppress files="[/\\]\..+" checks=".*"/>
          

Suppress checks for Maven-generated code:

<suppress files="[/\\]target[/\\]" checks=".*"/>
          

Suppress checks for archives, classes and other binary files:

<suppress files=".+\.(?:jar|zip|war|class|tar|bin)$" checks=".*"/>
          

Suppress checks for image files:

<suppress files=".+\.(?:png|gif|jpg|jpeg)$" checks=".*"/>
          

Suppress checks for non-java files:

<suppress files=".+\.(?:txt|xml|csv|sh|thrift|html|sql|eot|ttf|woff|css|png)$" checks=".*"/>
          

Suppress all checks in generated sources:

<suppress checks=".*" files="com[\\/]mycompany[\\/]app[\\/]gen[\\/]"/>
          

Suppress FileLength check on integration tests in certain folder:

<suppress checks="FileLength" files="com[\\/]mycompany[\\/]app[\\/].*IT.java"/>
          

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker

SuppressWarningsFilter

Description

Since Checkstyle 5.7

Filter SuppressWarningsFilter uses annotations to suppress audit events.

Rationale: Same as for SuppressionCommentFilter. In the contrary to it here, comments are not used comments but the builtin syntax of @SuppressWarnings. This can be perceived as a more elegant solution than using comments. Also this approach maybe supported by various IDE.

Usage: This filter only works in conjunction with a SuppressWarningsHolder, since that check finds the annotations in the Java files and makes them available for the filter. Because of that, a configuration that includes this filter must also include SuppressWarningsHolder as a child module of the TreeWalker. Name of check in annotation is case-insensitive and should be written with any dotted prefix or "Check" suffix removed.

Examples

To configure the check that makes tha annotations available to the filter.

<module name="TreeWalker">
              ...
<module name="SuppressWarningsHolder" />
              ...
</module>
          

To configure filter to suppress audit events for annotations add:

<module name="SuppressWarningsFilter" />
          
@SuppressWarnings({"memberName"})
private int J; // should NOT fail MemberNameCheck

@SuppressWarnings({"MemberName"})
@SuppressWarnings({"NoWhitespaceAfter"})
private int [] ARRAY; // should NOT fail MemberNameCheck and NoWhitespaceAfterCheck
          

It is possible to specify an ID of checks, so that it can be leveraged by the SuppressWarningsFilter to skip validations. The following examples show how to skip validations near code that has @SuppressWarnings("checkstyle:<ID>") or just @SuppressWarnings("<ID>") annotation, where ID is the ID of checks you want to suppress.

Example of Checkstyle check configuration:

<module name="RegexpSinglelineJava">
  <property name="id" value="systemout"/>
  <property name="format" value="^.*System\.(out|err).*$"/>
  <property name="message" value="Don't use System.out/err, use SLF4J instead."/>
</module>
          

To make the annotations available to the filter.

<module name="TreeWalker">
  ...
  <module name="SuppressWarningsHolder" />
  ...
</module>
          

To configure filter to suppress audit events for annotations add:

<module name="SuppressWarningsFilter" />
          
@SuppressWarnings("checkstyle:systemout")
public static void foo() {
  System.out.println("Debug info."); // should NOT fail RegexpSinglelineJava
}
          

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker

SuppressWithNearbyCommentFilter

Description

Since Checkstyle 5.0

Filter SuppressWithNearbyCommentFilter uses individual comments to suppress audit events.

Rationale: Same as SuppressionCommentFilter. Whereas the SuppressionCommentFilter uses matched pairs of filters to turn on/off comment matching, SuppressWithNearbyCommentFilter uses single comments. This requires fewer lines to mark a region, and may be aesthetically preferable in some contexts.

Properties

name description type default value since
commentFormat comment pattern to trigger filter to begin suppression Regular Expression "SUPPRESS CHECKSTYLE (\w+)" 5.0
checkFormat check pattern to suppress Regular Expression ".*" 5.0
messageFormat message pattern to suppress Regular Expression null 5.0
influenceFormat a negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment Regular Expression "0" 5.0
checkCPP whether to check C++ style comments (//) Boolean true 5.0
checkC whether to check C style comments (/* ... */) Boolean true 5.0

Examples

To configure a filter to suppress audit events for check on any line with a comment SUPPRESS CHECKSTYLE check:

<module name="SuppressWithNearbyCommentFilter"/>
            
private int [] array; // SUPPRESS CHECKSTYLE
            

To configure a filter to suppress all audit events on any line containing the comment CHECKSTYLE IGNORE THIS LINE:

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="CHECKSTYLE IGNORE THIS LINE"/>
  <property name="checkFormat" value=".*"/>
  <property name="influenceFormat" value="0"/>
</module>
            
public static final int lowerCaseConstant; // CHECKSTYLE IGNORE THIS LINE
            

To configure a filter so that // OK to catch (Throwable|Exception|RuntimeException) here permits the current and previous line to avoid generating an IllegalCatch audit event:

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="OK to catch (\w+) here"/>
  <property name="checkFormat" value="IllegalCatchCheck"/>
  <property name="messageFormat" value="$1"/>
  <property name="influenceFormat" value="-1"/>
</module>
            
. . .
catch (RuntimeException re) {
// OK to catch RuntimeException here
}
catch (Throwable th) { ... }
. . .
            

To configure a filter so that CHECKSTYLE IGNORE check FOR NEXT var LINES avoids triggering any audits for the given check for the current line and the next var lines (for a total of var+1 lines):

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="CHECKSTYLE IGNORE (\w+) FOR NEXT (\d+) LINES"/>
  <property name="checkFormat" value="$1"/>
  <property name="influenceFormat" value="$2"/>
</module>
            
public static final int lowerCaseConstant; // CHECKSTYLE IGNORE ConstantNameCheck FOR NEXT 3 LINES
public static final int lowerCaseConstant1;
public static final int lowerCaseConstant2;
public static final int lowerCaseConstant3;
public static final int lowerCaseConstant4; // will warn here
            

To configure a filter to avoid any audits on code like:

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="ALLOW (\\w+) ON PREVIOUS LINE"/>
  <property name="checkFormat" value="$1"/>
  <property name="influenceFormat" value="-1"/>
</module>
            
private int D2;
// ALLOW MemberName ON PREVIOUS LINE
. . .
            

To configure a filter to allow suppress one or more Checks(separated by "|") and demand comment no less than 14 symbols:

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="@cs\.suppress \[(\w+(\|\w+)*)\] \w[-\.'`,:;\w ]{14,}"/>
  <property name="checkFormat" value="$1"/>
  <property name="influenceFormat" value="1"/>
</module>
            
public static final int [] array; // @cs.suppress [ConstantName|NoWhitespaceAfter] A comment here
            

It is possible to specify an ID of checks, so that it can be leveraged by the SuppressWithNearbyCommentFilter to skip validations. The following examples show how to skip validations near code that has comment like // @cs-: <ID/> (reason), where ID is the ID of checks you want to suppress.

Examples of Checkstyle checks configuration:

<module name="RegexpSinglelineJava">
  <property name="id" value="ignore"/>
  <property name="format" value="^.*@Ignore\s*$"/>
  <property name="message" value="@Ignore should have a reason."/>
</module>

<module name="RegexpSinglelineJava">
  <property name="id" value="systemout"/>
  <property name="format" value="^.*System\.(out|err).*$"/>
  <property name="message" value="Don't use System.out/err, use SLF4J instead."/>
</module>
            

Example of SuppressWithNearbyCommentFilter configuration (checkFormat which is set to '$1' points that ID of the checks is in the first group of commentFormat regular expressions):

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="@cs-: (\w+) \(\w+\)"/>
  <property name="checkFormat" value="$1"/>
  <property name="influenceFormat" value="0"/>
</module>
            
@Ignore // @cs-: ignore (test has not been implemented yet)
@Test
public void testMethod() { }

public static void foo() {
  System.out.println("Debug info."); // @cs-: systemout (should not fail RegexpSinglelineJava)
}
            

Example of how to configure the check to suppress more than one checks. The influence format format is specified in the second regexp group.

<module name="SuppressWithNearbyCommentFilter">
  <property name="commentFormat" value="@cs-\: ([\w\|]+) influence (\d+)"/>
  <property name="checkFormat" value="$1"/>
  <property name="influenceFormat" value="$2"/>
  </module>
            
// @cs-: ClassDataAbstractionCoupling influence 2
// @cs-: MagicNumber influence 4
@Service // no violations from ClassDataAbstractionCoupling here
@Transactional
public class UserService {
  private int value = 10022; // no violations from MagicNumber here
}
            

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

TreeWalker