1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package com.puppycrawl.tools.checkstyle.checks.coding;
21
22 import java.util.List;
23
24 import com.puppycrawl.tools.checkstyle.StatelessCheck;
25 import com.puppycrawl.tools.checkstyle.api.AbstractCheck;
26 import com.puppycrawl.tools.checkstyle.api.DetailAST;
27 import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
28 import com.puppycrawl.tools.checkstyle.xpath.AbstractNode;
29 import com.puppycrawl.tools.checkstyle.xpath.RootNode;
30 import net.sf.saxon.Configuration;
31 import net.sf.saxon.om.Item;
32 import net.sf.saxon.sxpath.XPathDynamicContext;
33 import net.sf.saxon.sxpath.XPathEvaluator;
34 import net.sf.saxon.sxpath.XPathExpression;
35 import net.sf.saxon.trans.XPathException;
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64 @StatelessCheck
65 public class MatchXpathCheck extends AbstractCheck {
66
67
68
69
70 public static final String MSG_KEY = "matchxpath.match";
71
72
73 private String query = "";
74
75
76 private XPathExpression xpathExpression;
77
78
79
80
81
82
83
84
85 public void setQuery(String query) {
86 this.query = query;
87 if (!query.isEmpty()) {
88 try {
89 final XPathEvaluator xpathEvaluator =
90 new XPathEvaluator(Configuration.newConfiguration());
91 xpathExpression = xpathEvaluator.createExpression(query);
92 }
93 catch (XPathException exc) {
94 throw new IllegalStateException("Creating Xpath expression failed: " + query, exc);
95 }
96 }
97 }
98
99 @Override
100 public int[] getDefaultTokens() {
101 return getRequiredTokens();
102 }
103
104 @Override
105 public int[] getAcceptableTokens() {
106 return getRequiredTokens();
107 }
108
109 @Override
110 public int[] getRequiredTokens() {
111 return CommonUtil.EMPTY_INT_ARRAY;
112 }
113
114 @Override
115 public boolean isCommentNodesRequired() {
116 return true;
117 }
118
119 @Override
120 public void beginTree(DetailAST rootAST) {
121 if (!query.isEmpty()) {
122 final List<DetailAST> matchingNodes = findMatchingNodesByXpathQuery(rootAST);
123 matchingNodes.forEach(node -> log(node, MSG_KEY));
124 }
125 }
126
127
128
129
130
131
132
133
134 private List<DetailAST> findMatchingNodesByXpathQuery(DetailAST rootAST) {
135 try {
136 final RootNode rootNode = new RootNode(rootAST);
137 final XPathDynamicContext xpathDynamicContext =
138 xpathExpression.createDynamicContext(rootNode);
139 final List<Item> matchingItems = xpathExpression.evaluate(xpathDynamicContext);
140 return matchingItems.stream()
141 .map(item -> (DetailAST) ((AbstractNode) item).getUnderlyingNode())
142 .toList();
143 }
144 catch (XPathException exc) {
145 throw new IllegalStateException("Evaluation of Xpath query failed: " + query, exc);
146 }
147 }
148 }