Class MatchXpathCheck
- java.lang.Object
-
- com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
-
- com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
-
- com.puppycrawl.tools.checkstyle.api.AbstractCheck
-
- com.puppycrawl.tools.checkstyle.checks.coding.MatchXpathCheck
-
- All Implemented Interfaces:
Configurable
,Contextualizable
public class MatchXpathCheck extends AbstractCheck
Evaluates Xpath query and report violation on all matching AST nodes. This check allows user to implement custom checks using Xpath. If Xpath query is not specified explicitly, then the check does nothing.
It is recommended to define custom message for violation to explain what is not allowed and what to use instead, default message might be too abstract. To customize a message you need to add
message
element with matchxpath.match askey
attribute and desired message asvalue
attribute.Please read more about Xpath syntax at Xpath Syntax. Information regarding Xpath functions can be found at XSLT/XPath Reference. Note, that @text attribute can be used only with token types that are listed in XpathUtil.
-
Property
query
- Specify Xpath query. Type isjava.lang.String
. Default value is""
.
Checkstyle provides command line tool and GUI application with options to show AST and to ease usage of Xpath queries.
-T option prints AST tree of the checked file.
$ java -jar checkstyle-X.XX-all.jar -T Main.java CLASS_DEF -> CLASS_DEF [1:0] |--MODIFIERS -> MODIFIERS [1:0] | `--LITERAL_PUBLIC -> public [1:0] |--LITERAL_CLASS -> class [1:7] |--IDENT -> Main [1:13] `--OBJBLOCK -> OBJBLOCK [1:18] |--LCURLY -> { [1:18] |--METHOD_DEF -> METHOD_DEF [2:4] | |--MODIFIERS -> MODIFIERS [2:4] | | `--LITERAL_PUBLIC -> public [2:4] | |--TYPE -> TYPE [2:11] | | `--IDENT -> String [2:11] | |--IDENT -> sayHello [2:18] | |--LPAREN -> ( [2:26] | |--PARAMETERS -> PARAMETERS [2:27] | | `--PARAMETER_DEF -> PARAMETER_DEF [2:27] | | |--MODIFIERS -> MODIFIERS [2:27] | | |--TYPE -> TYPE [2:27] | | | `--IDENT -> String [2:27] | | `--IDENT -> name [2:34] | |--RPAREN -> ) [2:38] | `--SLIST -> { [2:40] | |--LITERAL_RETURN -> return [3:8] | | |--EXPR -> EXPR [3:25] | | | `--PLUS -> + [3:25] | | | |--STRING_LITERAL -> "Hello, " [3:15] | | | `--IDENT -> name [3:27] | | `--SEMI -> ; [3:31] | `--RCURLY -> } [4:4] `--RCURLY -> } [5:0]
-b option shows AST nodes that match given Xpath query. This command can be used to validate accuracy of Xpath query against given file.
$ java -jar checkstyle-X.XX-all.jar Main.java -b "//METHOD_DEF[./IDENT[@text='sayHello']]" CLASS_DEF -> CLASS_DEF [1:0] `--OBJBLOCK -> OBJBLOCK [1:18] |--METHOD_DEF -> METHOD_DEF [2:4]
The following example demonstrates validation of methods order, so that public methods should come before the private ones:
<module name="MatchXpath"> <property name="query" value="//METHOD_DEF[.//LITERAL_PRIVATE and following-sibling::METHOD_DEF[.//LITERAL_PUBLIC]]"/> <message key="matchxpath.match" value="Private methods must appear after public methods"/> </module>
Example:
public class Test { public void method1() { } private void method2() { } // violation public void method3() { } private void method4() { } // violation public void method5() { } private void method6() { } // ok }
To violate if there are any parametrized constructors
<module name="MatchXpath"> <property name="query" value="//CTOR_DEF[count(./PARAMETERS/*) > 0]"/> <message key="matchxpath.match" value="Parameterized constructors are not allowed, there should be only default ctor"/> </module>
Example:
public class Test { public Test(Object c) { } // violation public Test(int a, HashMap<String, Integer> b) { } // violation public Test() { } // ok }
To violate if method name is 'test' or 'foo'
<module name="MatchXpath"> <property name="query" value="//METHOD_DEF[./IDENT[@text='test' or @text='foo']]"/> <message key="matchxpath.match" value="Method name should not be 'test' or 'foo'"/> </module>
Example:
public class Test { public void test() {} // violation public void getName() {} // ok public void foo() {} // violation public void sayHello() {} // ok }
To violate if new instance creation was done without var type
<module name="MatchXpath"> <property name="query" value="//VARIABLE_DEF[./ASSIGN/EXPR/LITERAL_NEW and not(./TYPE/IDENT[@text='var'])]"/> <message key="matchxpath.match" value="New instances should be created via 'var' keyword to avoid duplication of type reference in statement"/> </module>
Example:
public class Test { public void foo() { SomeObject a = new SomeObject(); // violation var b = new SomeObject(); // OK } }
Parent is
com.puppycrawl.tools.checkstyle.TreeWalker
Violation Message Keys:
-
matchxpath.match
- Since:
- 8.39
-
-
Nested Class Summary
-
Nested classes/interfaces inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
AbstractAutomaticBean.OutputStreamOptions
-
-
Field Summary
Fields Modifier and Type Field Description static java.lang.String
MSG_KEY
A key is pointing to the warning message text provided by user.private java.lang.String
query
Specify Xpath query.private net.sf.saxon.sxpath.XPathExpression
xpathExpression
Xpath expression.
-
Constructor Summary
Constructors Constructor Description MatchXpathCheck()
-
Method Summary
All Methods Instance Methods Concrete Methods Modifier and Type Method Description void
beginTree(DetailAST rootAST)
Called before the starting to process a tree.private java.util.List<DetailAST>
findMatchingNodesByXpathQuery(DetailAST rootAST)
Find nodes that match query.int[]
getAcceptableTokens()
The configurable token set.int[]
getDefaultTokens()
Returns the default token a check is interested in.int[]
getRequiredTokens()
The tokens that this check must be registered for.boolean
isCommentNodesRequired()
Whether comment nodes are required or not.void
setQuery(java.lang.String query)
Setter to specify Xpath query.-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractCheck
clearViolations, destroy, finishTree, getFileContents, getFilePath, getLine, getLineCodePoints, getLines, getTabWidth, getTokenNames, getViolations, init, leaveToken, log, log, log, setFileContents, setTabWidth, setTokens, visitToken
-
Methods inherited from class com.puppycrawl.tools.checkstyle.api.AbstractViolationReporter
finishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeverity
-
Methods inherited from class com.puppycrawl.tools.checkstyle.AbstractAutomaticBean
configure, contextualize, getConfiguration, setupChild
-
-
-
-
Field Detail
-
MSG_KEY
public static final java.lang.String MSG_KEY
A key is pointing to the warning message text provided by user.- See Also:
- Constant Field Values
-
query
private java.lang.String query
Specify Xpath query.
-
xpathExpression
private net.sf.saxon.sxpath.XPathExpression xpathExpression
Xpath expression.
-
-
Constructor Detail
-
MatchXpathCheck
public MatchXpathCheck()
-
-
Method Detail
-
setQuery
public void setQuery(java.lang.String query)
Setter to specify Xpath query.- Parameters:
query
- Xpath query.- Throws:
java.lang.IllegalStateException
- if creation of xpath expression fails
-
getDefaultTokens
public int[] getDefaultTokens()
Description copied from class:AbstractCheck
Returns the default token a check is interested in. Only used if the configuration for a check does not define the tokens.- Specified by:
getDefaultTokens
in classAbstractCheck
- Returns:
- the default tokens
- See Also:
TokenTypes
-
getAcceptableTokens
public int[] getAcceptableTokens()
Description copied from class:AbstractCheck
The configurable token set. Used to protect Checks against malicious users who specify an unacceptable token set in the configuration file. The default implementation returns the check's default tokens.- Specified by:
getAcceptableTokens
in classAbstractCheck
- Returns:
- the token set this check is designed for.
- See Also:
TokenTypes
-
getRequiredTokens
public int[] getRequiredTokens()
Description copied from class:AbstractCheck
The tokens that this check must be registered for.- Specified by:
getRequiredTokens
in classAbstractCheck
- Returns:
- the token set this must be registered for.
- See Also:
TokenTypes
-
isCommentNodesRequired
public boolean isCommentNodesRequired()
Description copied from class:AbstractCheck
Whether comment nodes are required or not.- Overrides:
isCommentNodesRequired
in classAbstractCheck
- Returns:
- false as a default value.
-
beginTree
public void beginTree(DetailAST rootAST)
Description copied from class:AbstractCheck
Called before the starting to process a tree. Ideal place to initialize information that is to be collected whilst processing a tree.- Overrides:
beginTree
in classAbstractCheck
- Parameters:
rootAST
- the root of the tree
-
findMatchingNodesByXpathQuery
private java.util.List<DetailAST> findMatchingNodesByXpathQuery(DetailAST rootAST)
Find nodes that match query.- Parameters:
rootAST
- root node- Returns:
- list of matching nodes
- Throws:
java.lang.IllegalStateException
- if evaluation of xpath query fails
-
-