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.SearchTotalModeEnum;
036import ca.uhn.fhir.rest.param.DateRangeParam;
037import ca.uhn.fhir.rest.param.ParameterUtil;
038import ca.uhn.fhir.rest.server.exceptions.InvalidRequestException;
039import ca.uhn.fhir.rest.server.util.ISearchParamRegistry;
040import ca.uhn.fhir.util.ReflectionUtil;
041import ca.uhn.fhir.util.UrlUtil;
042import com.google.common.collect.ArrayListMultimap;
043import org.apache.http.NameValuePair;
044import org.springframework.beans.factory.annotation.Autowired;
045
046import java.util.List;
047
048import static org.apache.commons.lang3.StringUtils.isBlank;
049import static org.apache.commons.lang3.StringUtils.isNotBlank;
050
051public class MatchUrlService {
052
053        @Autowired
054        private FhirContext myFhirContext;
055
056        @Autowired
057        private ISearchParamRegistry mySearchParamRegistry;
058
059        public SearchParameterMap translateMatchUrl(
060                        String theMatchUrl, RuntimeResourceDefinition theResourceDefinition, Flag... theFlags) {
061                SearchParameterMap paramMap = new SearchParameterMap();
062                List<NameValuePair> parameters = UrlUtil.translateMatchUrl(theMatchUrl);
063
064                ArrayListMultimap<String, QualifiedParamList> nameToParamLists = ArrayListMultimap.create();
065                for (NameValuePair next : parameters) {
066                        if (isBlank(next.getValue())) {
067                                continue;
068                        }
069
070                        String paramName = next.getName();
071                        String qualifier = null;
072                        for (int i = 0; i < paramName.length(); i++) {
073                                switch (paramName.charAt(i)) {
074                                        case '.':
075                                        case ':':
076                                                qualifier = paramName.substring(i);
077                                                paramName = paramName.substring(0, i);
078                                                i = Integer.MAX_VALUE - 1;
079                                                break;
080                                }
081                        }
082
083                        QualifiedParamList paramList =
084                                        QualifiedParamList.splitQueryStringByCommasIgnoreEscape(qualifier, next.getValue());
085                        nameToParamLists.put(paramName, paramList);
086                }
087
088                for (String nextParamName : nameToParamLists.keySet()) {
089                        List<QualifiedParamList> paramList = nameToParamLists.get(nextParamName);
090
091                        if (theFlags != null) {
092                                for (Flag next : theFlags) {
093                                        next.process(nextParamName, paramList, paramMap);
094                                }
095                        }
096
097                        if (Constants.PARAM_LASTUPDATED.equals(nextParamName)) {
098                                if (!paramList.isEmpty()) {
099                                        if (paramList.size() > 2) {
100                                                throw new InvalidRequestException(Msg.code(484) + "Failed to parse match URL[" + theMatchUrl
101                                                                + "] - Can not have more than 2 " + Constants.PARAM_LASTUPDATED
102                                                                + " parameter repetitions");
103                                        } else {
104                                                DateRangeParam p1 = new DateRangeParam();
105                                                p1.setValuesAsQueryTokens(myFhirContext, nextParamName, paramList);
106                                                paramMap.setLastUpdated(p1);
107                                        }
108                                }
109                        } else if (Constants.PARAM_HAS.equals(nextParamName)) {
110                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
111                                                myFhirContext, RestSearchParameterTypeEnum.HAS, nextParamName, paramList);
112                                paramMap.add(nextParamName, param);
113                        } else if (Constants.PARAM_COUNT.equals(nextParamName)) {
114                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
115                                        String intString = paramList.get(0).get(0);
116                                        try {
117                                                paramMap.setCount(Integer.parseInt(intString));
118                                        } catch (NumberFormatException e) {
119                                                throw new InvalidRequestException(
120                                                                Msg.code(485) + "Invalid " + Constants.PARAM_COUNT + " value: " + intString);
121                                        }
122                                }
123                        } else if (Constants.PARAM_SEARCH_TOTAL_MODE.equals(nextParamName)) {
124                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
125                                        String totalModeEnumStr = paramList.get(0).get(0);
126                                        SearchTotalModeEnum searchTotalMode = SearchTotalModeEnum.fromCode(totalModeEnumStr);
127                                        if (searchTotalMode == null) {
128                                                // We had an oops here supporting the UPPER CASE enum instead of the FHIR code for _total.
129                                                // Keep supporting it in case someone is using it.
130                                                try {
131                                                        searchTotalMode = SearchTotalModeEnum.valueOf(totalModeEnumStr);
132                                                } catch (IllegalArgumentException e) {
133                                                        throw new InvalidRequestException(Msg.code(2078) + "Invalid "
134                                                                        + Constants.PARAM_SEARCH_TOTAL_MODE + " value: " + totalModeEnumStr);
135                                                }
136                                        }
137                                        paramMap.setSearchTotalMode(searchTotalMode);
138                                }
139                        } else if (Constants.PARAM_OFFSET.equals(nextParamName)) {
140                                if (!paramList.isEmpty() && !paramList.get(0).isEmpty()) {
141                                        String intString = paramList.get(0).get(0);
142                                        try {
143                                                paramMap.setOffset(Integer.parseInt(intString));
144                                        } catch (NumberFormatException e) {
145                                                throw new InvalidRequestException(
146                                                                Msg.code(486) + "Invalid " + Constants.PARAM_OFFSET + " value: " + intString);
147                                        }
148                                }
149                        } else if (ResourceMetaParams.RESOURCE_META_PARAMS.containsKey(nextParamName)) {
150                                if (isNotBlank(paramList.get(0).getQualifier())
151                                                && paramList.get(0).getQualifier().startsWith(".")) {
152                                        throw new InvalidRequestException(Msg.code(487) + "Invalid parameter chain: " + nextParamName
153                                                        + paramList.get(0).getQualifier());
154                                }
155                                IQueryParameterAnd<?> type = newInstanceAnd(nextParamName);
156                                type.setValuesAsQueryTokens(myFhirContext, nextParamName, (paramList));
157                                paramMap.add(nextParamName, type);
158                        } else if (Constants.PARAM_SOURCE.equals(nextParamName)) {
159                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
160                                                myFhirContext, RestSearchParameterTypeEnum.URI, nextParamName, paramList);
161                                paramMap.add(nextParamName, param);
162                        } else if (JpaConstants.PARAM_DELETE_EXPUNGE.equals(nextParamName)) {
163                                paramMap.setDeleteExpunge(true);
164                        } else if (Constants.PARAM_LIST.equals(nextParamName)) {
165                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
166                                                myFhirContext, RestSearchParameterTypeEnum.TOKEN, nextParamName, paramList);
167                                paramMap.add(nextParamName, param);
168                        } else if (nextParamName.startsWith("_") && !Constants.PARAM_LANGUAGE.equals(nextParamName)) {
169                                // ignore these since they aren't search params (e.g. _sort)
170                        } else {
171                                RuntimeSearchParam paramDef = mySearchParamRegistry.getActiveSearchParam(
172                                                theResourceDefinition.getName(),
173                                                nextParamName,
174                                                ISearchParamRegistry.SearchParamLookupContextEnum.SEARCH);
175                                if (paramDef == null) {
176                                        throw throwUnrecognizedParamException(theMatchUrl, theResourceDefinition, nextParamName);
177                                }
178
179                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
180                                                mySearchParamRegistry, myFhirContext, paramDef, nextParamName, paramList);
181                                paramMap.add(nextParamName, param);
182                        }
183                }
184                return paramMap;
185        }
186
187        public static class UnrecognizedSearchParameterException extends InvalidRequestException {
188
189                private final String myResourceName;
190                private final String myParamName;
191
192                UnrecognizedSearchParameterException(String theMessage, String theResourceName, String theParamName) {
193                        super(theMessage);
194                        myResourceName = theResourceName;
195                        myParamName = theParamName;
196                }
197
198                public String getResourceName() {
199                        return myResourceName;
200                }
201
202                public String getParamName() {
203                        return myParamName;
204                }
205        }
206
207        private InvalidRequestException throwUnrecognizedParamException(
208                        String theMatchUrl, RuntimeResourceDefinition theResourceDefinition, String nextParamName) {
209                return new UnrecognizedSearchParameterException(
210                                Msg.code(488) + "Failed to parse match URL[" + theMatchUrl + "] - Resource type "
211                                                + theResourceDefinition.getName() + " does not have a parameter with name: " + nextParamName,
212                                theResourceDefinition.getName(),
213                                nextParamName);
214        }
215
216        private IQueryParameterAnd<?> newInstanceAnd(String theParamType) {
217                Class<? extends IQueryParameterAnd<?>> clazz = ResourceMetaParams.RESOURCE_META_AND_PARAMS.get(theParamType);
218                return ReflectionUtil.newInstance(clazz);
219        }
220
221        public IQueryParameterType newInstanceType(String theParamType) {
222                Class<? extends IQueryParameterType> clazz = ResourceMetaParams.RESOURCE_META_PARAMS.get(theParamType);
223                return ReflectionUtil.newInstance(clazz);
224        }
225
226        public ResourceSearch getResourceSearch(String theUrl, RequestPartitionId theRequestPartitionId) {
227                RuntimeResourceDefinition resourceDefinition;
228                resourceDefinition = UrlUtil.parseUrlResourceType(myFhirContext, theUrl);
229                SearchParameterMap searchParameterMap = translateMatchUrl(theUrl, resourceDefinition);
230                return new ResourceSearch(resourceDefinition, searchParameterMap, theRequestPartitionId);
231        }
232
233        public ResourceSearch getResourceSearch(String theUrl) {
234                return getResourceSearch(theUrl, null);
235        }
236
237        public interface Flag {
238                void process(String theParamName, List<QualifiedParamList> theValues, SearchParameterMap theMapToPopulate);
239        }
240
241        /**
242         * Indicates that the parser should process _include and _revinclude (by default these are not handled)
243         */
244        public static Flag processIncludes() {
245                return (theParamName, theValues, theMapToPopulate) -> {
246                        if (Constants.PARAM_INCLUDE.equals(theParamName)) {
247                                for (QualifiedParamList nextQualifiedList : theValues) {
248                                        for (String nextValue : nextQualifiedList) {
249                                                theMapToPopulate.addInclude(new Include(
250                                                                nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
251                                        }
252                                }
253                        } else if (Constants.PARAM_REVINCLUDE.equals(theParamName)) {
254                                for (QualifiedParamList nextQualifiedList : theValues) {
255                                        for (String nextValue : nextQualifiedList) {
256                                                theMapToPopulate.addRevInclude(new Include(
257                                                                nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
258                                        }
259                                }
260                        }
261                };
262        }
263}