001/*-
002 * #%L
003 * HAPI FHIR JPA - Search Parameters
004 * %%
005 * Copyright (C) 2014 - 2025 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.searchparam;
021
022import ca.uhn.fhir.context.FhirContext;
023import ca.uhn.fhir.context.RuntimeResourceDefinition;
024import ca.uhn.fhir.context.RuntimeSearchParam;
025import ca.uhn.fhir.i18n.Msg;
026import ca.uhn.fhir.interceptor.model.RequestPartitionId;
027import ca.uhn.fhir.jpa.model.util.JpaConstants;
028import ca.uhn.fhir.jpa.searchparam.util.JpaParamUtil;
029import ca.uhn.fhir.model.api.IQueryParameterAnd;
030import ca.uhn.fhir.model.api.IQueryParameterType;
031import ca.uhn.fhir.model.api.Include;
032import ca.uhn.fhir.rest.api.Constants;
033import ca.uhn.fhir.rest.api.QualifiedParamList;
034import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum;
035import ca.uhn.fhir.rest.api.SearchIncludeDeletedEnum;
036import ca.uhn.fhir.rest.api.SearchTotalModeEnum;
037import ca.uhn.fhir.rest.param.DateRangeParam;
038import ca.uhn.fhir.rest.param.ParameterUtil;
039import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
040import ca.uhn.fhir.rest.server.util.ISearchParamRegistry;
041import ca.uhn.fhir.rest.server.util.MatchUrlUtil;
042import ca.uhn.fhir.util.ReflectionUtil;
043import ca.uhn.fhir.util.UrlUtil;
044import com.google.common.collect.ArrayListMultimap;
045import org.apache.http.NameValuePair;
046import org.springframework.beans.factory.annotation.Autowired;
047
048import java.util.HashSet;
049import java.util.List;
050import java.util.Set;
051
052import static ca.uhn.fhir.jpa.searchparam.ResourceMetaParams.STRICT_RESOURCE_META_PARAMS;
053import static org.apache.commons.lang3.StringUtils.isBlank;
054import static org.apache.commons.lang3.StringUtils.isNotBlank;
055
056public class MatchUrlService {
057
058        public static final Set<String> COMPATIBLE_PARAMS_NO_RES_TYPE =
059                        Set.of(Constants.PARAM_INCLUDE_DELETED, Constants.PARAM_LASTUPDATED);
060        public static final Set<String> COMPATIBLE_PARAMS_GIVEN_RES_TYPE =
061                        Set.of(Constants.PARAM_INCLUDE_DELETED, Constants.PARAM_LASTUPDATED, Constants.PARAM_ID);
062
063        @Autowired
064        private FhirContext myFhirContext;
065
066        @Autowired
067        private ISearchParamRegistry mySearchParamRegistry;
068
069        public MatchUrlService() {
070                super();
071        }
072
073        public MatchUrlService(FhirContext theFhirContext, ISearchParamRegistry theSearchParamRegistry) {
074                myFhirContext = theFhirContext;
075                mySearchParamRegistry = theSearchParamRegistry;
076        }
077
078        public SearchParameterMap translateMatchUrl(
079                        String theMatchUrl, RuntimeResourceDefinition theResourceDefinition, Flag... theFlags) {
080                SearchParameterMap paramMap = new SearchParameterMap();
081                List<NameValuePair> parameters = MatchUrlUtil.translateMatchUrl(theMatchUrl);
082
083                ArrayListMultimap<String, QualifiedParamList> nameToParamLists = ArrayListMultimap.create();
084                for (NameValuePair next : parameters) {
085                        if (isBlank(next.getValue())) {
086                                continue;
087                        }
088
089                        String paramName = next.getName();
090                        String qualifier = null;
091                        for (int i = 0; i < paramName.length(); i++) {
092                                switch (paramName.charAt(i)) {
093                                        case '.':
094                                        case ':':
095                                                qualifier = paramName.substring(i);
096                                                paramName = paramName.substring(0, i);
097                                                i = Integer.MAX_VALUE - 1;
098                                                break;
099                                }
100                        }
101
102                        QualifiedParamList paramList =
103                                        QualifiedParamList.splitQueryStringByCommasIgnoreEscape(qualifier, next.getValue());
104                        nameToParamLists.put(paramName, paramList);
105                }
106
107                boolean hasNoResourceType = hasNoResourceTypeInUrl(theMatchUrl, theResourceDefinition);
108
109                if (hasNoResourceType && !isSupportedQueryForNoProvidedResourceType(nameToParamLists.keySet())) {
110                        // Of all the general FHIR search parameters: https://hl7.org/fhir/R4/search.html#table
111                        // We can _only_ process the parameters on resource.meta fields for server requests
112                        // The following require a provided resource type because:
113                        // - Both _text and _content requires the FullTextSearchSvc and can only be performed on DomainResources
114                        // - _id since it is part of the unique constraint in the DB (see ResourceTableDao)
115                        // - Both _list and _has allows complex chaining with other resource-specific search params
116                        String errorMsg = myFhirContext.getLocalizer().getMessage(MatchUrlService.class, "noResourceType");
117                        throw new IllegalArgumentException(Msg.code(2742) + errorMsg);
118                }
119
120                for (String nextParamName : nameToParamLists.keySet()) {
121                        List<QualifiedParamList> paramList = nameToParamLists.get(nextParamName);
122
123                        if (theFlags != null) {
124                                for (Flag next : theFlags) {
125                                        next.process(nextParamName, paramList, paramMap);
126                                }
127                        }
128
129                        if (Constants.PARAM_INCLUDE_DELETED.equals(nextParamName)) {
130                                validateParamsAreCompatibleForDeleteOrThrow(nameToParamLists.keySet(), hasNoResourceType);
131                                paramMap.setSearchIncludeDeletedMode(
132                                                SearchIncludeDeletedEnum.fromCode(paramList.get(0).get(0)));
133                        } else if (Constants.PARAM_LASTUPDATED.equals(nextParamName)) {
134                                if (!paramList.isEmpty()) {
135                                        if (paramList.size() > 2) {
136                                                throw new InvalidRequestException(Msg.code(484) + "Failed to parse match URL[" + theMatchUrl
137                                                                + "] - Can not have more than 2 " + Constants.PARAM_LASTUPDATED
138                                                                + " parameter repetitions");
139                                        } else {
140                                                DateRangeParam p1 = new DateRangeParam();
141                                                p1.setValuesAsQueryTokens(myFhirContext, nextParamName, paramList);
142                                                paramMap.setLastUpdated(p1);
143                                        }
144                                }
145                        } else if (Constants.PARAM_HAS.equals(nextParamName)) {
146                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
147                                                myFhirContext, RestSearchParameterTypeEnum.HAS, nextParamName, paramList);
148                                paramMap.add(nextParamName, param);
149                        } else if (Constants.PARAM_COUNT.equals(nextParamName)) {
150                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
151                                        String intString = paramList.get(0).get(0);
152                                        try {
153                                                paramMap.setCount(Integer.parseInt(intString));
154                                        } catch (NumberFormatException e) {
155                                                throw new InvalidRequestException(
156                                                                Msg.code(485) + "Invalid " + Constants.PARAM_COUNT + " value: " + intString);
157                                        }
158                                }
159                        } else if (Constants.PARAM_SEARCH_TOTAL_MODE.equals(nextParamName)) {
160                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
161                                        String totalModeEnumStr = paramList.get(0).get(0);
162                                        SearchTotalModeEnum searchTotalMode = SearchTotalModeEnum.fromCode(totalModeEnumStr);
163                                        if (searchTotalMode == null) {
164                                                // We had an oops here supporting the UPPER CASE enum instead of the FHIR code for _total.
165                                                // Keep supporting it in case someone is using it.
166                                                try {
167                                                        searchTotalMode = SearchTotalModeEnum.valueOf(totalModeEnumStr);
168                                                } catch (IllegalArgumentException e) {
169                                                        throw new InvalidRequestException(Msg.code(2078) + "Invalid "
170                                                                        + Constants.PARAM_SEARCH_TOTAL_MODE + " value: " + totalModeEnumStr);
171                                                }
172                                        }
173                                        paramMap.setSearchTotalMode(searchTotalMode);
174                                }
175                        } else if (Constants.PARAM_OFFSET.equals(nextParamName)) {
176                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
177                                        String intString = paramList.get(0).get(0);
178                                        try {
179                                                paramMap.setOffset(Integer.parseInt(intString));
180                                        } catch (NumberFormatException e) {
181                                                throw new InvalidRequestException(
182                                                                Msg.code(486) + "Invalid " + Constants.PARAM_OFFSET + " value: " + intString);
183                                        }
184                                }
185                        } else if (ResourceMetaParams.RESOURCE_META_PARAMS.containsKey(nextParamName)) {
186                                if (isNotBlank(paramList.get(0).getQualifier())
187                                                && paramList.get(0).getQualifier().startsWith(".")) {
188                                        throw new InvalidRequestException(Msg.code(487) + "Invalid parameter chain: " + nextParamName
189                                                        + paramList.get(0).getQualifier());
190                                }
191                                IQueryParameterAnd<?> type = newInstanceAnd(nextParamName);
192                                type.setValuesAsQueryTokens(myFhirContext, nextParamName, (paramList));
193                                paramMap.add(nextParamName, type);
194                        } else if (Constants.PARAM_SOURCE.equals(nextParamName)) {
195                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
196                                                myFhirContext, RestSearchParameterTypeEnum.URI, nextParamName, paramList);
197                                paramMap.add(nextParamName, param);
198                        } else if (JpaConstants.PARAM_DELETE_EXPUNGE.equals(nextParamName)) {
199                                paramMap.setDeleteExpunge(true);
200                        } else if (Constants.PARAM_LIST.equals(nextParamName)) {
201                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
202                                                myFhirContext, RestSearchParameterTypeEnum.TOKEN, nextParamName, paramList);
203                                paramMap.add(nextParamName, param);
204                        } else if (nextParamName.startsWith("_") && !Constants.PARAM_LANGUAGE.equals(nextParamName)) {
205                                // ignore these since they aren't search params (e.g. _sort)
206                        } else {
207                                if (hasNoResourceType) {
208                                        // It is a resource specific search parameter being done on the server
209                                        throw new InvalidRequestException(Msg.code(2743) + "Failed to parse match URL [" + theMatchUrl
210                                                        + "] - Unknown search parameter " + nextParamName + " for operation on server base.");
211                                }
212
213                                RuntimeSearchParam paramDef = mySearchParamRegistry.getActiveSearchParam(
214                                                theResourceDefinition.getName(),
215                                                nextParamName,
216                                                ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
217                                if (paramDef == null) {
218                                        throw throwUnrecognizedParamException(theMatchUrl, theResourceDefinition, nextParamName);
219                                }
220
221                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
222                                                mySearchParamRegistry, myFhirContext, paramDef, nextParamName, paramList);
223                                paramMap.add(nextParamName, param);
224                        }
225                }
226                return paramMap;
227        }
228
229        private static boolean isSupportedQueryForNoProvidedResourceType(Set<String> theParamNames) {
230                if (theParamNames == null || theParamNames.isEmpty()) {
231                        // Query with no resource type in URL (ie. `[server base]?`)
232                        return false;
233                }
234                Set<String> acceptableServerParams = new HashSet<>(STRICT_RESOURCE_META_PARAMS);
235                acceptableServerParams.add(Constants.PARAM_INCLUDE_DELETED);
236                return acceptableServerParams.containsAll(theParamNames);
237        }
238
239        private static boolean hasNoResourceTypeInUrl(String theMatchUrl, RuntimeResourceDefinition theResourceDefinition) {
240                return theResourceDefinition == null && theMatchUrl.indexOf('?') == 0;
241        }
242
243        /**
244         * The _includeDeleted parameter should only be supported with _lastUpdated, and _id iff resource type is given
245         * This is because these are the common search parameter values that are still stored on the deleted resource version in DB
246         * However, since resources are unique by type and id, only _lastUpdated is supported if no resource type is given
247         * @param theParamsToCheck the list of parameters found in the URL
248         * @param theHasNoResourceType whether the request is on the base URL (ie `?_param` - without resource type)
249         */
250        private static void validateParamsAreCompatibleForDeleteOrThrow(
251                        Set<String> theParamsToCheck, boolean theHasNoResourceType) {
252                Set<String> compatibleParams =
253                                theHasNoResourceType ? COMPATIBLE_PARAMS_NO_RES_TYPE : COMPATIBLE_PARAMS_GIVEN_RES_TYPE;
254
255                if (!compatibleParams.containsAll(theParamsToCheck)) {
256                        throw new IllegalArgumentException(Msg.code(2744) + "The " + Constants.PARAM_INCLUDE_DELETED
257                                        + " parameter is only compatible with the following parameters: " + compatibleParams);
258                }
259        }
260
261        public static class UnrecognizedSearchParameterException extends InvalidRequestException {
262
263                private final String myResourceName;
264                private final String myParamName;
265
266                UnrecognizedSearchParameterException(String theMessage, String theResourceName, String theParamName) {
267                        super(theMessage);
268                        myResourceName = theResourceName;
269                        myParamName = theParamName;
270                }
271
272                public String getResourceName() {
273                        return myResourceName;
274                }
275
276                public String getParamName() {
277                        return myParamName;
278                }
279        }
280
281        private InvalidRequestException throwUnrecognizedParamException(
282                        String theMatchUrl, RuntimeResourceDefinition theResourceDefinition, String nextParamName) {
283                return new UnrecognizedSearchParameterException(
284                                Msg.code(488) + "Failed to parse match URL[" + theMatchUrl + "] - Resource type "
285                                                + theResourceDefinition.getName() + " does not have a parameter with name: " + nextParamName,
286                                theResourceDefinition.getName(),
287                                nextParamName);
288        }
289
290        private IQueryParameterAnd<?> newInstanceAnd(String theParamType) {
291                Class<? extends IQueryParameterAnd<?>> clazz = ResourceMetaParams.RESOURCE_META_AND_PARAMS.get(theParamType);
292                return ReflectionUtil.newInstance(clazz);
293        }
294
295        public IQueryParameterType newInstanceType(String theParamType) {
296                Class<? extends IQueryParameterType> clazz = ResourceMetaParams.RESOURCE_META_PARAMS.get(theParamType);
297                return ReflectionUtil.newInstance(clazz);
298        }
299
300        public ResourceSearch getResourceSearch(String theUrl, RequestPartitionId theRequestPartitionId, Flag... theFlags) {
301                RuntimeResourceDefinition resourceDefinition;
302                resourceDefinition = UrlUtil.parseUrlResourceType(myFhirContext, theUrl);
303                SearchParameterMap searchParameterMap = translateMatchUrl(theUrl, resourceDefinition, theFlags);
304                return new ResourceSearch(resourceDefinition, searchParameterMap, theRequestPartitionId);
305        }
306
307        public ResourceSearch getResourceSearch(String theUrl) {
308                return getResourceSearch(theUrl, null);
309        }
310
311        /**
312         * Parse a URL that contains _include or _revinclude parameters and return a {@link ResourceSearch} object
313         * @param theUrl
314         * @return the ResourceSearch object that can be used to create a SearchParameterMap
315         */
316        public ResourceSearch getResourceSearchWithIncludesAndRevIncludes(String theUrl) {
317                return getResourceSearch(theUrl, null, MatchUrlService.processIncludes());
318        }
319
320        public interface Flag {
321                void process(String theParamName, List<QualifiedParamList> theValues, SearchParameterMap theMapToPopulate);
322        }
323
324        /**
325         * Indicates that the parser should process _include and _revinclude (by default these are not handled)
326         */
327        public static Flag processIncludes() {
328                return (theParamName, theValues, theMapToPopulate) -> {
329                        if (Constants.PARAM_INCLUDE.equals(theParamName)) {
330                                for (QualifiedParamList nextQualifiedList : theValues) {
331                                        for (String nextValue : nextQualifiedList) {
332                                                theMapToPopulate.addInclude(new Include(
333                                                                nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
334                                        }
335                                }
336                        } else if (Constants.PARAM_REVINCLUDE.equals(theParamName)) {
337                                for (QualifiedParamList nextQualifiedList : theValues) {
338                                        for (String nextValue : nextQualifiedList) {
339                                                theMapToPopulate.addRevInclude(new Include(
340                                                                nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
341                                        }
342                                }
343                        }
344                };
345        }
346}