01: package org.acm.seguin.pmd.jaxen;
02:
03: import net.sourceforge.jrefactory.ast.Node;
04:
05: import java.util.Iterator;
06: import java.util.NoSuchElementException;
07:
08: /**
09: * @author daniels
10: *
11: * To change this generated comment go to
12: * Window>Preferences>Java>Code Generation>Code Template
13: */
14: public abstract class NodeIterator implements Iterator {
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 Object next() {
27: if (node == null)
28: throw new NoSuchElementException();
29: Node ret = node;
30: node = getNextNode(node);
31: return ret;
32: }
33:
34: public void remove() {
35: throw new UnsupportedOperationException();
36: }
37:
38: protected abstract Node getFirstNode(Node contextNode);
39:
40: protected abstract Node getNextNode(Node contextNode);
41:
42: protected Node getPreviousSibling(Node contextNode) {
43: Node parentNode = contextNode.jjtGetParent();
44: if (parentNode != null) {
45: int prevPosition = getPositionFromParent(contextNode) - 1;
46: if (prevPosition >= 0) {
47: return parentNode.jjtGetChild(prevPosition);
48: }
49: }
50: return null;
51: }
52:
53: private int getPositionFromParent(Node contextNode) {
54: Node parentNode = contextNode.jjtGetParent();
55: for (int i = 0; i < parentNode.jjtGetNumChildren(); i++) {
56: if (parentNode.jjtGetChild(i) == contextNode) {
57: return i;
58: }
59: }
60: throw new RuntimeException(
61: "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.jjtGetFirstChild();
78: } else {
79: return null;
80: }
81: }
82:
83: protected Node getLastChild(Node contextNode) {
84: if (contextNode.jjtGetNumChildren() > 0) {
85: return contextNode.jjtGetChild(contextNode
86: .jjtGetNumChildren() - 1);
87: } else {
88: return null;
89: }
90: }
91: }
|