Class SuppressionXpathFilter
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.api.AutomaticBean
-
- com.puppycrawl.tools.checkstyle.filters.SuppressionXpathFilter
-
- All Implemented Interfaces:
Configurable,Contextualizable,ExternalResourceHolder,TreeWalkerFilter
public class SuppressionXpathFilter extends AutomaticBean implements TreeWalkerFilter, ExternalResourceHolder
Filter
SuppressionXpathFilterworks as SuppressionFilter. Additionally, filter processessuppress-xpathelements, 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 issue #5770.
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.
The suppression file location is checked in following order:
- as a filesystem location
-
if no file found, and the location starts with either
http://orhttps://, then it is interpreted as a URL -
if no file found, then passed to the
ClassLoader.getResource()method.
SuppressionXpathFilter can suppress Checks that have Treewalker as parent module.
-
Property
file- Specify the location of the suppressions XML document file. Type isjava.lang.String. Default value isnull. -
Property
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. Type isboolean. Default value isfalse.
For example, the following configuration fragment directs the Checker to use a
SuppressionXpathFilterwith suppressions fileconfig/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
suppressandsuppress-xpathelements, where eachsuppress-xpathelement 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 asidormessageis specified. -
message- a Pattern matched against the message of the check associated with an audit event. Optional as long aschecksoridis specified. -
id- a String matched against the ID of the check associated with an audit event. Optional as long aschecksormessageis specified. -
query- a String xpath query. It is optional.
Each audit event is checked against each
suppressandsuppress-xpathelement. 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
SuppressionXpathFilterto rejectCyclomaticComplexityviolations 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@textattribute: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
LeftCurlycheck 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
RequireThisviolations 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
IllegalThrowsviolations only for methods with name throwsMethod and only forRuntimeExceptionexceptions. Double colon is used for axis iterations. In the following exampleancestoraxis is used to iterate all ancestor nodes of the current node with typeMETHOD_DEFand 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-selfaxis iterates through current node and all children nodes at any level. Keywordnode()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
wordCountin 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_DEFnode refers to variable declaration statement and has child node with token typeIDENTwhich 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_DEFnode is responsible for storing variable value -NUM_INTwith value 11.The following example demonstrates how variable can be queried by its value, same approach applies to
String, char, float, double, int, longdata 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 childIDENT -> Generated [6:5], therefore can be queried byIDENTvalue:<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 theANNOTATIONnode is stored inside sub-node with token typeSTRING_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']]]"/>Parent is
com.puppycrawl.tools.checkstyle.TreeWalker- Since:
- 8.6
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
AutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description private java.lang.StringfileSpecify the location of the suppressions XML document file.private java.util.Set<TreeWalkerFilter>filtersSet of individual xpath suppresses.private booleanoptionalControl what to do when the file is not existing.
-
Constructor Summary
Constructors Constructor Description SuppressionXpathFilter()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description booleanaccept(TreeWalkerAuditEvent treeWalkerAuditEvent)Determines whether or not a filteredTreeWalkerAuditEventis accepted.booleanequals(java.lang.Object obj)protected voidfinishLocalSetup()Provides a hook to finish the part of this component's setup that was not handled by the bean introspection.java.util.Set<java.lang.String>getExternalResourceLocations()Returns a set of external configuration resource locations which are used by the module.inthashCode()voidsetFile(java.lang.String fileName)Setter to specify the location of the suppressions XML document file.voidsetOptional(boolean optional)Setter to control what to do when the file is not existing.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
file
private java.lang.String file
Specify the location of the suppressions XML document file.
-
optional
private boolean 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.
-
filters
private java.util.Set<TreeWalkerFilter> filters
Set of individual xpath suppresses.
-
-
Constructor Detail
-
SuppressionXpathFilter
public SuppressionXpathFilter()
-
-
Method Detail
-
setFile
public void setFile(java.lang.String fileName)
Setter to specify the location of the suppressions XML document file.- Parameters:
fileName- name of the suppressions file.
-
setOptional
public void setOptional(boolean optional)
Setter to 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.- Parameters:
optional- tells if config file existence is optional.
-
equals
public boolean equals(java.lang.Object obj)
- Overrides:
equalsin classjava.lang.Object
-
hashCode
public int hashCode()
- Overrides:
hashCodein classjava.lang.Object
-
accept
public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent)
Description copied from interface:TreeWalkerFilterDetermines whether or not a filteredTreeWalkerAuditEventis accepted.- Specified by:
acceptin interfaceTreeWalkerFilter- Parameters:
treeWalkerAuditEvent- the TreeWalkerAuditEvent to filter.- Returns:
- true if the event is accepted.
-
getExternalResourceLocations
public java.util.Set<java.lang.String> getExternalResourceLocations()
Description copied from interface:ExternalResourceHolderReturns a set of external configuration resource locations which are used by the module. ATTENTION! If 'getExternalResourceLocations()' return null, there will beNullPointerExceptioninChecker. Such behaviour will signal that your module (check or filter) is designed incorrectly. It make sense to return an empty set from 'getExternalResourceLocations()' only for composite modules likeTreeWalker.- Specified by:
getExternalResourceLocationsin interfaceExternalResourceHolder- Returns:
- a set of external configuration resource locations which are used by the module.
-
finishLocalSetup
protected void finishLocalSetup() throws CheckstyleException
Description copied from class:AutomaticBeanProvides a hook to finish the part of this component's setup that was not handled by the bean introspection.The default implementation does nothing.
- Specified by:
finishLocalSetupin classAutomaticBean- Throws:
CheckstyleException- if there is a configuration error.
-
-