001package ca.uhn.fhir.rest.param;
002
003import ca.uhn.fhir.context.ConfigurationException;
004import ca.uhn.fhir.context.FhirContext;
005import ca.uhn.fhir.context.RuntimeSearchParam;
006import ca.uhn.fhir.model.api.IQueryParameterAnd;
007import ca.uhn.fhir.model.api.IQueryParameterOr;
008import ca.uhn.fhir.model.api.IQueryParameterType;
009import ca.uhn.fhir.model.primitive.IdDt;
010import ca.uhn.fhir.model.primitive.IntegerDt;
011import ca.uhn.fhir.rest.annotation.IdParam;
012import ca.uhn.fhir.rest.api.Constants;
013import ca.uhn.fhir.rest.api.QualifiedParamList;
014import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum;
015import ca.uhn.fhir.rest.param.binder.QueryParameterAndBinder;
016import ca.uhn.fhir.util.ReflectionUtil;
017import ca.uhn.fhir.util.UrlUtil;
018import org.hl7.fhir.instance.model.api.IIdType;
019import org.hl7.fhir.instance.model.api.IPrimitiveType;
020
021import java.lang.annotation.Annotation;
022import java.lang.reflect.Method;
023import java.util.ArrayList;
024import java.util.Collection;
025import java.util.Collections;
026import java.util.List;
027import java.util.stream.Collectors;
028
029/*
030 * #%L
031 * HAPI FHIR - Core Library
032 * %%
033 * Copyright (C) 2014 - 2020 University Health Network
034 * %%
035 * Licensed under the Apache License, Version 2.0 (the "License");
036 * you may not use this file except in compliance with the License.
037 * You may obtain a copy of the License at
038 *
039 * http://www.apache.org/licenses/LICENSE-2.0
040 *
041 * Unless required by applicable law or agreed to in writing, software
042 * distributed under the License is distributed on an "AS IS" BASIS,
043 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
044 * See the License for the specific language governing permissions and
045 * limitations under the License.
046 * #L%
047 */
048
049public class ParameterUtil {
050
051        @SuppressWarnings("unchecked")
052        public static <T extends IIdType> T convertIdToType(IIdType value, Class<T> theIdParamType) {
053                if (value != null && !theIdParamType.isAssignableFrom(value.getClass())) {
054                        IIdType newValue = ReflectionUtil.newInstance(theIdParamType);
055                        newValue.setValue(value.getValue());
056                        value = newValue;
057                }
058                return (T) value;
059        }
060
061        /**
062         * This is a utility method intended provided to help the JPA module.
063         */
064        public static IQueryParameterAnd<?> parseQueryParams(FhirContext theContext, RestSearchParameterTypeEnum paramType,
065                                                                                                                                                  String theUnqualifiedParamName, List<QualifiedParamList> theParameters) {
066                QueryParameterAndBinder binder;
067                switch (paramType) {
068                        case COMPOSITE:
069                                throw new UnsupportedOperationException();
070                        case DATE:
071                                binder = new QueryParameterAndBinder(DateAndListParam.class,
072                                        Collections.emptyList());
073                                break;
074                        case NUMBER:
075                                binder = new QueryParameterAndBinder(NumberAndListParam.class,
076                                        Collections.emptyList());
077                                break;
078                        case QUANTITY:
079                                binder = new QueryParameterAndBinder(QuantityAndListParam.class,
080                                        Collections.emptyList());
081                                break;
082                        case REFERENCE:
083                                binder = new QueryParameterAndBinder(ReferenceAndListParam.class,
084                                        Collections.emptyList());
085                                break;
086                        case STRING:
087                                binder = new QueryParameterAndBinder(StringAndListParam.class,
088                                        Collections.emptyList());
089                                break;
090                        case TOKEN:
091                                binder = new QueryParameterAndBinder(TokenAndListParam.class,
092                                        Collections.emptyList());
093                                break;
094                        case URI:
095                                binder = new QueryParameterAndBinder(UriAndListParam.class,
096                                        Collections.emptyList());
097                                break;
098                        case HAS:
099                                binder = new QueryParameterAndBinder(HasAndListParam.class,
100                                        Collections.emptyList());
101                                break;
102                        case SPECIAL:
103                                binder = new QueryParameterAndBinder(SpecialAndListParam.class,
104                                        Collections.emptyList());
105                                break;
106                        default:
107                                throw new IllegalArgumentException("Parameter '" + theUnqualifiedParamName + "' has type " + paramType + " which is currently not supported.");
108                }
109
110                return binder.parse(theContext, theUnqualifiedParamName, theParameters);
111        }
112
113        /**
114         * This is a utility method intended provided to help the JPA module.
115         */
116        public static IQueryParameterAnd<?> parseQueryParams(FhirContext theContext, RuntimeSearchParam theParamDef,
117                                                                                                                                                  String theUnqualifiedParamName, List<QualifiedParamList> theParameters) {
118                RestSearchParameterTypeEnum paramType = theParamDef.getParamType();
119                return parseQueryParams(theContext, paramType, theUnqualifiedParamName, theParameters);
120        }
121
122        /**
123         * Removes :modifiers and .chains from URL parameter names
124         */
125        public static String stripModifierPart(String theParam) {
126                for (int i = 0; i < theParam.length(); i++) {
127                        char nextChar = theParam.charAt(i);
128                        if (nextChar == ':' || nextChar == '.') {
129                                return theParam.substring(0, i);
130                        }
131                }
132                return theParam;
133        }
134
135        /**
136         * Escapes a string according to the rules for parameter escaping specified in the <a href="http://www.hl7.org/implement/standards/fhir/search.html#escaping">FHIR Specification Escaping
137         * Section</a>
138         */
139        public static String escape(String theValue) {
140                if (theValue == null) {
141                        return null;
142                }
143                StringBuilder b = new StringBuilder();
144
145                for (int i = 0; i < theValue.length(); i++) {
146                        char next = theValue.charAt(i);
147                        switch (next) {
148                                case '$':
149                                case ',':
150                                case '|':
151                                case '\\':
152                                        b.append('\\');
153                                        break;
154                                default:
155                                        break;
156                        }
157                        b.append(next);
158                }
159
160                return b.toString();
161        }
162
163        /**
164         * Escapes a string according to the rules for parameter escaping specified in the <a href="http://www.hl7.org/implement/standards/fhir/search.html#escaping">FHIR Specification Escaping
165         * Section</a>
166         */
167        public static String escapeWithDefault(Object theValue) {
168                if (theValue == null) {
169                        return "";
170                }
171                return escape(theValue.toString());
172        }
173
174        /**
175         * Applies {@link #escapeWithDefault(Object)} followed by {@link UrlUtil#escapeUrlParam(String)}
176         */
177        public static String escapeAndUrlEncode(String theInput) {
178                return UrlUtil.escapeUrlParam(escapeWithDefault(theInput));
179        }
180
181        public static Integer findIdParameterIndex(Method theMethod, FhirContext theContext) {
182                Integer index = findParamAnnotationIndex(theMethod, IdParam.class);
183                if (index != null) {
184                        Class<?> paramType = theMethod.getParameterTypes()[index];
185                        if (IIdType.class.equals(paramType)) {
186                                return index;
187                        }
188                        boolean isRi = theContext.getVersion().getVersion().isRi();
189                        boolean usesHapiId = IdDt.class.equals(paramType);
190                        if (isRi == usesHapiId) {
191                                throw new ConfigurationException("Method uses the wrong Id datatype (IdDt / IdType) for the given context FHIR version: " + theMethod.toString());
192                        }
193                }
194                return index;
195        }
196
197        // public static Integer findSinceParameterIndex(Method theMethod) {
198        // return findParamIndex(theMethod, Since.class);
199        // }
200
201        public static Integer findParamAnnotationIndex(Method theMethod, Class<?> toFind) {
202                int paramIndex = 0;
203                for (Annotation[] annotations : theMethod.getParameterAnnotations()) {
204                        for (Annotation nextAnnotation : annotations) {
205                                Class<? extends Annotation> class1 = nextAnnotation.annotationType();
206                                if (toFind.isAssignableFrom(class1)) {
207                                        return paramIndex;
208                                }
209                        }
210                        paramIndex++;
211                }
212                return null;
213        }
214
215        public static Object fromInteger(Class<?> theType, IntegerDt theArgument) {
216                if (theArgument == null) {
217                        return null;
218                }
219                if (theType.equals(Integer.class)) {
220                        return theArgument.getValue();
221                }
222                IPrimitiveType<?> retVal = (IPrimitiveType<?>) ReflectionUtil.newInstance(theType);
223                retVal.setValueAsString(theArgument.getValueAsString());
224                return retVal;
225        }
226
227        public static boolean isBindableIntegerType(Class<?> theClass) {
228                return Integer.class.isAssignableFrom(theClass)
229                        || IPrimitiveType.class.isAssignableFrom(theClass);
230        }
231
232        public static String escapeAndJoinOrList(Collection<String> theValues) {
233                return theValues
234                        .stream()
235                        .map(ParameterUtil::escape)
236                        .collect(Collectors.joining(","));
237        }
238
239        public static int nonEscapedIndexOf(String theString, char theCharacter) {
240                for (int i = 0; i < theString.length(); i++) {
241                        if (theString.charAt(i) == theCharacter) {
242                                if (i == 0 || theString.charAt(i - 1) != '\\') {
243                                        return i;
244                                }
245                        }
246                }
247                return -1;
248        }
249
250        public static String parseETagValue(String value) {
251                String eTagVersion;
252                value = value.trim();
253                if (value.length() > 1) {
254                        if (value.charAt(value.length() - 1) == '"') {
255                                if (value.charAt(0) == '"') {
256                                        eTagVersion = value.substring(1, value.length() - 1);
257                                } else if (value.length() > 3 && value.charAt(0) == 'W' && value.charAt(1) == '/'
258                                        && value.charAt(2) == '"') {
259                                        eTagVersion = value.substring(3, value.length() - 1);
260                                } else {
261                                        eTagVersion = value;
262                                }
263                        } else {
264                                eTagVersion = value;
265                        }
266                } else {
267                        eTagVersion = value;
268                }
269                return eTagVersion;
270        }
271
272        public static IQueryParameterOr<?> singleton(final IQueryParameterType theParam, final String theParamName) {
273                return new IQueryParameterOr<IQueryParameterType>() {
274
275                        private static final long serialVersionUID = 1L;
276
277                        @Override
278                        public List<IQueryParameterType> getValuesAsQueryTokens() {
279                                return Collections.singletonList(theParam);
280                        }
281
282                        @Override
283                        public void setValuesAsQueryTokens(FhirContext theContext, String theParamName,
284                                                                                                                  QualifiedParamList theParameters) {
285                                if (theParameters.isEmpty()) {
286                                        return;
287                                }
288                                if (theParameters.size() > 1) {
289                                        throw new IllegalArgumentException(
290                                                "Type " + theParam.getClass().getCanonicalName() + " does not support multiple values");
291                                }
292                                theParam.setValueAsQueryToken(theContext, theParamName, theParameters.getQualifier(),
293                                        theParameters.get(0));
294                        }
295                };
296        }
297
298        static List<String> splitParameterString(String theInput, char theDelimiter, boolean theUnescapeComponents) {
299                ArrayList<String> retVal = new ArrayList<>();
300                if (theInput != null) {
301                        StringBuilder b = new StringBuilder();
302                        for (int i = 0; i < theInput.length(); i++) {
303                                char next = theInput.charAt(i);
304                                if (next == theDelimiter) {
305                                        if (i == 0) {
306                                                b.append(next);
307                                        } else {
308                                                char prevChar = theInput.charAt(i - 1);
309                                                if (prevChar == '\\') {
310                                                        b.append(next);
311                                                } else {
312                                                        if (b.length() > 0) {
313                                                                retVal.add(b.toString());
314                                                        } else {
315                                                                retVal.add(null);
316                                                        }
317                                                        b.setLength(0);
318                                                }
319                                        }
320                                } else {
321                                        b.append(next);
322                                }
323                        }
324                        if (b.length() > 0) {
325                                retVal.add(b.toString());
326                        }
327                }
328
329                if (theUnescapeComponents) {
330                        for (int i = 0; i < retVal.size(); i++) {
331                                retVal.set(i, unescape(retVal.get(i)));
332                        }
333                }
334
335                return retVal;
336        }
337
338        public static IntegerDt toInteger(Object theArgument) {
339                if (theArgument instanceof IntegerDt) {
340                        return (IntegerDt) theArgument;
341                }
342                if (theArgument instanceof Integer) {
343                        return new IntegerDt((Integer) theArgument);
344                }
345                if (theArgument instanceof IPrimitiveType) {
346                        IPrimitiveType<?> pt = (IPrimitiveType<?>) theArgument;
347                        return new IntegerDt(pt.getValueAsString());
348                }
349                return null;
350        }
351
352        /**
353         * Unescapes a string according to the rules for parameter escaping specified in the <a href="http://www.hl7.org/implement/standards/fhir/search.html#escaping">FHIR Specification Escaping
354         * Section</a>
355         */
356        public static String unescape(String theValue) {
357                if (theValue == null) {
358                        return null;
359                }
360                if (theValue.indexOf('\\') == -1) {
361                        return theValue;
362                }
363
364                StringBuilder b = new StringBuilder();
365
366                for (int i = 0; i < theValue.length(); i++) {
367                        char next = theValue.charAt(i);
368                        if (next == '\\') {
369                                if (i == theValue.length() - 1) {
370                                        b.append(next);
371                                } else {
372                                        switch (theValue.charAt(i + 1)) {
373                                                case '$':
374                                                case ',':
375                                                case '|':
376                                                case '\\':
377                                                        continue;
378                                                default:
379                                                        b.append(next);
380                                        }
381                                }
382                        } else {
383                                b.append(next);
384                        }
385                }
386
387                return b.toString();
388        }
389
390        /**
391         * Returns true if the value is :iterate or :recurse (the former name of :iterate) for an _include parameter
392         */
393        public static boolean isIncludeIterate(String theQualifier) {
394                return Constants.PARAM_INCLUDE_QUALIFIER_RECURSE.equals(theQualifier) || Constants.PARAM_INCLUDE_QUALIFIER_ITERATE.equals(theQualifier);
395        }
396}