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