com.recurly.v3.Pager Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of api-client Show documentation
Show all versions of api-client Show documentation
The official Java client for Recurly's V3 API.
package com.recurly.v3;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.lang.reflect.Type;
import java.util.*;
import java.util.function.Consumer;
public class Pager implements Iterable {
public Pager(
String path, HashMap queryParams, BaseClient client, Type parameterizedType) {
this.next = path;
this.queryParams = queryParams;
this.client = client;
this.data = new ArrayList<>();
this.parameterizedType = parameterizedType;
this.more = true;
}
@SerializedName("has_more")
@Expose
private boolean more;
@SerializedName("next")
@Expose
private String next;
@Expose private List data;
private BaseClient client;
private Type parameterizedType;
private HashMap queryParams;
private boolean paramsConsumed;
public Pager.PagerIterator iterator() {
if (data.size() == 0 && this.hasMore()) this.getNextPage();
return new PagerIterator(data.toArray(), this);
}
public void forEach(Consumer super T> action) {
while (this.next != null) {
this.getNextPage();
for (T t : this) action.accept(t);
}
}
public void eachItem(Consumer super T> action) {
this.forEach(action);
}
public boolean hasMore() {
return more;
}
public String getNext() {
return next;
}
public List getData() {
return data;
}
public T getFirst() {
HashMap firstParams = (HashMap)this.queryParams.clone();
firstParams.put("limit", 1);
Pager pager =
this.client.makeRequest("GET", this.next, firstParams, this.parameterizedType);
PagerIterator iterator = pager.iterator();
if (iterator.hasNext()) {
return (T)iterator.next();
} else {
return null;
}
}
public int getCount() {
return this.client.getRecordCount(this.next, this.queryParams);
}
public void getNextPage() {
if (this.next == null) {
throw new NoSuchElementException();
}
Pager pager =
this.client.makeRequest("GET", this.next, this.consumeParams(), this.parameterizedType);
this.clone(pager);
}
private void clone(Pager pager) {
this.next = pager.getNext();
this.more = pager.hasMore();
this.data = pager.getData();
}
private HashMap consumeParams() {
if (this.paramsConsumed) return null;
this.paramsConsumed = true;
return this.queryParams;
}
private class PagerIterator implements Iterator {
public PagerIterator(Object[] data, Pager pager) {
this.data = data;
this.pager = pager;
}
private int position = 0;
private Object[] data;
private Pager pager;
public boolean hasNext() {
return position < this.data.length || pager.hasMore();
}
public Object next() {
if (position == this.data.length && pager.hasMore()) {
pager.getNextPage();
this.data = pager.getData().toArray();
position = 0;
}
return this.data[position++];
}
}
}