1 package net.sourceforge.pmd.lang.jsp.ast;
2
3 import static org.junit.Assert.assertEquals;
4
5 import java.io.StringReader;
6 import java.util.HashSet;
7 import java.util.Set;
8
9 import net.sourceforge.pmd.lang.ast.JavaCharStream;
10 import net.sourceforge.pmd.lang.ast.Node;
11 import net.sourceforge.pmd.lang.jsp.ast.JspParser;
12
13 public abstract class AbstractJspNodesTst {
14
15 public <T> void assertNumberOfNodes(Class<T> clazz, String source, int number) {
16 Set<T> nodes = getNodes(clazz, source);
17 assertEquals("Exactly " + number + " element(s) expected", number, nodes.size());
18 }
19
20
21
22
23
24
25
26
27 public <T> Set<T> getNodes(Class<T> clazz, String source) {
28 JspParser parser = new JspParser(new JavaCharStream(new StringReader(source)));
29 Node rootNode = parser.CompilationUnit();
30 Set<T> nodes = new HashSet<T>();
31 addNodeAndSubnodes(rootNode, nodes, clazz);
32 return nodes;
33 }
34
35
36
37
38
39
40
41
42
43 public <T> Set<T> getNodesOfType(Class<T> clazz, Set allNodes) {
44 Set<T> result = new HashSet<T>();
45 for (Object node: allNodes) {
46 if (clazz.equals(node.getClass())) {
47 result.add((T)node);
48 }
49 }
50 return result;
51 }
52
53
54
55
56
57 private <T> void addNodeAndSubnodes(Node node, Set<T> nodes, Class<T> clazz) {
58 if (null != node) {
59 if ((null == clazz) || (clazz.equals(node.getClass()))) {
60 nodes.add((T)node);
61 }
62 for (int i=0; i < node.jjtGetNumChildren(); i++) {
63 addNodeAndSubnodes(node.jjtGetChild(i), nodes, clazz);
64 }
65 }
66 }
67
68 }