View Javadoc
1   package ca.uhn.fhir.jpa.util;
2   
3   /*
4    * #%L
5    * HAPI FHIR JPA Server
6    * %%
7    * Copyright (C) 2014 - 2019 University Health Network
8    * %%
9    * Licensed under the Apache License, Version 2.0 (the "License");
10   * you may not use this file except in compliance with the License.
11   * You may obtain a copy of the License at
12   *
13   * http://www.apache.org/licenses/LICENSE-2.0
14   *
15   * Unless required by applicable law or agreed to in writing, software
16   * distributed under the License is distributed on an "AS IS" BASIS,
17   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18   * See the License for the specific language governing permissions and
19   * limitations under the License.
20   * #L%
21   */
22  
23  import org.apache.commons.lang3.Validate;
24  import org.hibernate.ScrollableResults;
25  
26  import java.io.Closeable;
27  import java.util.Iterator;
28  
29  public class ScrollableResultsIterator<T extends Object> extends BaseIterator<T> implements Iterator<T>, Closeable {
30  	private boolean hasNext;
31  	private T myNext;
32  	private ScrollableResults myScroll;
33  
34  	public ScrollableResultsIterator(ScrollableResults theScroll) {
35  		myScroll = theScroll;
36  	}
37  
38  	@SuppressWarnings("unchecked")
39  	private void ensureHaveNext() {
40  		if (myNext == null) {
41  			if (myScroll.next()) {
42  				hasNext = true;
43  				myNext = (T) myScroll.get(0);
44  			} else {
45  				hasNext = false;
46  			}
47  		}
48  	}
49  
50  	@Override
51  	public boolean hasNext() {
52  		ensureHaveNext();
53  		return hasNext;
54  	}
55  
56  	@Override
57  	public T next() {
58  		ensureHaveNext();
59  		Validate.isTrue(hasNext);
60  		T next = myNext;
61  		myNext = null;
62  		return next;
63  	}
64  
65  
66  	@Override
67  	public void close() {
68  		if (myScroll != null) {
69  			myScroll.close();
70  			myScroll = null;
71  		}
72  	}
73  
74  }