1 16 package org.apache.commons.collections.iterators; 17 18 import java.util.Iterator ; 19 import java.util.NoSuchElementException ; 20 21 import org.apache.commons.collections.ArrayStack; 22 import org.apache.commons.collections.Transformer; 23 24 77 public class ObjectGraphIterator implements Iterator { 78 79 80 protected final ArrayStack stack = new ArrayStack(8); 81 82 protected Object root; 83 84 protected Transformer transformer; 85 86 87 protected boolean hasNext = false; 88 89 protected Iterator currentIterator; 90 91 protected Object currentValue; 92 93 protected Iterator lastUsedIterator; 94 95 105 public ObjectGraphIterator(Object root, Transformer transformer) { 106 super(); 107 if (root instanceof Iterator ) { 108 this.currentIterator = (Iterator ) root; 109 } else { 110 this.root = root; 111 } 112 this.transformer = transformer; 113 } 114 115 125 public ObjectGraphIterator(Iterator rootIterator) { 126 super(); 127 this.currentIterator = rootIterator; 128 this.transformer = null; 129 } 130 131 135 protected void updateCurrentIterator() { 136 if (hasNext) { 137 return; 138 } 139 if (currentIterator == null) { 140 if (root == null) { 141 } else { 143 if (transformer == null) { 144 findNext(root); 145 } else { 146 findNext(transformer.transform(root)); 147 } 148 root = null; 149 } 150 } else { 151 findNextByIterator(currentIterator); 152 } 153 } 154 155 160 protected void findNext(Object value) { 161 if (value instanceof Iterator ) { 162 findNextByIterator((Iterator ) value); 164 } else { 165 currentValue = value; 167 hasNext = true; 168 } 169 } 170 171 176 protected void findNextByIterator(Iterator iterator) { 177 if (iterator != currentIterator) { 178 if (currentIterator != null) { 180 stack.push(currentIterator); 181 } 182 currentIterator = iterator; 183 } 184 185 while (currentIterator.hasNext() && hasNext == false) { 186 Object next = currentIterator.next(); 187 if (transformer != null) { 188 next = transformer.transform(next); 189 } 190 findNext(next); 191 } 192 if (hasNext) { 193 } else if (stack.isEmpty()) { 195 } else { 197 currentIterator = (Iterator ) stack.pop(); 199 findNextByIterator(currentIterator); 200 } 201 } 202 203 209 public boolean hasNext() { 210 updateCurrentIterator(); 211 return hasNext; 212 } 213 214 220 public Object next() { 221 updateCurrentIterator(); 222 if (hasNext == false) { 223 throw new NoSuchElementException ("No more elements in the iteration"); 224 } 225 lastUsedIterator = currentIterator; 226 Object result = currentValue; 227 currentValue = null; 228 hasNext = false; 229 return result; 230 } 231 232 245 public void remove() { 246 if (lastUsedIterator == null) { 247 throw new IllegalStateException ("Iterator remove() cannot be called at this time"); 248 } 249 lastUsedIterator.remove(); 250 lastUsedIterator = null; 251 } 252 253 } 254 | Popular Tags |