NodeIterator.java
01 /**
02  * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
03  */
04 package net.sourceforge.pmd.lang.ast.xpath;
05 
06 import java.util.Iterator;
07 import java.util.NoSuchElementException;
08 
09 import net.sourceforge.pmd.lang.ast.Node;
10 
11 /**
12  @author daniels
13  */
14 public abstract class NodeIterator implements Iterator<Node> {
15 
16     private Node node;
17 
18     public NodeIterator(Node contextNode) {
19         this.node = getFirstNode(contextNode);
20     }
21 
22     public boolean hasNext() {
23         return node != null;
24     }
25 
26     public Node next() {
27         if (node == null) {
28             throw new NoSuchElementException();
29         }
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(contextNode1;
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(contextNode1;
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 }