View Javadoc

    1   package net.sourceforge.pmd.lang.jsp.ast;
    2
    3   import static org.junit.Assert.assertEquals;
    4
    5   import java.io.StringReader;
    6   import java.util.HashSet;
    7   import java.util.Set;
    8
    9   import net.sourceforge.pmd.lang.ast.JavaCharStream;
    10  import net.sourceforge.pmd.lang.ast.Node;
    11  import net.sourceforge.pmd.lang.jsp.ast.JspParser;
    12
    13  public abstract class AbstractJspNodesTst {
    14
    15      public <T> void assertNumberOfNodes(Class<T> clazz, String source, int number) {
    16          Set<T> 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 <T> Set<T> getNodes(Class<T> clazz, String source) {
    28          JspParser parser = new JspParser(new JavaCharStream(new StringReader(source)));
    29          Node rootNode = parser.CompilationUnit();
    30          Set<T> nodes = new HashSet<T>();
    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 <T> Set<T> getNodesOfType(Class<T> clazz, Set allNodes) {
    44          Set<T> result = new HashSet<T>();
    45          for (Object node: allNodes) {
    46              if (clazz.equals(node.getClass())) {
    47                  result.add((T)node);
    48              }
    49          }
    50          return result;
    51      }
    52
    53      /**
    54       * Add the given node and its subnodes to the set of nodes. If clazz is not null, only
    55       * nodes of the given class are put in the set of nodes.
    56       */
    57      private <T> void addNodeAndSubnodes(Node node, Set<T> nodes, Class<T> clazz) {
    58          if (null != node) {
    59              if ((null == clazz) || (clazz.equals(node.getClass()))) {
    60                  nodes.add((T)node);
    61              }
    62  	        for (int i=0; i < node.jjtGetNumChildren(); i++) {
    63  	            addNodeAndSubnodes(node.jjtGetChild(i), nodes, clazz);
    64  	        }
    65          }
    66      }
    67
    68  }