Content

SeverityMatchFilter

Since Checkstyle 3.2

Description

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

Notes

SeverityMatchFilter can suppress Checks that have Treewalker or Checker as parent module.

Properties

name description type default value since
severity Specify the severity level of this filter. SeverityLevel error 3.2
acceptOnMatch Control whether 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

Since Checkstyle 3.5

Description

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.

Attention: This filter may only be specified within the TreeWalker module (<module name="TreeWalker"/>) and only applies to checks which are also defined within this module. To filter non-TreeWalker checks like RegexpSingleline, a SuppressWithPlainTextCommentFilter or similar filter must be used.

Notes

offCommentFormat and onCommentFormat must have equal paren counts.

SuppressionCommentFilter can suppress Checks that have Treewalker as parent module.

Properties

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

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:

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

Code after filter is applied:

...
//stop
GregorianCalendar calendar; // No warning here as it is suppressed by filter.
HashSet hashSet;
// Warning above 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="idFormat" 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

Since Checkstyle 3.2

Description

Filter SuppressionFilter rejects audit events for Check violations 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 Specify the location of the suppressions XML document file. String null 3.2
optional Control 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

Notes

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

  • files - a Pattern matched against the file name associated with an audit event. It is optional.
  • checks - a Pattern matched against the name of the check associated with an audit event. Optional as long as id or message is specified.
  • message - a Pattern matched against the message of the check associated with an audit event. Optional as long as checks or id is specified.
  • id - a String matched against the check id associated with an audit event. Optional as long as checks or message is specified.
  • lines - a comma-separated list of values, where each value is an int or a range of integers denoted by integer-integer. It is optional.
  • columns - a comma-separated list of values, where each value is an int 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.

ATTENTION: filtering by message is dependant on runtime locale. If project is running in different languages it is better to avoid filtering by message.

You can download template of empty suppression filter here.

Location of the file defined in file property is checked in the following order:

  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.

SuppressionFilter can suppress Checks that have Treewalker or Checker as parent module.

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>
        

The following suppressions XML document directs a SuppressionFilter to reject JavadocStyleCheck violations for lines 82 and 108 to 122 of file AbstractComplexityCheck.java, and MagicNumberCheck violations for line 221 of file JavadocStyleCheck.java, and 'Missing a Javadoc comment' violations for all lines and files:

<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
  "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN"
  "https://checkstyle.org/dtds/suppressions_1_2.dtd">

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

Suppress check by module id when config have two instances on the same check:

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

Suppress all checks for hidden files and folders:

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

Suppress all checks for Maven-generated code:

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

Suppress all checks for archives, classes and other binary files:

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

Suppress all checks for image files:

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

Suppress all 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"/>
        

Suppress naming violations on variable named 'log' in all files:

<suppress message="Name 'log' must match pattern"/>
        

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker

SuppressionSingleFilter

Since Checkstyle 8.23

Description

Filter SuppressionSingleFilter suppresses audit events for Checks violations in the specified file, class, checks, message, module id, lines, and columns.

Rationale: To allow users use suppressions configured in the same config with other modules. SuppressionFilter and SuppressionXpathFilter are require separate file.

Advice: If checkstyle configuration is used for several projects, single suppressions on common files/folders is better to put in checkstyle configuration as common rule. All suppression that are for specific file names is better to keep in project specific config file.

Attention: This filter only supports single suppression, and will need multiple instances if users wants to suppress multiple violations.

Notes

SuppressionSingleFilter can suppress Checks that have Treewalker or Checker as parent module.

Properties

name description type default value since
files Define the RegExp for matching against the file name associated with an audit event. Pattern null 8.23
checks Define the RegExp for matching against the name of the check associated with an audit event. Regular Expression null 8.23
message Define the RegExp for matching against the message of the check associated with an audit event. Pattern null 8.23
id Specify a string matched against the ID of the check associated with an audit event. String null 8.23
lines Specify a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. String null 8.23
columns Specify a comma-separated list of values, where each value is an integer or a range of integers denoted by integer-integer. String null 8.23

Examples

The following suppressions directs a SuppressionSingleFilter to reject JavadocStyleCheck violations for lines 82 and 108 to 122 of file AbstractComplexityCheck.java, and MagicNumberCheck violations for line 221 of file JavadocStyleCheck.java, and 'Missing a Javadoc comment' violations for all lines and files:

<module name="SuppressionSingleFilter">
  <property name="checks" value="JavadocStyleCheck"/>
  <property name="files" value="AbstractComplexityCheck.java"/>
  <property name="lines" value="82,108-122"/>
</module>
<module name="SuppressionSingleFilter">
  <property name="checks" value="MagicNumberCheck"/>
  <property name="files" value="JavadocStyleCheck.java"/>
  <property name="lines" value="221"/>
</module>
<module name="SuppressionSingleFilter">
  <property name="message" value="Missing a Javadoc comment"/>
</module>
        

Suppress check by module id when config have two instances on the same check:

<module name="SuppressionSingleFilter">
  <property name="id" value="stringEqual"/>
  <property name="files" value="SomeTestCode.java"/>
</module>
        

Suppress all checks for hidden files and folders:

<module name="SuppressionSingleFilter">
  <property name="files" value="[/\\]\..+"/>
  <property name="checks" value=".*"/>
</module>
        

Suppress all checks for Maven-generated code:

<module name="SuppressionSingleFilter">
  <property name="files" value="[/\\]target[/\\]"/>
  <property name="checks" value=".*"/>
</module>
        

Suppress all checks for archives, classes and other binary files:

<module name="SuppressionSingleFilter">
  <property name="files" value=".+\.(?:jar|zip|war|class|tar|bin)$"/>
  <property name="checks" value=".*"/>
</module>
        

Suppress all checks for image files:

<module name="SuppressionSingleFilter">
  <property name="files" value=".+\.(?:png|gif|jpg|jpeg)$"/>
  <property name="checks" value=".*"/>
</module>
        

Suppress all checks for non-java files:

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

Suppress all checks in generated sources:

<module name="SuppressionSingleFilter">
  <property name="files" value="com[\\/]mycompany[\\/]app[\\/]gen[\\/]"/>
  <property name="checks" value=".*"/>
</module>
        

Suppress FileLength check on integration tests in certain folder:

<module name="SuppressionSingleFilter">
  <property name="files" value="com[\\/]mycompany[\\/]app[\\/].*IT.java"/>
  <property name="checks" value="FileLength"/>
</module>
        

Suppress naming violations on variable named 'log' in all files:

<module name="SuppressionSingleFilter">
  <property name="message" value="Name 'log' must match pattern"/>
</module>
        

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker

SuppressionXpathFilter

Since Checkstyle 8.6

Description

Filter SuppressionXpathFilter works as SuppressionFilter. Additionally, filter processes suppress-xpath elements, which contains xpath-expressions. Xpath-expressions are queries for suppressed nodes inside the AST tree.

Currently, filter does not support the following checks:

  • NoCodeInFile (reason is that AST is not generated for a file not containing code)
  • Regexp (reason is at #7759)
  • RegexpSinglelineJava (reason is at #7759)

Also, the filter does not support suppressions inside javadoc reported by Javadoc checks:

  • AtclauseOrder
  • JavadocBlockTagLocation
  • JavadocMethod
  • JavadocMissingLeadingAsterisk
  • JavadocMissingWhitespaceAfterAsterisk
  • JavadocParagraph
  • JavadocStyle
  • JavadocTagContinuationIndentation
  • JavadocType
  • MissingDeprecated
  • NonEmptyAtclauseDescription
  • RequireEmptyLineBeforeBlockTagGroup
  • SingleLineJavadoc
  • SummaryJavadoc
  • WriteTag

Note, that support for these Checks will be available after resolving issues #5770 and #5777.

Currently, filter supports the following xpath axes:

  • ancestor
  • ancestor-or-self
  • attribute
  • child
  • descendant
  • descendant-or-self
  • following
  • following-sibling
  • parent
  • preceding
  • preceding-sibling
  • self

You can use the command line helper tool to generate xpath suppressions based on your configuration file and input files. See here for more details.

Notes

The suppression file location is checked in following order:

  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.

SuppressionXpathFilter can suppress Checks that have Treewalker as parent module.

Properties

name description type default value since
file Specify the location of the suppressions XML document file. String null 8.6
optional Control 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 accepts all audit events. boolean false 8.6

Examples

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

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

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

  • files - a Pattern matched against the file name associated with an audit event. It is optional.
  • checks - a Pattern matched against the name of the check associated with an audit event. Optional as long as id or message is specified.
  • message - a Pattern matched against the message of the check associated with an audit event. Optional as long as checks or id is specified.
  • id - a String matched against the ID of the check associated with an audit event. Optional as long as checks or message is specified.
  • query - a String xpath query. It is optional.

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

ATTENTION: filtering by message is dependant on runtime locale. If project is running in different languages it is better to avoid filtering by message.

The following suppressions XML document directs a SuppressionXpathFilter to reject CyclomaticComplexity violations for all methods with name sayHelloWorld inside FileOne and FileTwo files:

Currently, xpath queries support one type of attribute @text. @text - addresses to the text value of the node. For example: variable name, annotation name, text content and etc. Only the following token types support @text attribute: TokenTypes.IDENT, TokenTypes.STRING_LITERAL, TokenTypes.CHAR_LITERAL, TokenTypes.NUM_LONG, TokenTypes.NUM_INT, TokenTypes.NUM_DOUBLE, TokenTypes.NUM_FLOAT. These token types were selected because only their text values are different in content from token type and represent text value from file and can be used in xpath queries for more accurate results. Other token types always have constant values.

<?xml version="1.0"?>

<!DOCTYPE suppressions PUBLIC
"-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN"
"https://checkstyle.org/dtds/suppressions_1_2_xpath_experimental.dtd">

<suppressions>
  <suppress-xpath checks="CyclomaticComplexity"
  files="FileOne.java,FileTwo.java"
  query="//METHOD_DEF[./IDENT[@text='sayHelloWorld']]"/>
</suppressions>
        

Suppress checks for package definitions:

<suppress-xpath checks=".*" query="/PACKAGE_DEF"/>
        

Suppress checks for parent element of the first variable definition:

<suppress-xpath checks=".*" query="(//VARIABLE_DEF)[1]/.."/>
        

Suppress checks for elements which are either class definitions, either method definitions.

<suppress-xpath checks=".*" query="//CLASS_DEF | //METHOD_DEF"/>
        

Suppress checks for certain methods:

<suppress-xpath checks=".*" query="//METHOD_DEF[./IDENT[@text='getSomeVar'
          or @text='setSomeVar']]"/>
        

Suppress checks for variable testVariable inside testMethod method inside TestClass class.

<suppress-xpath checks=".*" query="/CLASS_DEF[@text='TestClass']
          //METHOD_DEF[./IDENT[@text='testMethod']]
          //VARIABLE_DEF[./IDENT[@text='testVariable']]"/>
        

In the following sample, violations for LeftCurly check will be suppressed for classes with name Main or for methods with name calculate.

<suppress-xpath checks="LeftCurly" query="/CLASS_DEF[./IDENT[@text='Main']]//*
          | //METHOD_DEF[./IDENT[@text='calculate']]/*"/>
        

The following example demonstrates how to suppress RequireThis violations for variable age inside changeAge method.

<suppress-xpath checks="RequireThis"
     query="/CLASS_DEF[./IDENT[@text='InputTest']]
          //METHOD_DEF[./IDENT[@text='changeAge']]//ASSIGN/IDENT[@text='age']"/>
        
public class InputTest {
  private int age = 23;

  public void changeAge() {
    age = 24; //violation will be suppressed
  }
}
        

Suppress IllegalThrows violations only for methods with name throwsMethod and only for RuntimeException exceptions. Double colon is used for axis iterations. In the following example ancestor axis is used to iterate all ancestor nodes of the current node with type METHOD_DEF and name throwsMethod. Please read more about xpath axes at W3Schools Xpath Axes.

<suppress-xpath checks="IllegalThrows" query="//LITERAL_THROWS
          /IDENT[@text='RuntimeException' and
          ./ancestor::METHOD_DEF[./IDENT[@text='throwsMethod']]]"/>
        
public class InputTest {
  public void throwsMethod() throws RuntimeException { // violation will be suppressed
  }

  public void sampleMethod() throws RuntimeException { // will throw violation here
  }
}
        

The following sample demonstrates how to suppress all violations for method itself and all descendants. descendant-or-self axis iterates through current node and all children nodes at any level. Keyword node() selects node elements. Please read more about xpath syntax at W3Schools Xpath Syntax.

<suppress-xpath checks=".*" query="//METHOD_DEF[./IDENT[@text='legacyMethod']]
          /descendant-or-self::node()"/>
        

Some elements can be suppressed in different ways. For example, to suppress violation on variable wordCount in following code:

public class InputTest {
    private int wordCount = 11;
}
        

You need to look at AST of such code by our CLI tool:

$ java -jar checkstyle-X.XX-all.jar -t InputTest.java
CLASS_DEF -> CLASS_DEF [1:0]
|--MODIFIERS -> MODIFIERS [1:0]
|   `--LITERAL_PUBLIC -> public [1:0]
|--LITERAL_CLASS -> class [1:7]
|--IDENT -> InputTest [1:13]
`--OBJBLOCK -> OBJBLOCK [1:23]
|--LCURLY -> { [1:23]
|--VARIABLE_DEF -> VARIABLE_DEF [2:4]
|   |--MODIFIERS -> MODIFIERS [2:4]
|   |   `--LITERAL_PRIVATE -> private [2:4]
|   |--TYPE -> TYPE [2:12]
|   |   `--LITERAL_INT -> int [2:12]
|   |--IDENT -> wordCount [2:16]
|   |--ASSIGN -> = [2:26]
|   |   `--EXPR -> EXPR [2:28]
|   |       `--NUM_INT -> 11 [2:28]
|   `--SEMI -> ; [2:30]
`--RCURLY -> } [3:0]
        

The easiest way is to suppress by variable name. As you can see VARIABLE_DEF node refers to variable declaration statement and has child node with token type IDENT which is used for storing class, method, variable names.

The following example demonstrates how variable can be queried by its name:

<suppress-xpath checks="." query="//VARIABLE_DEF[
            ./IDENT[@text='wordCount']]"/>
        

Another way is to suppress by variable value. Again, if you look at the printed AST tree above, you will notice that one of the grandchildren of VARIABLE_DEF node is responsible for storing variable value - NUM_INT with value 11.

The following example demonstrates how variable can be queried by its value, same approach applies to String, char, float, double, int, long data types:

<suppress-xpath checks="." query="//VARIABLE_DEF[.//NUM_INT[@text=11]]"/>
        

Next example is about suppressing method with certain annotation by its name and element value.

public class InputTest {
    @Generated("first") // should not be suppressed
    public void test1() {
    }

    @Generated("second") // should be suppressed
    public void test2() {
    }
}
        

First of all we need to look at AST tree printed by our CLI tool:

$ java -jar checkstyle-X.XX-all.jar -t InputTest.java
CLASS_DEF -> CLASS_DEF [1:0]
|--MODIFIERS -> MODIFIERS [1:0]
|   `--LITERAL_PUBLIC -> public [1:0]
|--LITERAL_CLASS -> class [1:7]
|--IDENT -> InputTest [1:13]
`--OBJBLOCK -> OBJBLOCK [1:23]
|--LCURLY -> { [1:23]
|--METHOD_DEF -> METHOD_DEF [2:4]
|   |--MODIFIERS -> MODIFIERS [2:4]
|   |   |--ANNOTATION -> ANNOTATION [2:4]
|   |   |   |--AT -> @ [2:4]
|   |   |   |--IDENT -> Generated [2:5]
|   |   |   |--LPAREN -> ( [2:14]
|   |   |   |--EXPR -> EXPR [2:15]
|   |   |   |   `--STRING_LITERAL -> "first" [2:15]
|   |   |   `--RPAREN -> ) [2:22]
|   |   `--LITERAL_PUBLIC -> public [3:4]
|   |--TYPE -> TYPE [3:11]
|   |   `--LITERAL_VOID -> void [3:11]
|   |--IDENT -> test1 [3:16]
|   |--LPAREN -> ( [3:21]
|   |--PARAMETERS -> PARAMETERS [3:22]
|   |--RPAREN -> ) [3:22]
|   `--SLIST -> { [3:24]
|       `--RCURLY -> } [4:4]
|--METHOD_DEF -> METHOD_DEF [6:4]
|   |--MODIFIERS -> MODIFIERS [6:4]
|   |   |--ANNOTATION -> ANNOTATION [6:4]
|   |   |   |--AT -> @ [6:4]
|   |   |   |--IDENT -> Generated [6:5]
|   |   |   |--LPAREN -> ( [6:14]
|   |   |   |--EXPR -> EXPR [6:15]
|   |   |   |   `--STRING_LITERAL -> "second" [6:15]
|   |   |   `--RPAREN -> ) [6:23]
|   |   `--LITERAL_PUBLIC -> public [7:4]
|   |--TYPE -> TYPE [7:11]
|   |   `--LITERAL_VOID -> void [7:11]
|   |--IDENT -> test2 [7:16]
|   |--LPAREN -> ( [7:21]
|   |--PARAMETERS -> PARAMETERS [7:22]
|   |--RPAREN -> ) [7:22]
|   `--SLIST -> { [7:24]
|       `--RCURLY -> } [8:4]
`--RCURLY -> } [9:0]
        

AST node ANNOTATION -> ANNOTATION [6:4] has direct child IDENT -> Generated [6:5], therefore can be queried by IDENT value:

<suppress-xpath checks="." query="//METHOD_DEF[
            .//ANNOTATION/IDENT[@text='Generated']]"/>
        

The problem with query above that it will suppress violations for all methods with annotation @Generated. In order to suppress methods with @Generated("second") annotations only, you need to look at AST tree again. Value of the ANNOTATION node is stored inside sub-node with token type STRING_LITERAL. Use the following query to suppress methods with @Generated("second") annotation:

<suppress-xpath checks="." query="//METHOD_DEF[.//ANNOTATION[
            ./IDENT[@text='Generated'] and ./EXPR/STRING_LITERAL[@text='second']]]"/>
        

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

TreeWalker

SuppressionXpathSingleFilter

Since Checkstyle 8.18

Description

Filter SuppressionXpathSingleFilter suppresses audit events for Checks violations in the specified file, class, checks, message, module id, and xpath.

Rationale: To allow users use suppressions configured in the same config with other modules. SuppressionFilter and SuppressionXpathFilter are require separate file.

Advice: If checkstyle configuration is used for several projects, single suppressions on common files/folders is better to put in checkstyle configuration as common rule. All suppression that are for specific file names is better to keep in project specific config file.

Attention: This filter only supports single suppression, and will need multiple instances if users wants to suppress multiple violations.

Notes

SuppressionXpathSingleFilter can suppress Checks that have Treewalker as parent module.

Properties

name description type default value since
files Define a Regular Expression matched against the file name associated with an audit event. Regular Expression null 8.18
checks Define a Regular Expression matched against the name of the check associated with an audit event. Regular Expression null 8.18
message Define a Regular Expression matched against the message of the check associated with an audit event. Regular Expression null 8.18
id Define a string matched against the ID of the check associated with an audit event. String null 8.18
query Define a string xpath query. String null 8.18

Examples

To configure to suppress the MethodName check for all methods with name MyMethod inside FileOne and FileTwo files:

<module name="SuppressionXpathSingleFilter">
  <property name="files" value="File(One|Two)\.java"/>
  <property name="checks" value="MethodName"/>
  <property name="query" value="(/CLASS_DEF[@text='FileOne']/OBJBLOCK/
            METHOD_DEF[@text='MyMethod']/IDENT)|
            (/CLASS_DEF[@text='FileTwo']/OBJBLOCK/METHOD_DEF[@text='MyMethod']/IDENT)"/>
</module>
          

Code example:

public class FileOne {
  public void MyMethod() {} // OK
}

public class FileTwo {
  public void MyMethod() {} // OK
}

public class FileThree {
  public void MyMethod() {} // violation, name 'MyMethod'
                            // must match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

To suppress MethodName check for method names matched pattern 'MyMethod[0-9]':

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="MethodName"/>
  <property name="message" value="MyMethod[0-9]"/>
</module>
          

Code Example:

public class FileOne {
  public void MyMethod1() {} // OK
  public void MyMethod2() {} // OK
  public void MyMethodA() {} // violation, name 'MyMethodA' must
                             // match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

To suppress checks being specified by id property:

<module name="MethodName">
  <property name="id" value="MethodName1"/>
  <property name="format" value="^[a-z](_?[a-zA-Z0-9]+)*$"/>
<module/>
<module name="SuppressionXpathSingleFilter">
  <property name="files" value="FileOne.java"/>
  <property name="id" value="MethodName1"/>
<module/>
          

Code example:

public class FileOne {
  public void MyMethod() {} // OK
}
public class FileTwo {
  public void MyMethod() {} // violation,  name 'MyMethod' must
                            //match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

To suppress checks for all package definitions:

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="PackageName"/>
  <property name="query" value="/PACKAGE_DEF[@text='File']/IDENT"/>
</module>
          

Code example:

package File; // OK

public class FileOne {}
          

To suppress RedundantModifier check for interface definitions:

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="RedundantModifier"/>
  <property name="query" value="/INTERFACE_DEF//*"/>
<module/>
          

Code Example:

public interface TestClass {
  public static final int CONSTANT1 = 1;  // OK
}
          

To suppress checks in the FileOne file by non-query:

<module name="SuppressionXpathSingleFilter">
  <property name="files" value="FileOne.java"/>
  <property name="checks" value="MyMethod"/>
</module>
          

Code example:

public class FileOne {
  public void MyMethod() {} // OK
}

public class FileTwo {
  public void MyMethod() {} // violation, name 'MyMethod'
                            // must match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

Suppress checks for elements which are either class definitions, either method definitions:

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value=".*"/>
  <property name="query"
            value="(/CLASS_DEF[@text='FileOne'])|
            (/CLASS_DEF[@text='FileOne']/OBJBLOCK/METHOD_DEF[@text='MyMethod']/IDENT)"/>
</module>
          

Code example:

abstract class FileOne { // OK
  public void MyMethod() {} // OK
}

abstract class FileTwo { // violation of the AbstractClassName check,
                         // it should match the pattern "^Abstract.+$"
  public void MyMethod() {} // violation, name 'MyMethod'
                            // must match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

Suppress checks for MyMethod1 or MyMethod2 methods:

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="MethodName"/>
  <property name="query" value="/CLASS_DEF[@text='FileOne']/OBJBLOCK/
            METHOD_DEF[@text='MyMethod1' or @text='MyMethod2']/IDENT"/>
</module>
          

Code example:

public class FileOne {
  public void MyMethod1() {} // OK
  public void MyMethod2() {} // OK
  public void MyMethod3() {} // violation, name 'MyMethod3' must
                             // match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
}
          

Suppress checks for variable testVariable inside testMethod method inside TestClass class:

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="LocalFinalVariableName"/>
  <property name="query" value="/CLASS_DEF[@text='TestClass']/OBJBLOCK
        /METHOD_DEF[@text='testMethod']/SLIST
        /VARIABLE_DEF[@text='testVariable1']/IDENT"/>
</module>
          

Code Example:

public class TestClass {
  public void testMethod() {
    final int testVariable1 = 10; // OK
    final int testVariable2 = 10; // violation of the LocalFinalVariableName check,
                                  // name 'testVariable2' must match pattern '^[A-Z][A-Z0-9]*$'
  }
}
          

In the following sample, violations for LeftCurly check will be suppressed for classes with name Main or for methods with name calculate.

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="LeftCurly"/>
  <property name="query" value="/CLASS_DEF[@text='TestClass']/OBJBLOCK
        /METHOD_DEF[@text='testMethod1']/SLIST*"/>
</module>
          

Code Example:

public class TestClass {
  public void testMethod1()
  { // OK
  }

  public void testMethod2()
  { // violation, '{' should be on the previous line
  }
}
          

The following example demonstrates how to suppress RequireThis violations for variable age inside changeAge method.

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="RequireThis"/>
  <property name="query" value="/CLASS_DEF[@text='InputTest']
        //METHOD_DEF[@text='changeAge']//ASSIGN[@text='age']/IDENT"/>
</module>
          

Code Example:

public class InputTest {
  private int age = 23;

  public void changeAge() {
    age = 24; // violation will be suppressed
  }
}
          

Suppress IllegalThrows violations only for methods with name throwsMethod and only for RuntimeException exceptions. Double colon is used for axis iterations. In the following example ancestor axis is used to iterate all ancestor nodes of the current node with type METHOD_DEF and name throwsMethod. Please read more about xpath axes at W3Schools Xpath Axes.

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value="IllegalThrows"/>
  <property name="query" value="//LITERAL_THROWS/IDENT[
      ..[@text='RuntimeException'] and ./ancestor::METHOD_DEF[@text='throwsMethod']]"/>
</module>
          

Code Example:

public class InputTest {
  public void throwsMethod() throws RuntimeException { // violation will be suppressed
  }

  public void sampleMethod() throws RuntimeException { // will throw violation here
  }
}
          

The following sample demonstrates how to suppress all violations for method itself and all descendants. descendant-or-self axis iterates through current node and all children nodes at any level. Keyword node() selects node elements. Please read more about xpath syntax at W3Schools Xpath Syntax.

<module name="SuppressionXpathSingleFilter">
  <property name="checks" value=".*"/>
  <property name="query" value="//METHOD_DEF[@text='TestMethod1']
        /descendant-or-self::node()"/>
</module>
          

Code Example:

public class TestClass {
  public void TestMethod1() { // OK
    final int num = 10; // OK
  }

  public void TestMethod2() { // violation of the MethodName check,
                              // name 'TestMethod2' must match pattern '^[a-z](_?[a-zA-Z0-9]+)*$'
    final int num = 10; // violation of the LocalFinalVariableName check,
                        // name 'num' must match pattern '^[A-Z][A-Z0-9]*$'
  }
}
          

The following example is an example of what checks would be suppressed while building Spring projects with checkstyle plugin. Please find more information at: spring-javaformat

<module name="SuppressionXpathSingleFilter">
  <property name="files" value="[\\/]src[\\/]test[\\/]java[\\/]"/>
  <property name="checks" value="Javadoc*"/>
</module>
<module name="SuppressionXpathSingleFilter">
  <property name="files" value=".*Tests\.java">
  <property name="checks" value="Javadoc*">
</module>
<module name="SuppressionXpathSingleFilter">
  <property name="files" value="generated-sources">
  <property name="checks" value="[a-zA-Z0-9]*">
</module>
          

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

TreeWalker

SuppressWarningsFilter

Since Checkstyle 5.7

Description

Filter SuppressWarningsFilter uses annotation {@code SuppressWarnings} 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.

Notes

SuppressWarningsFilter can suppress Checks that have Treewalker or Checker as parent module.

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

Since Checkstyle 5.0

Description

Filter SuppressWithNearbyCommentFilter uses nearby 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.

Attention: This filter may only be specified within the TreeWalker module (<module name="TreeWalker"/>) and only applies to checks which are also defined within this module. To filter non-TreeWalker checks like RegexpSingleline, a SuppressWithPlainTextCommentFilter or similar filter must be used.

Notes

SuppressWithNearbyCommentFilter can suppress Checks that have Treewalker as parent module.

Properties

name description type default value since
commentFormat Specify comment pattern to trigger filter to begin suppression. Pattern "SUPPRESS CHECKSTYLE (\w+)" 5.0
checkFormat Specify check pattern to suppress. Regular Expression ".*" 5.0
messageFormat Define message pattern to suppress. Regular Expression null 5.0
idFormat Specify check ID pattern to suppress. Regular Expression null 8.24
influenceFormat Specify negative/zero/positive value that defines the number of lines preceding/at/following the suppression comment. Regular Expression "0" 5.0
checkCPP Control whether to check C++ style comments (//). boolean true 5.0
checkC Control 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 NEXTvar 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>
        
static final int lowerCaseConstant; // CHECKSTYLE IGNORE ConstantNameCheck FOR NEXT 3 LINES
static final int lowerCaseConstant1;
static final int lowerCaseConstant2;
static final int lowerCaseConstant3;
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 (idFormat 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+) \(.*\)"/>
  <property name="idFormat" 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

SuppressWithPlainTextCommentFilter

Since Checkstyle 8.6

Description

Filter SuppressWithPlainTextCommentFilter uses plain text to suppress audit events. The filter can be used only to suppress audit events received from the checks which implement FileSetCheck interface. In other words, the checks which have Checker as a parent module. The filter knows nothing about AST, it treats only plain text comments and extracts the information required for suppression from the plain text comments. Currently the filter supports only single line comments.

Please, be aware of the fact that, it is not recommended to use the filter for Java code anymore, however you still are able to use it to suppress audit events received from the checks which implement FileSetCheck interface.

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 Specify comment pattern to trigger filter to begin suppression. Pattern "// CHECKSTYLE:OFF" 8.6
onCommentFormat Specify comment pattern to trigger filter to end suppression. Pattern "// CHECKSTYLE:ON" 8.6
checkFormat Specify check pattern to suppress. Regular Expression ".*" 8.6
messageFormat Specify message pattern to suppress. Regular Expression null 8.6
idFormat Specify check ID pattern to suppress. Regular Expression null 8.24

Notes

Properties offCommentFormat and onCommentFormat must have equal paren counts.

SuppressionWithPlainTextCommentFilter can suppress Checks that have Treewalker or Checker as parent module.

Examples

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

<module name="Checker">
  ...
  <module name="SuppressWithPlainTextCommentFilter"/>
  ...
</module>
        

To configure a filter to suppress audit events between a comment containing line BEGIN GENERATED CONTENT and a comment containing line END GENERATED CONTENT (Checker is configured to check only properties files):

<module name="Checker">
  <property name="fileExtensions" value="properties"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="BEGIN GENERATED CONTENT"/>
    <property name="onCommentFormat" value="END GENERATED CONTENT"/>
  </module>

</module>
        
//BEGIN GENERATED CONTENT
my.property=value1 // No violation events will be reported
my.property=value2 // No violation events will be reported
//END GENERATED CONTENT
. . .
        

To configure a filter so that -- stop tab check and -- resume tab check marks allowed tab positions (Checker is configured to check only sql files):

<module name="Checker">
  <property name="fileExtensions" value="sql"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="stop tab check"/>
    <property name="onCommentFormat" value="resume tab check"/>
    <property name="checkFormat" value="FileTabCharacterCheck"/>
  </module>

</module>
        
-- stop tab check
  SELECT * FROM users // won't warn here if there is a tab character on line
-- resume tab check
  SELECT 1 // will warn here if there is a tab character on line
        

To configure a filter so that name of suppressed check mentioned in comment CSOFF: regexp and CSON: regexp mark a matching check (Checker is configured to check only xml files):

<module name="Checker">
  <property name="fileExtensions" value="xml"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="CSOFF\: ([\w\|]+)"/>
    <property name="onCommentFormat" value="CSON\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
  </module>

</module>
        
// CSOFF: RegexpSinglelineCheck
 // RegexpSingleline check won't warn any lines below here if the line matches regexp
<condition property="checkstyle.ant.skip">
  <isset property="checkstyle.ant.skip"/>
</condition>
// CSON: RegexpSinglelineCheck
// RegexpSingleline check will warn below here if the line matches regexp
<property name="checkstyle.pattern.todo" value="NOTHingWillMatCH_-"/>
        

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 (Checker is configured to check only java files):

<module name="Checker">
  <property name="fileExtensions" value="java"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat"
      value="CHECKSTYLE_OFF: ALMOST_ALL"/>
    <property name="onCommentFormat"
      value="CHECKSTYLE_ON: ALMOST_ALL"/>
    <property name="checkFormat"
      value="^((?!(FileTabCharacterCheck)).)*$"/>
  </module>

</module>
        
// CHECKSTYLE_OFF: ALMOST_ALL
public static final int array [];
private String [] strArray;
// CHECKSTYLE_ON: ALMOST_ALL
private int array1 [];
        

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

<module name="Checker">
  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="stop"/>
    <property name="onCommentFormat" value="resume"/>
    <property name="checkFormat" value="FileTabCharacterCheck"/>
    <property name="messageFormat"
        value="^File contains tab characters (this is the first instance)\.$"/>
  </module>
</module>
        

It is possible to specify an ID of checks, so that it can be leveraged by the SuppressWithPlainTextCommentFilter 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="count"/>
  <property name="format" value="^.*COUNT(*).*$"/>
  <property name="message"
    value="Don't use COUNT(*), use COUNT(1) instead."/>
</module>

<module name="RegexpSinglelineJava">
  <property name="id" value="join"/>
  <property name="format" value="^.*JOIN\s.+\s(ON|USING)$"/>
  <property name="message"
    value="Don't use JOIN, use sub-select instead."/>
</module>
        

Example of SuppressWithPlainTextCommentFilter 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="Checker">
  <property name="fileExtensions" value="sql"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="CSOFF (\w+) \(\w+\)"/>
    <property name="onCommentFormat" value="CSON (\w+)"/>
    <property name="idFormat" value="$1"/>
  </module>

</module>
        
-- CSOFF join (it is ok to use join here for performance reasons)
SELECT name, job_name
FROM users AS u
JOIN jobs AS j ON u.job_id = j.id
-- CSON join

-- CSOFF count (test query execution plan)
EXPLAIN SELECT COUNT(*) FROM restaurants
-- CSON count
        

Example of how to configure the check to suppress more than one check (Checker is configured to check only sql files).

<module name="Checker">
  <property name="fileExtensions" value="sql"/>

  <module name="SuppressWithPlainTextCommentFilter">
    <property name="offCommentFormat" value="@cs-\: ([\w\|]+)"/>
    <property name="checkFormat" value="$1"/>
  </module>

</module>
        
-- @cs-: RegexpSinglelineCheck
-- @cs-: FileTabCharacterCheck
CREATE TABLE STATION (
  ID INTEGER PRIMARY KEY,
  CITY CHAR(20),
  STATE CHAR(2),
  LAT_N REAL,
  LONG_W REAL);
        

Example of Usage

Package

com.puppycrawl.tools.checkstyle.filters

Parent Module

Checker