1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.jxpath.ri.model.beans;
18
19 import java.util.ArrayList;
20 import java.util.List;
21
22 import org.apache.commons.jxpath.JXPathException;
23 import org.apache.commons.jxpath.ri.model.NodeIterator;
24 import org.apache.commons.jxpath.ri.model.NodePointer;
25
26
27
28
29
30
31
32
33 public abstract class CollectionNodeIterator implements NodeIterator {
34 private CollectionPointer pointer;
35 private boolean reverse;
36 private NodePointer startWith;
37 private int position;
38 private List collection;
39
40
41
42
43
44
45
46 protected CollectionNodeIterator(
47 CollectionPointer pointer,
48 boolean reverse,
49 NodePointer startWith) {
50 this.pointer = pointer;
51 this.reverse = reverse;
52 this.startWith = startWith;
53 }
54
55
56
57
58
59
60 protected abstract NodeIterator
61 getElementNodeIterator(NodePointer elementPointer);
62
63 public int getPosition() {
64 return position;
65 }
66
67 public boolean setPosition(int position) {
68 if (collection == null) {
69 prepare();
70 }
71
72 if (position < 1 || position > collection.size()) {
73 return false;
74 }
75 this.position = position;
76 return true;
77 }
78
79 public NodePointer getNodePointer() {
80 if (position == 0) {
81 return null;
82 }
83 return (NodePointer) collection.get(position - 1);
84 }
85
86
87
88
89 private void prepare() {
90 collection = new ArrayList();
91 NodePointer ptr = (NodePointer) pointer.clone();
92 int length = ptr.getLength();
93 for (int i = 0; i < length; i++) {
94 ptr.setIndex(i);
95 NodePointer elementPointer = ptr.getValuePointer();
96 NodeIterator iter = getElementNodeIterator(elementPointer);
97
98 for (int j = 1; iter.setPosition(j); j++) {
99 NodePointer childPointer = iter.getNodePointer();
100 if (reverse) {
101 collection.add(0, childPointer);
102 }
103 else {
104 collection.add(childPointer);
105 }
106 }
107 }
108 if (startWith != null) {
109 int index = collection.indexOf(startWith);
110 if (index == -1) {
111 throw new JXPathException(
112 "Invalid starting pointer for iterator: " + startWith);
113 }
114 while (collection.size() > index) {
115 if (!reverse) {
116 collection.remove(collection.size() - 1);
117 }
118 else {
119 collection.remove(0);
120 }
121 }
122 }
123 }
124 }