001package ca.uhn.fhir.util;
002
003/*
004 * #%L
005 * HAPI FHIR - Core Library
006 * %%
007 * Copyright (C) 2014 - 2020 University Health Network
008 * %%
009 * Licensed under the Apache License, Version 2.0 (the "License");
010 * you may not use this file except in compliance with the License.
011 * You may obtain a copy of the License at
012 *
013 *      http://www.apache.org/licenses/LICENSE-2.0
014 *
015 * Unless required by applicable law or agreed to in writing, software
016 * distributed under the License is distributed on an "AS IS" BASIS,
017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
018 * See the License for the specific language governing permissions and
019 * limitations under the License.
020 * #L%
021 */
022
023import ca.uhn.fhir.context.BaseRuntimeChildDefinition;
024import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition;
025import ca.uhn.fhir.context.BaseRuntimeElementDefinition;
026import ca.uhn.fhir.context.FhirContext;
027import ca.uhn.fhir.context.RuntimeResourceDefinition;
028import ca.uhn.fhir.model.primitive.StringDt;
029import org.apache.commons.lang3.Validate;
030import org.hl7.fhir.instance.model.api.IBase;
031import org.hl7.fhir.instance.model.api.IBaseDatatype;
032import org.hl7.fhir.instance.model.api.IBaseParameters;
033import org.hl7.fhir.instance.model.api.IBaseReference;
034import org.hl7.fhir.instance.model.api.IBaseResource;
035import org.hl7.fhir.instance.model.api.IPrimitiveType;
036
037import java.math.BigDecimal;
038import java.util.ArrayList;
039import java.util.Collection;
040import java.util.List;
041import java.util.Optional;
042import java.util.function.Function;
043import java.util.stream.Collectors;
044
045import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
046
047/**
048 * Utilities for dealing with parameters resources in a version indepenedent way
049 */
050public class ParametersUtil {
051
052        public static List<String> getNamedParameterValuesAsString(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
053                Function<IPrimitiveType<?>, String> mapper = t -> defaultIfBlank(t.getValueAsString(), null);
054                return extractNamedParameters(theCtx, theParameters, theParameterName, mapper);
055        }
056
057        public static List<Integer> getNamedParameterValuesAsInteger(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
058                Function<IPrimitiveType<?>, Integer> mapper = t -> (Integer) t.getValue();
059                return extractNamedParameters(theCtx, theParameters, theParameterName, mapper);
060        }
061
062        public static Optional<Integer> getNamedParameterValueAsInteger(FhirContext theCtx, IBaseParameters theParameters, String theParameterName) {
063                return getNamedParameterValuesAsInteger(theCtx, theParameters, theParameterName).stream().findFirst();
064        }
065
066        public static List<IBase> getNamedParameters(FhirContext theCtx, IBaseResource theParameters, String theParameterName) {
067                Validate.notNull(theParameters, "theParameters must not be null");
068                RuntimeResourceDefinition resDef = theCtx.getResourceDefinition(theParameters.getClass());
069                BaseRuntimeChildDefinition parameterChild = resDef.getChildByName("parameter");
070                List<IBase> parameterReps = parameterChild.getAccessor().getValues(theParameters);
071
072                return parameterReps
073                        .stream()
074                        .filter(param -> {
075                                BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(param.getClass());
076                                BaseRuntimeChildDefinition nameChild = nextParameterDef.getChildByName("name");
077                                List<IBase> nameValues = nameChild.getAccessor().getValues(param);
078                                Optional<? extends IPrimitiveType<?>> nameValue = nameValues
079                                        .stream()
080                                        .filter(t -> t instanceof IPrimitiveType<?>)
081                                        .map(t -> ((IPrimitiveType<?>) t))
082                                        .findFirst();
083                                if (!nameValue.isPresent() || !theParameterName.equals(nameValue.get().getValueAsString())) {
084                                        return false;
085                                }
086                                return true;
087                        })
088                        .collect(Collectors.toList());
089
090        }
091
092        public static Optional<IBase> getParameterPart(FhirContext theCtx, IBase theParameter, String theParameterName) {
093                BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(theParameter.getClass());
094                BaseRuntimeChildDefinition valueChild = nextParameterDef.getChildByName("part");
095                List<IBase> parts = valueChild.getAccessor().getValues(theParameter);
096
097                for (IBase nextPart : parts) {
098                        Optional<IPrimitiveType> name = theCtx.newTerser().getSingleValue(nextPart, "name", IPrimitiveType.class);
099                        if (name.isPresent() && theParameterName.equals(name.get().getValueAsString())) {
100                                return Optional.of(nextPart);
101                        }
102                }
103
104                return Optional.empty();
105        }
106
107        public static Optional<IBase> getParameterPartValue(FhirContext theCtx, IBase theParameter, String theParameterName) {
108                Optional<IBase> part = getParameterPart(theCtx, theParameter, theParameterName);
109                if (part.isPresent()) {
110                        return theCtx.newTerser().getSingleValue(part.get(), "value[x]", IBase.class);
111                } else {
112                        return Optional.empty();
113                }
114        }
115
116        public static String getParameterPartValueAsString(FhirContext theCtx, IBase theParameter, String theParameterName) {
117                return getParameterPartValue(theCtx, theParameter, theParameterName).map(t -> (IPrimitiveType<?>) t).map(t -> t.getValueAsString()).orElse(null);
118        }
119
120        private static <T> List<T> extractNamedParameters(FhirContext theCtx, IBaseParameters theParameters, String theParameterName, Function<IPrimitiveType<?>, T> theMapper) {
121                List<T> retVal = new ArrayList<>();
122
123                List<IBase> namedParameters = getNamedParameters(theCtx, theParameters, theParameterName);
124                for (IBase nextParameter : namedParameters) {
125                        BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(nextParameter.getClass());
126                        BaseRuntimeChildDefinition valueChild = nextParameterDef.getChildByName("value[x]");
127                        List<IBase> valueValues = valueChild.getAccessor().getValues(nextParameter);
128                        valueValues
129                                .stream()
130                                .filter(t -> t instanceof IPrimitiveType<?>)
131                                .map(t -> ((IPrimitiveType<?>) t))
132                                .map(theMapper)
133                                .filter(t -> t != null)
134                                .forEach(retVal::add);
135
136                }
137                return retVal;
138        }
139
140        private static void addClientParameter(FhirContext theContext, Object theValue, IBaseResource theTargetResource, BaseRuntimeChildDefinition paramChild, BaseRuntimeElementCompositeDefinition<?> paramChildElem, String theName) {
141                Validate.notNull(theValue, "theValue must not be null");
142
143                if (theValue instanceof IBaseResource) {
144                        IBase parameter = createParameterRepetition(theContext, theTargetResource, paramChild, paramChildElem, theName);
145                        paramChildElem.getChildByName("resource").getMutator().addValue(parameter, (IBaseResource) theValue);
146                } else if (theValue instanceof IBaseDatatype) {
147                        IBase parameter = createParameterRepetition(theContext, theTargetResource, paramChild, paramChildElem, theName);
148                        paramChildElem.getChildByName("value[x]").getMutator().addValue(parameter, (IBaseDatatype) theValue);
149                } else if (theValue instanceof Collection) {
150                        Collection<?> collection = (Collection<?>) theValue;
151                        for (Object next : collection) {
152                                addClientParameter(theContext, next, theTargetResource, paramChild, paramChildElem, theName);
153                        }
154                } else {
155                        throw new IllegalArgumentException("Don't know how to handle value of type " + theValue.getClass() + " for parameter " + theName);
156                }
157        }
158
159        /**
160         * Add a parameter value to a Parameters resource
161         *
162         * @param theContext    The FhirContext
163         * @param theParameters The Parameters resource
164         * @param theName       The parametr name
165         * @param theValue      The parameter value (can be a {@link IBaseResource resource} or a {@link IBaseDatatype datatype})
166         */
167        public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, Object theValue) {
168                RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
169                BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
170                BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
171
172                addClientParameter(theContext, theValue, theParameters, paramChild, paramChildElem, theName);
173        }
174
175        /**
176         * Add a parameter value to a Parameters resource
177         *
178         * @param theContext           The FhirContext
179         * @param theParameters        The Parameters resource
180         * @param theName              The parameter name
181         * @param thePrimitiveDatatype The datatype, e.g. "string", or "uri"
182         * @param theValue             The value
183         */
184        public static void addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName, String thePrimitiveDatatype, String theValue) {
185                Validate.notBlank(thePrimitiveDatatype, "thePrimitiveDatatype must not be null or empty");
186
187                BaseRuntimeElementDefinition<?> datatypeDef = theContext.getElementDefinition(thePrimitiveDatatype);
188                IPrimitiveType<?> value = (IPrimitiveType<?>) datatypeDef.newInstance();
189                value.setValueAsString(theValue);
190
191                addParameterToParameters(theContext, theParameters, theName, value);
192        }
193
194        private static IBase createParameterRepetition(FhirContext theContext, IBaseResource theTargetResource, BaseRuntimeChildDefinition paramChild, BaseRuntimeElementCompositeDefinition<?> paramChildElem, String theName) {
195                IBase parameter = paramChildElem.newInstance();
196                paramChild.getMutator().addValue(theTargetResource, parameter);
197                IPrimitiveType<?> value;
198                value = createString(theContext, theName);
199                paramChildElem.getChildByName("name").getMutator().addValue(parameter, value);
200                return parameter;
201        }
202
203        public static IPrimitiveType<?> createString(FhirContext theContext, String theValue) {
204                IPrimitiveType<?> value;
205                if (theContext.getVersion().getVersion().isRi()) {
206                        value = (IPrimitiveType<?>) theContext.getElementDefinition("string").newInstance(theValue);
207                } else {
208                        value = new StringDt(theValue);
209                }
210                return value;
211        }
212
213        public static IPrimitiveType<?> createUri(FhirContext theContext, String theValue) {
214                IPrimitiveType<?> value = (IPrimitiveType<?>) theContext.getElementDefinition("uri").newInstance(theValue);
215                return value;
216        }
217
218        public static IPrimitiveType<?> createCode(FhirContext theContext, String theValue) {
219                IPrimitiveType<?> value = (IPrimitiveType<?>) theContext.getElementDefinition("code").newInstance(theValue);
220                return value;
221        }
222
223        public static IBaseParameters newInstance(FhirContext theContext) {
224                Validate.notNull(theContext, "theContext must not be null");
225                return (IBaseParameters) theContext.getResourceDefinition("Parameters").newInstance();
226        }
227
228        @SuppressWarnings("unchecked")
229        public static void addParameterToParametersBoolean(FhirContext theCtx, IBaseParameters theParameters, String theName, boolean theValue) {
230                IPrimitiveType<Boolean> value = (IPrimitiveType<Boolean>) theCtx.getElementDefinition("boolean").newInstance();
231                value.setValue(theValue);
232                addParameterToParameters(theCtx, theParameters, theName, value);
233        }
234
235        @SuppressWarnings("unchecked")
236        public static void addParameterToParametersCode(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
237                IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("code").newInstance();
238                value.setValue(theValue);
239                addParameterToParameters(theCtx, theParameters, theName, value);
240        }
241
242        @SuppressWarnings("unchecked")
243        public static void addParameterToParametersInteger(FhirContext theCtx, IBaseParameters theParameters, String theName, int theValue) {
244                IPrimitiveType<Integer> count = (IPrimitiveType<Integer>) theCtx.getElementDefinition("integer").newInstance();
245                count.setValue(theValue);
246                addParameterToParameters(theCtx, theParameters, theName, count);
247
248        }
249
250        public static void addParameterToParametersReference(FhirContext theCtx, IBaseParameters theParameters, String theName, String theReference) {
251                IBaseReference target = (IBaseReference) theCtx.getElementDefinition("reference").newInstance();
252                target.setReference(theReference);
253                addParameterToParameters(theCtx, theParameters, theName, target);
254        }
255
256        @SuppressWarnings("unchecked")
257        public static void addParameterToParametersString(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
258                IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("string").newInstance();
259                value.setValue(theValue);
260                addParameterToParameters(theCtx, theParameters, theName, value);
261        }
262
263        @SuppressWarnings("unchecked")
264        public static void addParameterToParametersUri(FhirContext theCtx, IBaseParameters theParameters, String theName, String theValue) {
265                IPrimitiveType<String> value = (IPrimitiveType<String>) theCtx.getElementDefinition("uri").newInstance();
266                value.setValue(theValue);
267                addParameterToParameters(theCtx, theParameters, theName, value);
268
269        }
270
271        /**
272         * Add a parameter with no value (typically because we'll be adding sub-parameters)
273         */
274        public static IBase addParameterToParameters(FhirContext theContext, IBaseParameters theParameters, String theName) {
275                RuntimeResourceDefinition def = theContext.getResourceDefinition(theParameters);
276                BaseRuntimeChildDefinition paramChild = def.getChildByName("parameter");
277                BaseRuntimeElementCompositeDefinition<?> paramChildElem = (BaseRuntimeElementCompositeDefinition<?>) paramChild.getChildByName("parameter");
278
279                return createParameterRepetition(theContext, theParameters, paramChild, paramChildElem, theName);
280        }
281
282        public static void addPartCode(FhirContext theContext, IBase theParameter, String theName, String theCode) {
283                IPrimitiveType<String> value = (IPrimitiveType<String>) theContext.getElementDefinition("code").newInstance();
284                value.setValue(theCode);
285
286                addPart(theContext, theParameter, theName, value);
287        }
288
289        public static void addPartInteger(FhirContext theContext, IBase theParameter, String theName, Integer theInteger) {
290                IPrimitiveType<Integer> value = (IPrimitiveType<Integer>) theContext.getElementDefinition("integer").newInstance();
291                value.setValue(theInteger);
292
293                addPart(theContext, theParameter, theName, value);
294        }
295
296        public static void addPartString(FhirContext theContext, IBase theParameter, String theName, String theValue) {
297                IPrimitiveType<String> value = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
298                value.setValue(theValue);
299
300                addPart(theContext, theParameter, theName, value);
301        }
302
303        public static void addPartBoolean(FhirContext theContext, IBase theParameter, String theName, Boolean theValue) {
304                IPrimitiveType<Boolean> value = (IPrimitiveType<Boolean>) theContext.getElementDefinition("boolean").newInstance();
305                value.setValue(theValue);
306
307                addPart(theContext, theParameter, theName, value);
308        }
309
310        public static void addPartDecimal(FhirContext theContext, IBase theParameter, String theName, Double theValue) {
311                IPrimitiveType<BigDecimal> value = (IPrimitiveType<BigDecimal>) theContext.getElementDefinition("decimal").newInstance();
312                value.setValue(theValue == null ? null : new BigDecimal(theValue));
313
314                addPart(theContext, theParameter, theName, value);
315        }
316
317        public static void addPartCoding(FhirContext theContext, IBase theParameter, String theName, String theSystem, String theCode, String theDisplay) {
318                IBase coding = theContext.getElementDefinition("coding").newInstance();
319
320                BaseRuntimeElementCompositeDefinition<?> codingDef = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(coding.getClass());
321                codingDef.getChildByName("system").getMutator().addValue(coding, createUri(theContext, theSystem));
322                codingDef.getChildByName("code").getMutator().addValue(coding, createCode(theContext, theCode));
323                codingDef.getChildByName("display").getMutator().addValue(coding, createString(theContext, theDisplay));
324
325                addPart(theContext, theParameter, theName, coding);
326        }
327
328        public static void addPart(FhirContext theContext, IBase theParameter, String theName, IBase theValue) {
329                BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(theParameter.getClass());
330                BaseRuntimeChildDefinition partChild = def.getChildByName("part");
331
332                BaseRuntimeElementCompositeDefinition<?> partChildElem = (BaseRuntimeElementCompositeDefinition<?>) partChild.getChildByName("part");
333                IBase part = partChildElem.newInstance();
334                partChild.getMutator().addValue(theParameter, part);
335
336                IPrimitiveType<String> name = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
337                name.setValue(theName);
338                partChildElem.getChildByName("name").getMutator().addValue(part, name);
339
340                if (theValue instanceof IBaseResource) {
341                        partChildElem.getChildByName("resource").getMutator().addValue(part, theValue);
342                } else {
343                        partChildElem.getChildByName("value[x]").getMutator().addValue(part, theValue);
344                }
345
346        }
347
348        public static void addPartResource(FhirContext theContext, IBase theParameter, String theName, IBaseResource theValue) {
349                BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) theContext.getElementDefinition(theParameter.getClass());
350                BaseRuntimeChildDefinition partChild = def.getChildByName("part");
351
352                BaseRuntimeElementCompositeDefinition<?> partChildElem = (BaseRuntimeElementCompositeDefinition<?>) partChild.getChildByName("part");
353                IBase part = partChildElem.newInstance();
354                partChild.getMutator().addValue(theParameter, part);
355
356                IPrimitiveType<String> name = (IPrimitiveType<String>) theContext.getElementDefinition("string").newInstance();
357                name.setValue(theName);
358                partChildElem.getChildByName("name").getMutator().addValue(part, name);
359
360                partChildElem.getChildByName("resource").getMutator().addValue(part, theValue);
361        }
362
363        public static List<String> getNamedParameterPartAsString(FhirContext theCtx, IBaseParameters theParameters, String thePartName, String theParameterName) {
364                return extractNamedParameterPartsAsString(theCtx, theParameters, thePartName, theParameterName);
365        }
366
367        // TODO KHS need to consolidate duplicated functionality that came in from different branches
368        private static List<String> extractNamedParameterPartsAsString(FhirContext theCtx, IBaseParameters theParameters, String thePartName, String theParameterName) {
369                List<IBase> parameterReps = getParameterReps(theCtx, theParameters);
370
371                List<String> retVal = new ArrayList<>();
372
373                for (IBase nextParameter : parameterReps) {
374                        BaseRuntimeElementCompositeDefinition<?> nextParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(nextParameter.getClass());
375                        Optional<? extends IPrimitiveType<?>> nameValue = getNameValue(nextParameter, nextParameterDef);
376                        if (!nameValue.isPresent() || !thePartName.equals(nameValue.get().getValueAsString())) {
377                                continue;
378                        }
379
380                        BaseRuntimeChildDefinition partChild = nextParameterDef.getChildByName("part");
381                        List<IBase> partValues = partChild.getAccessor().getValues(nextParameter);
382                        for (IBase partValue : partValues) {
383                                BaseRuntimeElementCompositeDefinition<?> partParameterDef = (BaseRuntimeElementCompositeDefinition<?>) theCtx.getElementDefinition(partValue.getClass());
384                                Optional<? extends IPrimitiveType<?>> partNameValue = getNameValue(partValue, partParameterDef);
385                                if (!partNameValue.isPresent() || !theParameterName.equals(partNameValue.get().getValueAsString())) {
386                                        continue;
387                                }
388                                BaseRuntimeChildDefinition valueChild = partParameterDef.getChildByName("value[x]");
389                                List<IBase> valueValues = valueChild.getAccessor().getValues(partValue);
390                                valueValues
391                                        .stream()
392                                        .filter(t -> t instanceof IPrimitiveType<?>)
393                                        .map(t -> ((IPrimitiveType<String>) t))
394                                        .map(t -> defaultIfBlank(t.getValueAsString(), null))
395                                        .filter(t -> t != null)
396                                        .forEach(retVal::add);
397
398                        }
399                }
400                return retVal;
401        }
402
403        private static List<IBase> getParameterReps(FhirContext theCtx, IBaseParameters theParameters) {
404                Validate.notNull(theParameters, "theParameters must not be null");
405                RuntimeResourceDefinition resDef = theCtx.getResourceDefinition(theParameters.getClass());
406                BaseRuntimeChildDefinition parameterChild = resDef.getChildByName("parameter");
407                return parameterChild.getAccessor().getValues(theParameters);
408        }
409
410        private static Optional<? extends IPrimitiveType<?>> getNameValue(IBase nextParameter, BaseRuntimeElementCompositeDefinition<?> theNextParameterDef) {
411                BaseRuntimeChildDefinition nameChild = theNextParameterDef.getChildByName("name");
412                List<IBase> nameValues = nameChild.getAccessor().getValues(nextParameter);
413                return nameValues
414                        .stream()
415                        .filter(t -> t instanceof IPrimitiveType<?>)
416                        .map(t -> ((IPrimitiveType<?>) t))
417                        .findFirst();
418        }
419
420}