KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > test > net > sourceforge > pmd > jsp > ast > AbstractJspNodesTst


1 package test.net.sourceforge.pmd.jsp.ast;
2
3 import junit.framework.TestCase;
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 JavaDoc;
9 import java.util.HashSet JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.Set JavaDoc;
12
13 public class AbstractJspNodesTst extends TestCase {
14
15     public void assertNumberOfNodes(Class JavaDoc clazz, String JavaDoc source, int number) {
16         Set JavaDoc nodes = getNodes(clazz, source);
17         assertEquals("Exactly " + number + " element(s) expected", number, nodes.size());
18     }
19
20     /**
21      * Run the JSP parser on the source, and return the nodes of type clazz.
22      *
23      * @param clazz
24      * @param source
25      * @return Set
26      */

27     public Set JavaDoc getNodes(Class JavaDoc clazz, String JavaDoc source) {
28         JspParser parser = new JspParser(new JspCharStream(new StringReader JavaDoc(source)));
29         Node rootNode = parser.CompilationUnit();
30         Set JavaDoc nodes = new HashSet JavaDoc();
31         addNodeAndSubnodes(rootNode, nodes, clazz);
32         return nodes;
33     }
34
35     /**
36      * Return a subset of allNodes, containing the items in allNodes
37      * that are of the given type.
38      *
39      * @param clazz
40      * @param allNodes
41      * @return Set
42      */

43     public Set JavaDoc getNodesOfType(Class JavaDoc clazz, Set JavaDoc allNodes) {
44         Set JavaDoc result = new HashSet JavaDoc();
45         for (Iterator JavaDoc i = allNodes.iterator(); i.hasNext();) {
46             Object JavaDoc node = i.next();
47             if (clazz.equals(node.getClass())) {
48                 result.add(node);
49             }
50         }
51         return result;
52     }
53
54     /**
55      * Add the given node and its subnodes to the set of nodes. If clazz is not null, only
56      * nodes of the given class are put in the set of nodes.
57      *
58      * @param node
59      * @param nodex
60      * @param clazz
61      */

62     private void addNodeAndSubnodes(Node node, Set JavaDoc nodes, Class JavaDoc clazz) {
63         if (null != node) {
64             if ((null == clazz) || (clazz.equals(node.getClass()))) {
65                 nodes.add(node);
66             }
67         }
68         for (int i = 0; i < node.jjtGetNumChildren(); i++) {
69             addNodeAndSubnodes(node.jjtGetChild(i), nodes, clazz);
70         }
71     }
72
73 }
74
Popular Tags