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
029public class PagingIterator<T> implements Iterator<T> {
030
031        public interface PageFetcher<T> {
032                void fetchNextPage(int thePageIndex, int theBatchSize, Consumer<T> theConsumer);
033        }
034
035        static final int PAGE_SIZE = 100;
036
037        private int myPage;
038
039        private boolean myIsFinished;
040
041        private final LinkedList<T> myCurrentBatch = new LinkedList<>();
042
043        private final PageFetcher<T> myFetcher;
044
045        public PagingIterator(PageFetcher<T> theFetcher) {
046                myFetcher = theFetcher;
047        }
048
049        @Override
050        public boolean hasNext() {
051                fetchNextBatch();
052
053                return !myCurrentBatch.isEmpty();
054        }
055
056        @Override
057        public T next() {
058                fetchNextBatch();
059
060                if (myCurrentBatch.isEmpty()) {
061                        throw new NoSuchElementException(Msg.code(2098) + " Nothing to fetch");
062                }
063
064                return myCurrentBatch.remove(0);
065        }
066
067        private void fetchNextBatch() {
068                if (!myIsFinished && myCurrentBatch.isEmpty()) {
069                        myFetcher.fetchNextPage(myPage, PAGE_SIZE, myCurrentBatch::add);
070                        myPage++;
071                        myIsFinished = myCurrentBatch.size() < PAGE_SIZE;
072                }
073        }
074}