View Javadoc

1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package net.sourceforge.pmd.jaxen;
5   import net.sourceforge.pmd.ast.Node;
6   
7   import java.util.Iterator;
8   import java.util.NoSuchElementException;
9   /***
10   * @author daniels
11   *
12   * To change this generated comment go to 
13   * Window>Preferences>Java>Code Generation>Code Template
14   */
15  public abstract class NodeIterator implements Iterator {
16  
17      private Node node;
18  
19      public NodeIterator(Node contextNode) {
20          this.node = getFirstNode(contextNode);
21      }
22  
23      public boolean hasNext() {
24          return node != null;
25      }
26  
27      public Object next() {
28          if (node == null)
29              throw new NoSuchElementException();
30          Node ret = node;
31          node = getNextNode(node);
32          return ret;
33      }
34  
35      public void remove() {
36          throw new UnsupportedOperationException();
37      }
38  
39      protected abstract Node getFirstNode(Node contextNode);
40  
41      protected abstract Node getNextNode(Node contextNode);
42  
43      protected Node getPreviousSibling(Node contextNode) {
44          Node parentNode = contextNode.jjtGetParent();
45          if(parentNode != null) {
46              int prevPosition = getPositionFromParent(contextNode) - 1;
47              if (prevPosition >= 0) {
48                  return parentNode.jjtGetChild(prevPosition);
49              }
50          }
51          return null;
52      }
53  
54      private int getPositionFromParent(Node contextNode) {
55          Node parentNode = contextNode.jjtGetParent();
56          for (int i = 0; i < parentNode.jjtGetNumChildren(); i++) {
57              if (parentNode.jjtGetChild(i) == contextNode) {
58                  return i;
59              }
60          }
61          throw new RuntimeException("Node was not a child of it's parent ???");
62      }
63  
64      protected Node getNextSibling(Node contextNode) {
65          Node parentNode = contextNode.jjtGetParent();
66          if(parentNode != null) {
67              int nextPosition = getPositionFromParent(contextNode) + 1;
68              if (nextPosition < parentNode.jjtGetNumChildren()) {
69                  return parentNode.jjtGetChild(nextPosition);
70              }
71          }
72          return null;
73      }
74  
75      protected Node getFirstChild(Node contextNode) {
76          if (contextNode.jjtGetNumChildren() > 0) {
77              return contextNode.jjtGetChild(0);
78          } else {
79              return null;
80          }
81      }
82  
83      protected Node getLastChild(Node contextNode) {
84          if (contextNode.jjtGetNumChildren() > 0) {
85              return contextNode.jjtGetChild(contextNode.jjtGetNumChildren() - 1);
86          } else {
87              return null;
88          }
89      }
90  }