View Javadoc
1   /*
2    * Copyright (C) 2007-2012 Argeo GmbH
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *         http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.argeo.jcr;
17  
18  import java.util.Collection;
19  import java.util.Iterator;
20  import java.util.NoSuchElementException;
21  
22  import javax.jcr.Node;
23  import javax.jcr.NodeIterator;
24  
25  /** Wraps a collection of nodes in order to read it as a {@link NodeIterator} */
26  public class CollectionNodeIterator implements NodeIterator {
27  	private final Long collectionSize;
28  	private final Iterator<Node> iterator;
29  	private Integer position = 0;
30  
31  	public CollectionNodeIterator(Collection<Node> nodes) {
32  		super();
33  		this.collectionSize = (long) nodes.size();
34  		this.iterator = nodes.iterator();
35  	}
36  
37  	public void skip(long skipNum) {
38  		if (skipNum < 0)
39  			throw new IllegalArgumentException(
40  					"Skip count has to be positive: " + skipNum);
41  
42  		for (long i = 0; i < skipNum; i++) {
43  			if (!hasNext())
44  				throw new NoSuchElementException("Last element past (position="
45  						+ getPosition() + ")");
46  			nextNode();
47  		}
48  	}
49  
50  	public long getSize() {
51  		return collectionSize;
52  	}
53  
54  	public long getPosition() {
55  		return position;
56  	}
57  
58  	public boolean hasNext() {
59  		return iterator.hasNext();
60  	}
61  
62  	public Object next() {
63  		return nextNode();
64  	}
65  
66  	public void remove() {
67  		iterator.remove();
68  	}
69  
70  	public Node nextNode() {
71  		Node node = iterator.next();
72  		position++;
73  		return node;
74  	}
75  
76  }