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

org.openfact.models.jpa.ScrollPagingAdapter 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 ScrollPagingAdapter implements ScrollModel {

    protected int size;
    protected TypedQuery query;
    protected Function, T> converter;

    protected Class type;

    public ScrollPagingAdapter(Class type, TypedQuery query, Function, T> converter) {
        this(type, query, converter, 10);
    }

    public ScrollPagingAdapter(Class type, TypedQuery query, Function, T> 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 boolean hasMore;

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

        @Override
        public boolean hasNext() {
            if (results == null) {
                refreshResults();
                return !results.isEmpty();
            }
            return hasMore;
        }

        @Override
        public T next() {
            if (results.isEmpty()) {
                throw new NoSuchElementException();
            }
            return (T) converter.apply((List) results);
        }

        private void refreshResults() {
            int start = (page - 1) * pageSize;
            List results = (List) query.setFirstResult(start).setMaxResults(pageSize + 1).getResultList();
            page++;
            if (results.size() > pageSize) {
                hasMore = true;
                results.remove(results.size());
            }
            this.results = results;
        }

    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy