1
2
3
4 package net.sourceforge.pmd.lang.ast.xpath;
5
6 import java.util.Iterator;
7 import java.util.NoSuchElementException;
8
9 import net.sourceforge.pmd.lang.ast.Node;
10
11
12
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 = contextNode.jjtGetChildIndex() - 1;
47 if (prevPosition >= 0) {
48 return parentNode.jjtGetChild(prevPosition);
49 }
50 }
51 return null;
52 }
53
54 protected Node getNextSibling(Node contextNode) {
55 Node parentNode = contextNode.jjtGetParent();
56 if (parentNode != null) {
57 int nextPosition = contextNode.jjtGetChildIndex() + 1;
58 if (nextPosition < parentNode.jjtGetNumChildren()) {
59 return parentNode.jjtGetChild(nextPosition);
60 }
61 }
62 return null;
63 }
64
65 protected Node getFirstChild(Node contextNode) {
66 if (contextNode.jjtGetNumChildren() > 0) {
67 return contextNode.jjtGetChild(0);
68 } else {
69 return null;
70 }
71 }
72
73 protected Node getLastChild(Node contextNode) {
74 if (contextNode.jjtGetNumChildren() > 0) {
75 return contextNode.jjtGetChild(contextNode.jjtGetNumChildren() - 1);
76 } else {
77 return null;
78 }
79 }
80 }