com.distelli.persistence.PageIterator Maven / Gradle / Ivy
package com.distelli.persistence;
import java.util.Iterator;
/**
Intended Usage:
// Operate on batches of up to 100:
for ( PageIterator iter : new PageIterator()
.marker(marker)
.pageSize(100)
.forward() )
{
for ( Something something : manager.listSomething(iter) ) {
System.out.println(something);
}
}
*/
public class PageIterator implements Iterable, Iterator {
private boolean _isForward = true;
private String _marker = null;
private String _prevMarker = null;
private int _pageSize = Integer.MAX_VALUE;
private boolean _isFirstPage = true;
public PageIterator() {}
public PageIterator(PageIterator other) {
this._isForward = other._isForward;
this._marker = other._marker;
this._prevMarker = other._prevMarker;
this._pageSize = other._pageSize;
this._isFirstPage = other._isFirstPage;
}
@Override
public Iterator iterator() {
return this;
}
@Override
public boolean hasNext() {
return _isFirstPage || null != _marker;
}
@Override
public PageIterator next() {
return this;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
// Used for construction:
public PageIterator marker(String marker) {
_marker = marker;
return this;
}
public PageIterator pageSize(int pageSize) {
_pageSize = pageSize;
return this;
}
public PageIterator forward() {
_isForward = true;
return this;
}
public PageIterator backward() {
_isForward = false;
return this;
}
public PageIterator setIsForward(boolean isForward) {
_isForward = isForward;
return this;
}
// Used by DB implementation:
public boolean isForward() {
return _isForward;
}
public String getMarker() {
return _marker;
}
public String getPrevMarker() {
return _prevMarker;
}
// Actual iteration is done with this method. It MUST be called
// even if marker is null!
public void setMarker(String marker) {
_marker = marker;
_isFirstPage = false;
}
// This MUST be called even if null!
public void setPrevMarker(String prevMarker) {
_prevMarker = prevMarker;
}
public int getPageSize() {
return _pageSize;
}
}