001/*-
002 * #%L
003 * HAPI FHIR JPA - Search Parameters
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.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 != null && paramList.size() > 0) {
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 != null
115                                                && paramList.size() > 0
116                                                && paramList.get(0).size() > 0) {
117                                        String intString = paramList.get(0).get(0);
118                                        try {
119                                                paramMap.setCount(Integer.parseInt(intString));
120                                        } catch (NumberFormatException e) {
121                                                throw new InvalidRequestException(
122                                                                Msg.code(485) + "Invalid " + Constants.PARAM_COUNT + " value: " + intString);
123                                        }
124                                }
125                        } else if (Constants.PARAM_SEARCH_TOTAL_MODE.equals(nextParamName)) {
126                                if (paramList != null
127                                                && !paramList.isEmpty()
128                                                && !paramList.get(0).isEmpty()) {
129                                        String totalModeEnumStr = paramList.get(0).get(0);
130                                        try {
131                                                paramMap.setSearchTotalMode(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                        } else if (Constants.PARAM_OFFSET.equals(nextParamName)) {
138                                if (paramList != null
139                                                && paramList.size() > 0
140                                                && paramList.get(0).size() > 0) {
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 =
172                                                mySearchParamRegistry.getActiveSearchParam(theResourceDefinition.getName(), nextParamName);
173                                if (paramDef == null) {
174                                        throw throwUnrecognizedParamException(theMatchUrl, theResourceDefinition, nextParamName);
175                                }
176
177                                IQueryParameterAnd<?> param = JpaParamUtil.parseQueryParams(
178                                                mySearchParamRegistry, myFhirContext, paramDef, nextParamName, paramList);
179                                paramMap.add(nextParamName, param);
180                        }
181                }
182                return paramMap;
183        }
184
185        public static class UnrecognizedSearchParameterException extends InvalidRequestException {
186
187                private final String myResourceName;
188                private final String myParamName;
189
190                UnrecognizedSearchParameterException(String theMessage, String theResourceName, String theParamName) {
191                        super(theMessage);
192                        myResourceName = theResourceName;
193                        myParamName = theParamName;
194                }
195
196                public String getResourceName() {
197                        return myResourceName;
198                }
199
200                public String getParamName() {
201                        return myParamName;
202                }
203        }
204
205        private InvalidRequestException throwUnrecognizedParamException(
206                        String theMatchUrl, RuntimeResourceDefinition theResourceDefinition, String nextParamName) {
207                return new UnrecognizedSearchParameterException(
208                                Msg.code(488) + "Failed to parse match URL[" + theMatchUrl + "] - Resource type "
209                                                + theResourceDefinition.getName() + " does not have a parameter with name: " + nextParamName,
210                                theResourceDefinition.getName(),
211                                nextParamName);
212        }
213
214        private IQueryParameterAnd<?> newInstanceAnd(String theParamType) {
215                Class<? extends IQueryParameterAnd<?>> clazz = ResourceMetaParams.RESOURCE_META_AND_PARAMS.get(theParamType);
216                return ReflectionUtil.newInstance(clazz);
217        }
218
219        public IQueryParameterType newInstanceType(String theParamType) {
220                Class<? extends IQueryParameterType> clazz = ResourceMetaParams.RESOURCE_META_PARAMS.get(theParamType);
221                return ReflectionUtil.newInstance(clazz);
222        }
223
224        public ResourceSearch getResourceSearch(String theUrl, RequestPartitionId theRequestPartitionId) {
225                RuntimeResourceDefinition resourceDefinition;
226                resourceDefinition = UrlUtil.parseUrlResourceType(myFhirContext, theUrl);
227                SearchParameterMap searchParameterMap = translateMatchUrl(theUrl, resourceDefinition);
228                return new ResourceSearch(resourceDefinition, searchParameterMap, theRequestPartitionId);
229        }
230
231        public ResourceSearch getResourceSearch(String theUrl) {
232                return getResourceSearch(theUrl, null);
233        }
234
235        public abstract static class Flag {
236
237                /**
238                 * Constructor
239                 */
240                Flag() {
241                        // nothing
242                }
243
244                abstract void process(
245                                String theParamName, List<QualifiedParamList> theValues, SearchParameterMap theMapToPopulate);
246        }
247
248        /**
249         * Indicates that the parser should process _include and _revinclude (by default these are not handled)
250         */
251        public static Flag processIncludes() {
252                return new Flag() {
253
254                        @Override
255                        void process(String theParamName, List<QualifiedParamList> theValues, SearchParameterMap theMapToPopulate) {
256                                if (Constants.PARAM_INCLUDE.equals(theParamName)) {
257                                        for (QualifiedParamList nextQualifiedList : theValues) {
258                                                for (String nextValue : nextQualifiedList) {
259                                                        theMapToPopulate.addInclude(new Include(
260                                                                        nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
261                                                }
262                                        }
263                                } else if (Constants.PARAM_REVINCLUDE.equals(theParamName)) {
264                                        for (QualifiedParamList nextQualifiedList : theValues) {
265                                                for (String nextValue : nextQualifiedList) {
266                                                        theMapToPopulate.addRevInclude(new Include(
267                                                                        nextValue, ParameterUtil.isIncludeIterate(nextQualifiedList.getQualifier())));
268                                                }
269                                        }
270                                }
271                        }
272                };
273        }
274}