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; 9 import java.util.HashSet; 10 import java.util.Iterator; 11 import java.util.Set; 12 13 public class AbstractJspNodesTst extends TestCase { 14 15 public void assertNumberOfNodes(Class clazz, String source, int number) { 16 Set 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 26 */ 27 public Set getNodes(Class clazz, String source) { 28 JspParser parser = new JspParser(new JspCharStream(new StringReader(source))); 29 Node rootNode = parser.CompilationUnit(); 30 Set nodes = new HashSet(); 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 42 */ 43 public Set getNodesOfType(Class clazz, Set allNodes) { 44 Set result = new HashSet(); 45 for (Iterator i = allNodes.iterator(); i.hasNext();) { 46 Object 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 nodes, Class 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 }