001/*-
002 * #%L
003 * HAPI FHIR - Core Library
004 * %%
005 * Copyright (C) 2014 - 2024 Smile CDR, Inc.
006 * %%
007 * Licensed under the Apache License, Version 2.0 (the "License");
008 * you may not use this file except in compliance with the License.
009 * You may obtain a copy of the License at
010 *
011 *      http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 * #L%
019 */
020package ca.uhn.fhir.model.api;
021
022import ca.uhn.fhir.i18n.Msg;
023
024import java.util.Iterator;
025import java.util.LinkedList;
026import java.util.NoSuchElementException;
027import java.util.function.Consumer;
028
029/**
030 * This paging iterator only works with already ordered queries
031 */
032public class PagingIterator<T> implements Iterator<T> {
033
034        public interface PageFetcher<T> {
035                void fetchNextPage(int thePageIndex, int theBatchSize, Consumer<T> theConsumer);
036        }
037
038        static final int DEFAULT_PAGE_SIZE = 100;
039
040        private int myPage;
041
042        private boolean myIsFinished;
043
044        private final LinkedList<T> myCurrentBatch = new LinkedList<>();
045
046        private final PageFetcher<T> myFetcher;
047
048        private final int myPageSize;
049
050        public PagingIterator(PageFetcher<T> theFetcher) {
051                this(DEFAULT_PAGE_SIZE, theFetcher);
052        }
053
054        public PagingIterator(int thePageSize, PageFetcher<T> theFetcher) {
055                assert thePageSize > 0 : "Page size must be a positive value";
056                myFetcher = theFetcher;
057                myPageSize = thePageSize;
058        }
059
060        @Override
061        public boolean hasNext() {
062                fetchNextBatch();
063
064                return !myCurrentBatch.isEmpty();
065        }
066
067        @Override
068        public T next() {
069                fetchNextBatch();
070
071                if (myCurrentBatch.isEmpty()) {
072                        throw new NoSuchElementException(Msg.code(2098) + " Nothing to fetch");
073                }
074
075                return myCurrentBatch.remove(0);
076        }
077
078        private void fetchNextBatch() {
079                if (!myIsFinished && myCurrentBatch.isEmpty()) {
080                        myFetcher.fetchNextPage(myPage, myPageSize, myCurrentBatch::add);
081                        myPage++;
082                        myIsFinished = myCurrentBatch.size() < myPageSize;
083                }
084        }
085}