All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.braintreegateway.ResourceCollection Maven / Gradle / Ivy

The newest version!
package com.braintreegateway;

import com.braintreegateway.util.NodeWrapper;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * A collection used to page through query or search results.
 *
 * @param 
 *            type of object being paged, e.g. {@link Transaction} or
 *            {@link Customer}.
 */
public class ResourceCollection implements Iterable {

    private class PagedIterator implements Iterator {
        private ResourceCollection resourceCollection;
        private List ids;
        private int pageSize;
        private int index;
        private int nextIndexToFetch;
        private List items;

        public PagedIterator(ResourceCollection resourceCollection) {
            this.resourceCollection = resourceCollection;
            this.ids = resourceCollection.ids;
            this.pageSize = resourceCollection.pageSize;
            this.index = 0;
            this.nextIndexToFetch = 0;
            this.items = new ArrayList();
        }

        private List nextBatchOfIds() {
            int lastIdIndex = nextIndexToFetch + pageSize;
            if (lastIdIndex > ids.size()) {
                lastIdIndex = ids.size();
            }

            List nextIds = ids.subList(nextIndexToFetch, lastIdIndex);
            nextIndexToFetch = lastIdIndex;

            return nextIds;
        }

        public boolean hasNext() {
            if (nextIndexToFetch < ids.size() && index == items.size()) {
                this.items = resourceCollection.pager.getPage(nextBatchOfIds());
                this.index = 0;
            }

            if (index < items.size()) {
                return true;
            }
            return false;
        }

        public E next() {
            E item = items.get(index);
            index++;
            return item;
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    private List ids;
    private Pager pager;
    private int pageSize;

    public ResourceCollection(Pager pager, NodeWrapper response) {
        this.pager = pager;
        pageSize = response.findInteger("page-size");
        ids = response.findAllStrings("ids/*");
    }

    /**
     * Returns the approximate total size of the collection.
     *
     * @return Approximate size of collection
     */
    public int getMaximumSize() {
        return ids.size();
    }

    public Iterator iterator() {
        return new PagedIterator(this);
    }

    public T getFirst() {
        return pager.getPage(ids.subList(0, 1)).get(0);
    }

    public List getIds() {
        return ids;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy