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

org.openfact.models.jpa.ScrollAdapter Maven / Gradle / Ivy

There is a newer version: 1.1.3.Final
Show newest version
package org.openfact.models.jpa;

import org.openfact.models.ScrollModel;

import javax.persistence.TypedQuery;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.function.Function;

public class ScrollAdapter implements ScrollModel {

    protected int size;
    protected TypedQuery query;
    protected Function converter;

    protected Class type;

    public ScrollAdapter(Class type, TypedQuery query, Function converter) {
        this(type, query, converter, 10);
    }

    public ScrollAdapter(Class type, TypedQuery query, Function converter, int size) {
        this.type = type;
        this.query = query;
        this.converter = converter;
        this.size = size;
    }

    @Override
    public Iterator iterator() {
        return new PageIterator();
    }

    class PageIterator implements Iterator {

        private int page;
        private int pageSize;
        private List results;

        private int current;

        public PageIterator() {
            this.page = 1;
            this.pageSize = size;
        }

        @Override
        public boolean hasNext() {
            if (results == null) {
                refreshResults();
            }
            if (current < results.size()) {
                return true;
            } else {
                if (current == pageSize) {
                    refreshResults();
                    return hasNext();
                } else {
                    return false;
                }
            }
        }

        @Override
        public T next() {
            R r = results.get(current++);
            if (r == null) {
                throw new NoSuchElementException();
            }
            return (T) converter.apply(type.cast(r));
        }

        private void refreshResults() {
            int start = (page - 1) * pageSize;
            results = (List) query.setFirstResult(start).setMaxResults(pageSize).getResultList();
            page++;
            current = 0;
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy