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