001package ca.uhn.fhir.context.support;
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.FhirContext;
024import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException;
025import ca.uhn.fhir.util.ParametersUtil;
026import org.apache.commons.lang3.Validate;
027import org.hl7.fhir.instance.model.api.IBase;
028import org.hl7.fhir.instance.model.api.IBaseParameters;
029import org.hl7.fhir.instance.model.api.IBaseResource;
030import org.hl7.fhir.instance.model.api.IPrimitiveType;
031
032import javax.annotation.Nonnull;
033import javax.annotation.Nullable;
034import java.util.ArrayList;
035import java.util.Collections;
036import java.util.List;
037import java.util.Set;
038import java.util.stream.Collectors;
039
040import static org.apache.commons.lang3.StringUtils.isNotBlank;
041
042/**
043 * This interface is a version-independent representation of the
044 * various functions that can be provided by validation and terminology
045 * services.
046 * <p>
047 * This interface is invoked directly by internal parts of the HAPI FHIR API, including the
048 * Validator and the FHIRPath evaluator. It is used to supply artifacts required for validation
049 * (e.g. StructureDefinition resources, ValueSet resources, etc.) and also to provide
050 * terminology functions such as code validation, ValueSet expansion, etc.
051 * </p>
052 * <p>
053 * Implementations are not required to implement all of the functions
054 * in this interface; in fact it is expected that most won't. Any
055 * methods which are not implemented may simply return <code>null</code>
056 * and calling code is expected to be able to handle this. Generally, a
057 * series of implementations of this interface will be joined together using
058 * the
059 * <a href="https://hapifhir.io/hapi-fhir/apidocs/hapi-fhir-validation/org/hl7/fhir/common/hapi/validation/ValidationSupportChain2.html">ValidationSupportChain</a>
060 * class.
061 * </p>
062 * <p>
063 * See <a href="https://hapifhir.io/hapi-fhir/docs/validation/validation_support_modules.html">Validation Support Modules</a>
064 * for information on how to assemble and configure implementations of this interface. See also
065 * the <code>org.hl7.fhir.common.hapi.validation.support</code>
066 * <a href="https://hapifhir.io/hapi-fhir/apidocs/hapi-fhir-validation/org/hl7/fhir/common/hapi/validation/package-summary.html">package summary</a>
067 * in the <code>hapi-fhir-validation</code> module for many implementations of this interface.
068 * </p>
069 *
070 * @since 5.0.0
071 */
072public interface IValidationSupport {
073        String URL_PREFIX_VALUE_SET = "http://hl7.org/fhir/ValueSet/";
074
075
076        /**
077         * Expands the given portion of a ValueSet
078         *
079         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
080         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
081         * @param theExpansionOptions      If provided (may be <code>null</code>), contains options controlling the expansion
082         * @param theValueSetToExpand      The valueset that should be expanded
083         * @return The expansion, or null
084         */
085        default ValueSetExpansionOutcome expandValueSet(ValidationSupportContext theValidationSupportContext, @Nullable ValueSetExpansionOptions theExpansionOptions, @Nonnull IBaseResource theValueSetToExpand) {
086                return null;
087        }
088
089        /**
090         * Load and return all conformance resources associated with this
091         * validation support module. This method may return null if it doesn't
092         * make sense for a given module.
093         */
094        default List<IBaseResource> fetchAllConformanceResources() {
095                return null;
096        }
097
098        /**
099         * Load and return all possible structure definitions
100         */
101        default <T extends IBaseResource> List<T> fetchAllStructureDefinitions() {
102                return null;
103        }
104
105        /**
106         * Fetch a code system by ID
107         *
108         * @param theSystem The code system
109         * @return The valueset (must not be null, but can be an empty ValueSet)
110         */
111        default IBaseResource fetchCodeSystem(String theSystem) {
112                return null;
113        }
114
115        /**
116         * Loads a resource needed by the validation (a StructureDefinition, or a
117         * ValueSet)
118         *
119         * @param theClass The type of the resource to load
120         * @param theUri   The resource URI
121         * @return Returns the resource, or <code>null</code> if no resource with the
122         * given URI can be found
123         */
124        default <T extends IBaseResource> T fetchResource(Class<T> theClass, String theUri) {
125                Validate.notNull(theClass, "theClass must not be null or blank");
126                Validate.notBlank(theUri, "theUri must not be null or blank");
127
128                switch (getFhirContext().getResourceType(theClass)) {
129                        case "StructureDefinition":
130                                return theClass.cast(fetchStructureDefinition(theUri));
131                        case "ValueSet":
132                                return theClass.cast(fetchValueSet(theUri));
133                        case "CodeSystem":
134                                return theClass.cast(fetchCodeSystem(theUri));
135                }
136
137                if (theUri.startsWith(URL_PREFIX_VALUE_SET)) {
138                        return theClass.cast(fetchValueSet(theUri));
139                }
140
141                return null;
142        }
143
144        default IBaseResource fetchStructureDefinition(String theUrl) {
145                return null;
146        }
147
148        /**
149         * Returns <code>true</code> if codes in the given code system can be expanded
150         * or validated
151         *
152         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
153         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
154         * @param theSystem                The URI for the code system, e.g. <code>"http://loinc.org"</code>
155         * @return Returns <code>true</code> if codes in the given code system can be
156         * validated
157         */
158        default boolean isCodeSystemSupported(ValidationSupportContext theValidationSupportContext, String theSystem) {
159                return false;
160        }
161
162        /**
163         * Fetch the given ValueSet by URL
164         */
165        default IBaseResource fetchValueSet(String theValueSetUrl) {
166                return null;
167        }
168
169        /**
170         * Validates that the given code exists and if possible returns a display
171         * name. This method is called to check codes which are found in "example"
172         * binding fields (e.g. <code>Observation.code</code> in the default profile.
173         *
174         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
175         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
176         * @param theOptions               Provides options controlling the validation
177         * @param theCodeSystem            The code system, e.g. "<code>http://loinc.org</code>"
178         * @param theCode                  The code, e.g. "<code>1234-5</code>"
179         * @param theDisplay               The display name, if it should also be validated
180         * @return Returns a validation result object
181         */
182        default CodeValidationResult validateCode(ValidationSupportContext theValidationSupportContext, ConceptValidationOptions theOptions, String theCodeSystem, String theCode, String theDisplay, String theValueSetUrl) {
183                return null;
184        }
185
186        /**
187         * Validates that the given code exists and if possible returns a display
188         * name. This method is called to check codes which are found in "example"
189         * binding fields (e.g. <code>Observation.code</code> in the default profile.
190         *
191         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
192         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
193         * @param theCodeSystem            The code system, e.g. "<code>http://loinc.org</code>"
194         * @param theCode                  The code, e.g. "<code>1234-5</code>"
195         * @param theDisplay               The display name, if it should also be validated
196         * @param theValueSet              The ValueSet to validate against. Must not be null, and must be a ValueSet resource.
197         * @return Returns a validation result object, or <code>null</code> if this validation support module can not handle this kind of request
198         */
199        default CodeValidationResult validateCodeInValueSet(ValidationSupportContext theValidationSupportContext, ConceptValidationOptions theOptions, String theCodeSystem, String theCode, String theDisplay, @Nonnull IBaseResource theValueSet) {
200                return null;
201        }
202
203        /**
204         * Look up a code using the system and code value
205         *
206         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
207         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
208         * @param theSystem                The CodeSystem URL
209         * @param theCode                  The code
210         */
211        default LookupCodeResult lookupCode(ValidationSupportContext theValidationSupportContext, String theSystem, String theCode) {
212                return null;
213        }
214
215        /**
216         * Returns <code>true</code> if the given valueset can be validated by the given
217         * validation support module
218         *
219         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
220         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
221         * @param theValueSetUrl           The ValueSet canonical URL
222         */
223        default boolean isValueSetSupported(ValidationSupportContext theValidationSupportContext, String theValueSetUrl) {
224                return false;
225        }
226
227        /**
228         * Generate a snapshot from the given differential profile.
229         *
230         * @param theValidationSupportContext The validation support module will be passed in to this method. This is convenient in cases where the operation needs to make calls to
231         *                                 other method in the support chain, so that they can be passed through the entire chain. Implementations of this interface may always safely ignore this parameter.
232         * @return Returns null if this module does not know how to handle this request
233         */
234        default IBaseResource generateSnapshot(ValidationSupportContext theValidationSupportContext, IBaseResource theInput, String theUrl, String theWebUrl, String theProfileName) {
235                return null;
236        }
237
238        /**
239         * Returns the FHIR Context associated with this module
240         */
241        FhirContext getFhirContext();
242
243        /**
244         * This method clears any temporary caches within the validation support. It is mainly intended for unit tests,
245         * but could be used in non-test scenarios as well.
246         */
247        default void invalidateCaches() {
248                // nothing
249        }
250
251
252        class ConceptDesignation {
253                private String myLanguage;
254                private String myUseSystem;
255                private String myUseCode;
256                private String myUseDisplay;
257                private String myValue;
258
259                public String getLanguage() {
260                        return myLanguage;
261                }
262
263                public ConceptDesignation setLanguage(String theLanguage) {
264                        myLanguage = theLanguage;
265                        return this;
266                }
267
268                public String getUseSystem() {
269                        return myUseSystem;
270                }
271
272                public ConceptDesignation setUseSystem(String theUseSystem) {
273                        myUseSystem = theUseSystem;
274                        return this;
275                }
276
277                public String getUseCode() {
278                        return myUseCode;
279                }
280
281                public ConceptDesignation setUseCode(String theUseCode) {
282                        myUseCode = theUseCode;
283                        return this;
284                }
285
286                public String getUseDisplay() {
287                        return myUseDisplay;
288                }
289
290                public ConceptDesignation setUseDisplay(String theUseDisplay) {
291                        myUseDisplay = theUseDisplay;
292                        return this;
293                }
294
295                public String getValue() {
296                        return myValue;
297                }
298
299                public ConceptDesignation setValue(String theValue) {
300                        myValue = theValue;
301                        return this;
302                }
303        }
304
305        abstract class BaseConceptProperty {
306                private final String myPropertyName;
307
308                /**
309                 * Constructor
310                 */
311                protected BaseConceptProperty(String thePropertyName) {
312                        myPropertyName = thePropertyName;
313                }
314
315                public String getPropertyName() {
316                        return myPropertyName;
317                }
318        }
319
320        class StringConceptProperty extends BaseConceptProperty {
321                private final String myValue;
322
323                /**
324                 * Constructor
325                 *
326                 * @param theName The name
327                 */
328                public StringConceptProperty(String theName, String theValue) {
329                        super(theName);
330                        myValue = theValue;
331                }
332
333                public String getValue() {
334                        return myValue;
335                }
336        }
337
338        class CodingConceptProperty extends BaseConceptProperty {
339                private final String myCode;
340                private final String myCodeSystem;
341                private final String myDisplay;
342
343                /**
344                 * Constructor
345                 *
346                 * @param theName The name
347                 */
348                public CodingConceptProperty(String theName, String theCodeSystem, String theCode, String theDisplay) {
349                        super(theName);
350                        myCodeSystem = theCodeSystem;
351                        myCode = theCode;
352                        myDisplay = theDisplay;
353                }
354
355                public String getCode() {
356                        return myCode;
357                }
358
359                public String getCodeSystem() {
360                        return myCodeSystem;
361                }
362
363                public String getDisplay() {
364                        return myDisplay;
365                }
366        }
367
368        enum IssueSeverity {
369                /**
370                 * The issue caused the action to fail, and no further checking could be performed.
371                 */
372                FATAL,
373                /**
374                 * The issue is sufficiently important to cause the action to fail.
375                 */
376                ERROR,
377                /**
378                 * The issue is not important enough to cause the action to fail, but may cause it to be performed suboptimally or in a way that is not as desired.
379                 */
380                WARNING,
381                /**
382                 * The issue has no relation to the degree of success of the action.
383                 */
384                INFORMATION
385        }
386
387        class CodeValidationResult {
388                private String myCode;
389                private String myMessage;
390                private IssueSeverity mySeverity;
391                private String myCodeSystemName;
392                private String myCodeSystemVersion;
393                private List<BaseConceptProperty> myProperties;
394                private String myDisplay;
395
396                public CodeValidationResult() {
397                        super();
398                }
399
400                public String getDisplay() {
401                        return myDisplay;
402                }
403
404                public CodeValidationResult setDisplay(String theDisplay) {
405                        myDisplay = theDisplay;
406                        return this;
407                }
408
409                public String getCode() {
410                        return myCode;
411                }
412
413                public CodeValidationResult setCode(String theCode) {
414                        myCode = theCode;
415                        return this;
416                }
417
418                String getCodeSystemName() {
419                        return myCodeSystemName;
420                }
421
422                public CodeValidationResult setCodeSystemName(String theCodeSystemName) {
423                        myCodeSystemName = theCodeSystemName;
424                        return this;
425                }
426
427                public String getCodeSystemVersion() {
428                        return myCodeSystemVersion;
429                }
430
431                public CodeValidationResult setCodeSystemVersion(String theCodeSystemVersion) {
432                        myCodeSystemVersion = theCodeSystemVersion;
433                        return this;
434                }
435
436                public String getMessage() {
437                        return myMessage;
438                }
439
440                public CodeValidationResult setMessage(String theMessage) {
441                        myMessage = theMessage;
442                        return this;
443                }
444
445                public List<BaseConceptProperty> getProperties() {
446                        return myProperties;
447                }
448
449                public void setProperties(List<BaseConceptProperty> theProperties) {
450                        myProperties = theProperties;
451                }
452
453                public IssueSeverity getSeverity() {
454                        return mySeverity;
455                }
456
457                public CodeValidationResult setSeverity(IssueSeverity theSeverity) {
458                        mySeverity = theSeverity;
459                        return this;
460                }
461
462                public boolean isOk() {
463                        return isNotBlank(myCode);
464                }
465
466                public LookupCodeResult asLookupCodeResult(String theSearchedForSystem, String theSearchedForCode) {
467                        LookupCodeResult retVal = new LookupCodeResult();
468                        retVal.setSearchedForSystem(theSearchedForSystem);
469                        retVal.setSearchedForCode(theSearchedForCode);
470                        if (isOk()) {
471                                retVal.setFound(true);
472                                retVal.setCodeDisplay(myDisplay);
473                                retVal.setCodeSystemDisplayName(getCodeSystemName());
474                                retVal.setCodeSystemVersion(getCodeSystemVersion());
475                        }
476                        return retVal;
477                }
478
479                /**
480                 * Convenience method that returns {@link #getSeverity()} as an IssueSeverity code string
481                 */
482                public String getSeverityCode() {
483                        String retVal = null;
484                        if (getSeverity() != null) {
485                                retVal = getSeverity().name().toLowerCase();
486                        }
487                        return retVal;
488                }
489
490                /**
491                 * Sets an issue severity as a string code. Value must be the name of
492                 * one of the enum values in {@link IssueSeverity}. Value is case-insensitive.
493                 */
494                public CodeValidationResult setSeverityCode(@Nonnull String theIssueSeverity) {
495                        setSeverity(IssueSeverity.valueOf(theIssueSeverity.toUpperCase()));
496                        return this;
497                }
498        }
499
500        class ValueSetExpansionOutcome {
501
502                private final IBaseResource myValueSet;
503                private final String myError;
504
505                public ValueSetExpansionOutcome(IBaseResource theValueSet, String theError) {
506                        myValueSet = theValueSet;
507                        myError = theError;
508                }
509
510                public ValueSetExpansionOutcome(IBaseResource theValueSet) {
511                        myValueSet = theValueSet;
512                        myError = null;
513                }
514
515                public String getError() {
516                        return myError;
517                }
518
519                public IBaseResource getValueSet() {
520                        return myValueSet;
521                }
522        }
523
524        class LookupCodeResult {
525
526                private String myCodeDisplay;
527                private boolean myCodeIsAbstract;
528                private String myCodeSystemDisplayName;
529                private String myCodeSystemVersion;
530                private boolean myFound;
531                private String mySearchedForCode;
532                private String mySearchedForSystem;
533                private List<IValidationSupport.BaseConceptProperty> myProperties;
534                private List<ConceptDesignation> myDesignations;
535
536                /**
537                 * Constructor
538                 */
539                public LookupCodeResult() {
540                        super();
541                }
542
543                public List<BaseConceptProperty> getProperties() {
544                        if (myProperties == null) {
545                                myProperties = new ArrayList<>();
546                        }
547                        return myProperties;
548                }
549
550                public void setProperties(List<IValidationSupport.BaseConceptProperty> theProperties) {
551                        myProperties = theProperties;
552                }
553
554                @Nonnull
555                public List<ConceptDesignation> getDesignations() {
556                        if (myDesignations == null) {
557                                myDesignations = new ArrayList<>();
558                        }
559                        return myDesignations;
560                }
561
562                public String getCodeDisplay() {
563                        return myCodeDisplay;
564                }
565
566                public void setCodeDisplay(String theCodeDisplay) {
567                        myCodeDisplay = theCodeDisplay;
568                }
569
570                public String getCodeSystemDisplayName() {
571                        return myCodeSystemDisplayName;
572                }
573
574                public void setCodeSystemDisplayName(String theCodeSystemDisplayName) {
575                        myCodeSystemDisplayName = theCodeSystemDisplayName;
576                }
577
578                public String getCodeSystemVersion() {
579                        return myCodeSystemVersion;
580                }
581
582                public void setCodeSystemVersion(String theCodeSystemVersion) {
583                        myCodeSystemVersion = theCodeSystemVersion;
584                }
585
586                public String getSearchedForCode() {
587                        return mySearchedForCode;
588                }
589
590                public LookupCodeResult setSearchedForCode(String theSearchedForCode) {
591                        mySearchedForCode = theSearchedForCode;
592                        return this;
593                }
594
595                public String getSearchedForSystem() {
596                        return mySearchedForSystem;
597                }
598
599                public LookupCodeResult setSearchedForSystem(String theSearchedForSystem) {
600                        mySearchedForSystem = theSearchedForSystem;
601                        return this;
602                }
603
604                public boolean isCodeIsAbstract() {
605                        return myCodeIsAbstract;
606                }
607
608                public void setCodeIsAbstract(boolean theCodeIsAbstract) {
609                        myCodeIsAbstract = theCodeIsAbstract;
610                }
611
612                public boolean isFound() {
613                        return myFound;
614                }
615
616                public LookupCodeResult setFound(boolean theFound) {
617                        myFound = theFound;
618                        return this;
619                }
620
621                public void throwNotFoundIfAppropriate() {
622                        if (isFound() == false) {
623                                throw new ResourceNotFoundException("Unable to find code[" + getSearchedForCode() + "] in system[" + getSearchedForSystem() + "]");
624                        }
625                }
626
627                public IBaseParameters toParameters(FhirContext theContext, List<? extends IPrimitiveType<String>> theProperties) {
628
629                        IBaseParameters retVal = ParametersUtil.newInstance(theContext);
630                        if (isNotBlank(getCodeSystemDisplayName())) {
631                                ParametersUtil.addParameterToParametersString(theContext, retVal, "name", getCodeSystemDisplayName());
632                        }
633                        if (isNotBlank(getCodeSystemVersion())) {
634                                ParametersUtil.addParameterToParametersString(theContext, retVal, "version", getCodeSystemVersion());
635                        }
636                        ParametersUtil.addParameterToParametersString(theContext, retVal, "display", getCodeDisplay());
637                        ParametersUtil.addParameterToParametersBoolean(theContext, retVal, "abstract", isCodeIsAbstract());
638
639                        if (myProperties != null) {
640
641                                Set<String> properties = Collections.emptySet();
642                                if (theProperties != null) {
643                                        properties = theProperties
644                                                .stream()
645                                                .map(IPrimitiveType::getValueAsString)
646                                                .collect(Collectors.toSet());
647                                }
648
649                                for (IValidationSupport.BaseConceptProperty next : myProperties) {
650
651                                        if (!properties.isEmpty()) {
652                                                if (!properties.contains(next.getPropertyName())) {
653                                                        continue;
654                                                }
655                                        }
656
657                                        IBase property = ParametersUtil.addParameterToParameters(theContext, retVal, "property");
658                                        ParametersUtil.addPartCode(theContext, property, "code", next.getPropertyName());
659
660                                        if (next instanceof IValidationSupport.StringConceptProperty) {
661                                                IValidationSupport.StringConceptProperty prop = (IValidationSupport.StringConceptProperty) next;
662                                                ParametersUtil.addPartString(theContext, property, "value", prop.getValue());
663                                        } else if (next instanceof IValidationSupport.CodingConceptProperty) {
664                                                IValidationSupport.CodingConceptProperty prop = (IValidationSupport.CodingConceptProperty) next;
665                                                ParametersUtil.addPartCoding(theContext, property, "value", prop.getCodeSystem(), prop.getCode(), prop.getDisplay());
666                                        } else {
667                                                throw new IllegalStateException("Don't know how to handle " + next.getClass());
668                                        }
669                                }
670                        }
671
672                        if (myDesignations != null) {
673                                for (ConceptDesignation next : myDesignations) {
674
675                                        IBase property = ParametersUtil.addParameterToParameters(theContext, retVal, "designation");
676                                        ParametersUtil.addPartCode(theContext, property, "language", next.getLanguage());
677                                        ParametersUtil.addPartCoding(theContext, property, "use", next.getUseSystem(), next.getUseCode(), next.getUseDisplay());
678                                        ParametersUtil.addPartString(theContext, property, "value", next.getValue());
679                                }
680                        }
681
682                        return retVal;
683                }
684
685                public static LookupCodeResult notFound(String theSearchedForSystem, String theSearchedForCode) {
686                        return new LookupCodeResult()
687                                .setFound(false)
688                                .setSearchedForSystem(theSearchedForSystem)
689                                .setSearchedForCode(theSearchedForCode);
690                }
691        }
692
693}