View Javadoc

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