1   package test.net.sourceforge.pmd.jsp.ast;
2   
3   import static org.junit.Assert.assertEquals;
4   import net.sourceforge.pmd.ast.Node;
5   import net.sourceforge.pmd.jsp.ast.JspCharStream;
6   import net.sourceforge.pmd.jsp.ast.JspParser;
7   
8   import java.io.StringReader;
9   import java.util.HashSet;
10  import java.util.Set;
11  public abstract class AbstractJspNodesTst {
12  
13      public <T> void assertNumberOfNodes(Class<T> clazz, String source, int number) {
14          Set<T> nodes = getNodes(clazz, source);
15          assertEquals("Exactly " + number + " element(s) expected", number, nodes.size());
16      }
17  
18      /**
19       * Run the JSP parser on the source, and return the nodes of type clazz.
20       *
21       * @param clazz
22       * @param source
23       * @return Set 
24       */
25      public <T> Set<T> getNodes(Class<T> clazz, String source) {
26          JspParser parser = new JspParser(new JspCharStream(new StringReader(source)));
27          Node rootNode = parser.CompilationUnit();
28          Set<T> nodes = new HashSet<T>();
29          addNodeAndSubnodes(rootNode, nodes, clazz);
30          return nodes;
31      }
32  
33      /**
34       * Return a subset of allNodes, containing the items in allNodes
35       * that are of the given type.
36       *
37       * @param clazz
38       * @param allNodes
39       * @return Set 
40       */
41      public <T> Set<T> getNodesOfType(Class<T> clazz, Set allNodes) {
42          Set<T> result = new HashSet<T>();
43          for (Object node: allNodes) {
44              if (clazz.equals(node.getClass())) {
45                  result.add((T)node);
46              }
47          }
48          return result;
49      }
50  
51      /**
52       * Add the given node and its subnodes to the set of nodes. If clazz is not null, only
53       * nodes of the given class are put in the set of nodes.
54       *
55       * @param node
56       * @param nodex
57       * @param clazz
58       */
59      private <T> void addNodeAndSubnodes(Node node, Set<T> nodes, Class<T> clazz) {
60          if (null != node) {
61              if ((null == clazz) || (clazz.equals(node.getClass()))) {
62                  nodes.add((T)node);
63              }
64          }
65          for (int i = 0; i < node.jjtGetNumChildren(); i++) {
66              addNodeAndSubnodes(node.jjtGetChild(i), nodes, clazz);
67          }
68      }
69  
70  }