com.twilio.base.ResourceSet Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of twilio Show documentation
Show all versions of twilio Show documentation
Twilio Java Helper Library
package com.twilio.base;
import com.twilio.http.TwilioRestClient;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* A collection of resources.
*
* @param type of the resource
*/
public class ResourceSet implements Iterable {
private final Reader reader;
private final TwilioRestClient client;
private boolean autoPaging;
private long pages = 1;
private long pageLimit = Long.MAX_VALUE;
private long processed = 0;
private Page page;
private Iterator iterator;
/**
* Initialize the resource set.
*
* @param reader reader used to fetch next page
* @param client client used to make requests
* @param page page of data
*/
public ResourceSet(final Reader reader, final TwilioRestClient client, final Page page) {
this.reader = reader;
this.client = client;
this.page = page;
this.iterator = page.getRecords().iterator();
this.autoPaging = true;
if (reader.getLimit() != null) {
this.pageLimit = (long)(Math.ceil((double)reader.getLimit() / (double)page.getPageSize()));
}
}
public boolean isAutoPaging() {
return autoPaging;
}
public ResourceSet setAutoPaging(final boolean autoPaging) {
this.autoPaging = autoPaging;
return this;
}
public Integer getPageSize() {
return page.getPageSize();
}
public ResourceSet setPageSize(final int pageSize) {
reader.pageSize(pageSize);
return this;
}
public Long getLimit() {
return reader.getLimit();
}
public ResourceSet setLimit(final long limit) {
reader.limit(limit);
return this;
}
public long getPageLimit() {
return pageLimit;
}
@Override
public Iterator iterator() {
return new ResourceSetIterator<>(this);
}
private void fetchNextPage() {
if (!page.hasNextPage() || pages >= pageLimit) {
return;
}
pages++;
page = reader.nextPage(page, client);
iterator = page.getRecords().iterator();
}
private class ResourceSetIterator implements Iterator {
private final ResourceSet resourceSet;
public ResourceSetIterator(final ResourceSet resourceSet) {
this.resourceSet = resourceSet;
}
@Override
public boolean hasNext() {
if (resourceSet.getLimit() != null && resourceSet.processed >= resourceSet.getLimit()) {
return false;
}
return resourceSet.iterator.hasNext();
}
@Override
public E next() {
if (resourceSet == null || resourceSet.iterator == null) {
throw new NoSuchElementException();
}
E element = resourceSet.iterator.next();
if (resourceSet.isAutoPaging() && !resourceSet.iterator.hasNext()) {
resourceSet.fetchNextPage();
}
resourceSet.processed++;
return element;
}
@Override
public void remove() {
if (resourceSet.iterator != null) {
resourceSet.processed++;
resourceSet.iterator.remove();
}
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy