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.interceptor;
021
022import ca.uhn.fhir.interceptor.api.Hook;
023import ca.uhn.fhir.interceptor.api.Interceptor;
024import ca.uhn.fhir.interceptor.api.Pointcut;
025import ca.uhn.fhir.jpa.searchparam.SearchParameterMap;
026import ca.uhn.fhir.rest.api.server.RequestDetails;
027import org.apache.commons.lang3.Validate;
028
029/**
030 * This interceptor for the HAPI FHIR JPA server forces all queries to
031 * be performed as offset queries. This means that the query cache will
032 * not be used and searches will never result in any writes to the
033 * database.
034 */
035@Interceptor
036public class ForceOffsetSearchModeInterceptor {
037
038        /**
039         * Default value for {@link #setDefaultCount(Integer)}
040         */
041        public static final int DEFAULT_DEFAULT_COUNT = 100;
042
043        private Integer myDefaultCount = DEFAULT_DEFAULT_COUNT;
044
045        public void setDefaultCount(Integer theDefaultCount) {
046                Validate.notNull(theDefaultCount, "theDefaultCount must not be null");
047                myDefaultCount = theDefaultCount;
048        }
049
050        @Hook(Pointcut.STORAGE_PRESEARCH_REGISTERED)
051        public void storagePreSearchRegistered(SearchParameterMap theMap, RequestDetails theRequestDetails) {
052
053                // If the params indicate a synchronous search, it doesn't make
054                // sense to inject any offset processing since the search
055                // will be handled synchronously anyhow
056                if (theMap.isLoadSynchronous()) {
057                        return;
058                }
059
060                if (theMap.getOffset() == null) {
061                        theMap.setOffset(0);
062                }
063                if (theMap.getCount() == null) {
064                        theMap.setCount(myDefaultCount);
065                }
066        }
067}