01: package test.net.sourceforge.pmd.jsp.ast;
02:
03: import static org.junit.Assert.assertEquals;
04: import net.sourceforge.pmd.ast.Node;
05: import net.sourceforge.pmd.jsp.ast.JspCharStream;
06: import net.sourceforge.pmd.jsp.ast.JspParser;
07:
08: import java.io.StringReader;
09: import java.util.HashSet;
10: import java.util.Set;
11:
12: public abstract class AbstractJspNodesTst {
13:
14: public <T> void assertNumberOfNodes(Class<T> clazz, String source,
15: int number) {
16: Set<T> nodes = getNodes(clazz, source);
17: assertEquals("Exactly " + number + " element(s) expected",
18: number, nodes.size());
19: }
20:
21: /**
22: * Run the JSP parser on the source, and return the nodes of type clazz.
23: *
24: * @param clazz
25: * @param source
26: * @return Set
27: */
28: public <T> Set<T> getNodes(Class<T> clazz, String source) {
29: JspParser parser = new JspParser(new JspCharStream(
30: 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: * @param node
60: * @param nodex
61: * @param clazz
62: */
63: private <T> void addNodeAndSubnodes(Node node, Set<T> nodes,
64: Class<T> clazz) {
65: if (null != node) {
66: if ((null == clazz) || (clazz.equals(node.getClass()))) {
67: nodes.add((T) node);
68: }
69: }
70: for (int i = 0; i < node.jjtGetNumChildren(); i++) {
71: addNodeAndSubnodes(node.jjtGetChild(i), nodes, clazz);
72: }
73: }
74:
75: }
|