001/*-
002 * #%L
003 * HAPI FHIR JPA Server
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.jpa.dao.search;
021
022import ca.uhn.fhir.jpa.search.builder.ISearchQueryExecutor;
023import org.hibernate.search.engine.search.query.SearchScroll;
024import org.hibernate.search.engine.search.query.SearchScrollResult;
025
026import java.util.Iterator;
027
028/**
029 * Adapt Hibernate Search SearchScroll paging result to our ISearchQueryExecutor
030 */
031public class SearchScrollQueryExecutorAdaptor implements ISearchQueryExecutor {
032        private final SearchScroll<Long> myScroll;
033        private Iterator<Long> myCurrentIterator;
034
035        public SearchScrollQueryExecutorAdaptor(SearchScroll<Long> theScroll) {
036                myScroll = theScroll;
037                advanceNextScrollPage();
038        }
039
040        /**
041         * Advance one page (i.e. SearchScrollResult).
042         * Note: the last page will have 0 hits.
043         */
044        private void advanceNextScrollPage() {
045                SearchScrollResult<Long> scrollResults = myScroll.next();
046                myCurrentIterator = scrollResults.hits().iterator();
047        }
048
049        @Override
050        public void close() {
051                myScroll.close();
052        }
053
054        @Override
055        public boolean hasNext() {
056                return myCurrentIterator.hasNext();
057        }
058
059        @Override
060        public Long next() {
061                Long result = myCurrentIterator.next();
062                // was this the last in the current scroll page?
063                if (!myCurrentIterator.hasNext()) {
064                        advanceNextScrollPage();
065                }
066                return result;
067        }
068}