Vinyeh commited on
Commit
afa0745
·
verified ·
1 Parent(s): 03a261d

Add pinned source: cql-clinical (part 6)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/README.md +16 -0
  2. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/build.gradle.kts +49 -0
  3. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/detekt-baseline.xml +250 -0
  4. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/Constants.kt +4 -0
  5. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/parser/Parser.kt +258 -0
  6. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu2/model/AnnotatedUuidType.kt +6 -0
  7. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu3/model/AnnotatedUuidType.kt +5 -0
  8. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/r4/model/AnnotatedUuidType.kt +5 -0
  9. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/BaseFhirTypeConverter.kt +471 -0
  10. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2FhirTypeConverter.kt +578 -0
  11. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu3FhirTypeConverter.kt +550 -0
  12. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverter.kt +444 -0
  13. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverterFactory.kt +25 -0
  14. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R4FhirTypeConverter.kt +545 -0
  15. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R5FhirTypeConverter.kt +541 -0
  16. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/FhirVersionMisMatchException.kt +3 -0
  17. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownElement.kt +5 -0
  18. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownPath.kt +5 -0
  19. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownType.kt +5 -0
  20. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu2FhirModelResolver.kt +156 -0
  21. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu3FhirModelResolver.kt +162 -0
  22. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/FhirModelResolver.kt +768 -0
  23. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R4FhirModelResolver.kt +169 -0
  24. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R5FhirModelResolver.kt +187 -0
  25. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/BaseFhirQueryGenerator.kt +460 -0
  26. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/CodeFilter.kt +9 -0
  27. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/DateFilter.kt +10 -0
  28. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/Dstu3FhirQueryGenerator.kt +215 -0
  29. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirBundleCursor.kt +142 -0
  30. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirQueryGeneratorFactory.kt +81 -0
  31. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirVersionIntegrityChecker.kt +11 -0
  32. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/R4FhirQueryGenerator.kt +212 -0
  33. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/RestFhirRetrieveProvider.kt +168 -0
  34. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/SearchParamFhirRetrieveProvider.kt +111 -0
  35. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterMap.kt +526 -0
  36. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterResolver.kt +167 -0
  37. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/Dstu3FhirTerminologyProvider.kt +200 -0
  38. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/HeaderInjectionInterceptor.kt +34 -0
  39. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/R4FhirTerminologyProvider.kt +197 -0
  40. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsDstu3Test.kt +166 -0
  41. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsR4Test.kt +253 -0
  42. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/DateTypeTest.kt +29 -0
  43. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu2Test.kt +75 -0
  44. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu3Test.kt +79 -0
  45. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestFhirPath.kt +367 -0
  46. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestLibrarySourceProvider.kt +28 -0
  47. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TranslatorHelper.kt +136 -0
  48. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/Dstu3FhirTest.kt +143 -0
  49. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/R4FhirTest.kt +143 -0
  50. source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/ConverterTestUtils.kt +59 -0
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/README.md ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # engine-fhir
2
+
3
+ This module contains the implementation of the FHIR model resolvers and retrieve providers for the CQL engine, based on the HAPI FHIR library.
4
+
5
+
6
+ ## Converting from HAPI FHIR structures to engine value types
7
+
8
+ The `FhirModelResolver.toCqlValue()` helper method converts HAPI FHIR structures (resources and individual elements) to appropriate `ClassInstance`s, which can then be used as inputs to the engine. Given a FHIR structure, the method:
9
+
10
+ - walks all child elements of the FHIR structure (using introspection methods and reflections on HAPI FHIR classes) and adds an entry for every child in the named tuple being built,
11
+ - checks max cardinality to determine if a CQL list or a singleton to use as the value,
12
+ - if the child FHIR element has no values, sets the element value to `null` in the tuple.
13
+
14
+ In general, the least nested structure is chosen for the value of an element, e.g.:
15
+ - when the element is List-typed but has no values, `null` is chosen instead of an empty list
16
+ - when an element is FHIR primitive-typed (e.g. `FHIR.string` or `FHIR.code`-typed) and does not have value/id/extensions, `null` is chosen instead of a blank structure like `FHIR.string { id: null, extension: null, value: null }`
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/build.gradle.kts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
2
+
3
+ plugins {
4
+ id("cql.xjc-conventions")
5
+ id("cql.fhir-kotlin-multiplatform-conventions")
6
+ }
7
+
8
+ val generateFhirPathTests =
9
+ tasks.register<XjcTask>("generateFhirPathTests") {
10
+ outputDir.set(
11
+ project.layout.buildDirectory.dir("generated/sources/engine-fhir/jvmTest/java")
12
+ )
13
+ schema.set("${projectDir}/src/jvmTest/resources/org/hl7/fhirpath/testSchema")
14
+ extraArgs.set(listOf("-npa", "-p", "org.hl7.fhirpath.tests"))
15
+ }
16
+
17
+ kotlin {
18
+ js { outputModuleName = "engine-fhir" }
19
+
20
+ @OptIn(ExperimentalWasmDsl::class) wasmJs { outputModuleName = "engine-fhir" }
21
+
22
+ sourceSets {
23
+ commonMain { dependencies { api(project(":engine")) } }
24
+
25
+ jvmMain { dependencies { api(project(":ucum")) } }
26
+
27
+ jvmTest {
28
+ dependencies {
29
+ implementation(libs.wiremock)
30
+ implementation(project(":cql-to-elm"))
31
+ implementation(project(":quick"))
32
+ implementation(libs.hapi.fhir.client)
33
+
34
+ // JAXB runtime deps needed for the classes generated by xjc
35
+ implementation(libs.jaxb2.commons.basics)
36
+ implementation(libs.jaxb2.commons.fluent.api)
37
+ implementation(libs.jakarta.xml.bind.api)
38
+ implementation(libs.jaxb.runtime)
39
+ implementation(libs.moxy)
40
+ }
41
+ }
42
+ }
43
+ }
44
+
45
+ java {
46
+ sourceSets { named("jvmTest") { java { srcDir(generateFhirPathTests.map { it.outputDir }) } } }
47
+ }
48
+
49
+ dependencies { kover(project(":engine")) }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/detekt-baseline.xml ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version='1.0' encoding='UTF-8'?>
2
+ <SmellBaseline>
3
+ <ManuallySuppressedIssues/>
4
+ <CurrentIssues>
5
+ <ID>ComplexCondition:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$context != null &amp;&amp; context == "Patient" &amp;&amp; contextValue != null &amp;&amp; contextPath != null</ID>
6
+ <ID>ComplexCondition:Parser.kt$jsonObject.containsKey(propertyKeyWithType) || (type is ClassType &amp;&amp; isFhirPrimitiveType(type) &amp;&amp; jsonObject.containsKey("_$propertyKeyWithType"))</ID>
7
+ <ID>ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.&lt;no name provided>$PATIENT == dataType &amp;&amp; PATIENT == context &amp;&amp; ID == contextPath &amp;&amp; _PATIENT_123 == contextValue</ID>
8
+ <ID>ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.&lt;no name provided>$PATIENT == dataType &amp;&amp; PRACTITIONER == context &amp;&amp; GENERAL_PRACTITIONER == contextPath &amp;&amp; equals</ID>
9
+ <ID>ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.&lt;no name provided>$PRACTITIONER == dataType &amp;&amp; PATIENT == context &amp;&amp; ID == codePath &amp;&amp; codesEqual(codes, PRACTITIONER_SLASH + XYZ)</ID>
10
+ <ID>CyclomaticComplexMethod:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( codes: Iterable&lt;Code?>?, valueSet: String?, ): MutableList&lt;TokenOrListParam></ID>
11
+ <ID>CyclomaticComplexMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toCqlType(value: Any?): Value?</ID>
12
+ <ID>CyclomaticComplexMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toFhirType(value: Value?): IBase?</ID>
13
+ <ID>CyclomaticComplexMethod:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
14
+ <ID>CyclomaticComplexMethod:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance?</ID>
15
+ <ID>CyclomaticComplexMethod:FhirModelResolver.kt$FhirModelResolver$private fun resolveTypeUncached(typeName: String?): Class&lt;*>?</ID>
16
+ <ID>CyclomaticComplexMethod:FhirModelResolverTest.kt$private fun validateCqlValueAgainstModel( fhirVersion: FhirVersionEnum, expectedFhirTypeName: String, cqlValue: Any?, )</ID>
17
+ <ID>CyclomaticComplexMethod:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value?</ID>
18
+ <ID>CyclomaticComplexMethod:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
19
+ <ID>CyclomaticComplexMethod:R5FhirModelResolver.kt$R5FhirModelResolver$override fun resolveType(typeName: String?): Class&lt;*>?</ID>
20
+ <ID>CyclomaticComplexMethod:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String</ID>
21
+ <ID>CyclomaticComplexMethod:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver&lt;*, *, *, *, *, *, *, *>, )</ID>
22
+ <ID>CyclomaticComplexMethod:TestR4ModelResolver.kt$TestR4ModelResolver$@Test @Throws(Exception::class) fun modelInfo401Tests()</ID>
23
+ <ID>ForbiddenComment:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$// TODO: Think about how to best handle the decision to expand value sets... Should it be part</ID>
24
+ <ID>ForbiddenComment:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$// TODO: This assumes the code path will always be a token param.</ID>
25
+ <ID>ForbiddenComment:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id,</ID>
26
+ <ID>ForbiddenComment:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in HAPI.</ID>
27
+ <ID>ForbiddenComment:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$// TODO: Deal with the case that the value is expressed as an expression extension</ID>
28
+ <ID>ForbiddenComment:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$// TODO: What to do if/when System is not provided...</ID>
29
+ <ID>ForbiddenComment:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id,</ID>
30
+ <ID>ForbiddenComment:FhirBundleCursor.kt$FhirBundleCursor.FhirBundleIterator$// TODO: It would be possible to get here if the next link was present, but the returned</ID>
31
+ <ID>ForbiddenComment:FhirExecutionMultiLibTestBase.kt$FhirExecutionMultiLibTestBase.Companion$// TODO: LD: figure out how to compile the CQLs only once for the whole test class</ID>
32
+ <ID>ForbiddenComment:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$// TODO: ModelInfo bug. Not aware of SimpleQuantity</ID>
33
+ <ID>ForbiddenComment:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$// TODO: Resolve Error: Could not load model information for model FHIR, version</ID>
34
+ <ID>ForbiddenComment:FhirModelResolver.kt$FhirModelResolver$/* * // TODO: Find HAPI registry of Primitive Type conversions public Object * fromJavaPrimitive(Object value, Object target) { String simpleName = * target.getClass().getSimpleName(); switch(simpleName) { case "DateTimeType": * case "InstantType": return ((DateTime)value).toJavaDate(); case "DateType": * return ((org.opencds.cqf.cql.engine.runtime.Date)value).toJavaDate(); case * "TimeType": return ((Time) value).toString(); } * * if (value instanceof Time) { return ((Time) value).toString(); } else { * return value; } } */</ID>
35
+ <ID>ForbiddenComment:FhirModelResolver.kt$FhirModelResolver$// TODO: Probably quite a bit of redundancy here. Probably only really need the BaseType and the</ID>
36
+ <ID>ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$* TODO: Add DSTU2 test. At the moment, * * FhirContext.forDstu2().getElementDefinition(org.hl7.fhir.dstu2.model.Extension().javaClass) * * throws * * HAPI-1690: Unknown profileOf value: class org.hl7.fhir.dstu2.model.StringType in type org.hl7.fhir.dstu2.model.IdType ...</ID>
37
+ <ID>ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$* TODO: Add DSTU2 test. At the moment, * * FhirContext.forDstu2().getResourceDefinition(org.hl7.fhir.dstu2.model.Patient()) * * throws * * HAPI-1731: This context is for FHIR version "DSTU2" but the class "org.hl7.fhir.dstu2.model.Patient" is for version "DSTU2_HL7ORG"</ID>
38
+ <ID>ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$* TODO: Add DSTU2 test. At the moment, it throws * * Could not resolve type NameUseEnumFactory. Primary package(s) for this resolver are * ca.uhn.fhir.model.dstu2,org.hl7.fhir.dstu2.model,ca.uhn.fhir.model.primitive</ID>
39
+ <ID>ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$// TODO: Add DSTU2 test</ID>
40
+ <ID>ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$// TODO: enable this for DSTU2 and DSTU3 models which use FHIR.ResourceContainer for</ID>
41
+ <ID>ForbiddenComment:R4FhirModelResolver.kt$R4FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in HAPI.</ID>
42
+ <ID>ForbiddenComment:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$// TODO: Deal with the case that the value is expressed as an expression extension</ID>
43
+ <ID>ForbiddenComment:R4FhirTypeConverter.kt$R4FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system</ID>
44
+ <ID>ForbiddenComment:R5FhirModelResolver.kt$R5FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in</ID>
45
+ <ID>ForbiddenComment:R5FhirTypeConverter.kt$R5FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id,</ID>
46
+ <ID>ForbiddenComment:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$// TODO: evaluate this lazily in case the engine only needs the first element</ID>
47
+ <ID>ForbiddenComment:SearchParameterResolver.kt$SearchParameterResolver$// TODO: All the others like "_language"</ID>
48
+ <ID>ForbiddenComment:SearchParameterResolver.kt$SearchParameterResolver$// TODO: What we really need is FhirPath parsing to just get the path</ID>
49
+ <ID>ForbiddenComment:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$// TODO: LD: Due to a type erasure and the CQL compiler historically being in separate</ID>
50
+ <ID>ForbiddenComment:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$// TODO: Consider making this an exception on the resolver because</ID>
51
+ <ID>ForbiddenComment:TestDstu3ModelResolver.kt$TestDstu3ModelResolver$// TODO: Consider making this an exception on the resolver because</ID>
52
+ <ID>ForbiddenComment:TestFhirExecution.kt$TestFhirExecution$// TODO: fix this... I think it requires a resource to be loaded - put in init bundle</ID>
53
+ <ID>ForbiddenComment:TestR4ModelResolver.kt$TestR4ModelResolver$// TODO: Consider making this an exception on the resolver because</ID>
54
+ <ID>ForbiddenComment:TestR4ModelResolver.kt$TestR4ModelResolver$// TODO: The cause of failure for this is unknown.</ID>
55
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// // TODO: HAPI Doesn't have a ResourceContainer type</ID>
56
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// // TODO: The cause of failure for this is unknown.</ID>
57
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Consider making this an exception on the resolver because</ID>
58
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Replace with 5.0.0 model info once that's available</ID>
59
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Replace with R5 special cases once that's available</ID>
60
+ <ID>ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver.Companion.&lt;no name provided>$// TODO: Add the remainder of the FHIR R5 enums.</ID>
61
+ <ID>FunctionParameterNaming:FhirModelResolver.kt$FhirModelResolver$`object`: Any</ID>
62
+ <ID>ImplicitDefaultLocale:TranslatorHelper.kt$TranslatorHelper$String.format( "[%d:%d, %d:%d]", tb.startLine, tb.startChar, tb.endLine, tb.endChar, )</ID>
63
+ <ID>IteratorNotThrowingNoSuchElementException:FhirBundleCursor.kt$FhirBundleCursor$FhirBundleIterator : Iterator</ID>
64
+ <ID>LargeClass:Dstu2TypeConverterTests.kt$Dstu2TypeConverterTests</ID>
65
+ <ID>LargeClass:Dstu3TypeConverterTests.kt$Dstu3TypeConverterTests</ID>
66
+ <ID>LargeClass:R4TypeConverterTests.kt$R4TypeConverterTests</ID>
67
+ <ID>LargeClass:R5TypeConverterTests.kt$R5TypeConverterTests</ID>
68
+ <ID>LongMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime</ID>
69
+ <ID>LongMethod:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
70
+ <ID>LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibraryEvaluationParams(): Stream&lt;Arguments?></ID>
71
+ <ID>LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibrarySingleEvaluationAtATimeParams(): Stream&lt;Arguments?></ID>
72
+ <ID>LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun singleLibraryEvaluationParams(): Stream&lt;Arguments></ID>
73
+ <ID>LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest$@ParameterizedTest @MethodSource("multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiledParams") fun multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiled(expressionCaching: Boolean)</ID>
74
+ <ID>LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibParams(): List&lt;Arguments></ID>
75
+ <ID>LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun singleLibParams(): List&lt;Arguments></ID>
76
+ <ID>LongMethod:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance?</ID>
77
+ <ID>LongMethod:FhirModelResolver.kt$FhirModelResolver$protected fun toDateTime( value: BaseDateTimeType, calendarConstant: Int = this.getCalendarConstant(value), ): DateTime</ID>
78
+ <ID>LongMethod:FhirModelResolverTest.kt$FhirModelResolverTest$@Test fun toCqlValueFhirPrimitiveWithValueAndExtension()</ID>
79
+ <ID>LongMethod:FhirModelResolverTest.kt$fun validateCqlValueAgainstModelInner(cqlValue: Any?, modelType: DataType)</ID>
80
+ <ID>LongMethod:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value?</ID>
81
+ <ID>LongMethod:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
82
+ <ID>LongMethod:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String</ID>
83
+ <ID>LongMethod:TestFHIR2Helpers.kt$TestFHIR2Helpers$fun test()</ID>
84
+ <ID>LongMethod:TestFHIR3Helpers.kt$TestFHIR3Helpers$fun test()</ID>
85
+ <ID>LongMethod:TestFHIRHelpers.kt$TestFHIRHelpers$@Test fun testFhirHelpers()</ID>
86
+ <ID>LongMethod:TestFhirDataProviderDstu3.kt$TestFhirDataProviderDstu3$fun testContained()</ID>
87
+ <ID>LongMethod:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver&lt;*, *, *, *, *, *, *, *>, )</ID>
88
+ <ID>LongMethod:TestR4ModelResolver.kt$TestR4ModelResolver$@Test fun modelInfoSpecialCaseTests()</ID>
89
+ <ID>LongParameterList:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$( context: String?, contextPath: String?, contextValue: String?, dataType: String?, templateId: String?, codeFilters: MutableList&lt;CodeFilter>?, dateFilters: MutableList&lt;DateFilter>?, )</ID>
90
+ <ID>LongParameterList:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$( context: String?, contextPath: String?, contextValue: String?, dataType: String?, templateId: String?, codePath: String?, codes: Iterable&lt;Code?>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, )</ID>
91
+ <ID>LongParameterList:FhirQueryGeneratorFactory.kt$FhirQueryGeneratorFactory$( modelResolver: ModelResolver, searchParameterResolver: SearchParameterResolver, terminologyProvider: TerminologyProvider?, shouldExpandValueSets: Boolean?, maxCodesPerQuery: Int?, pageSize: Int?, queryBatchThreshold: Int?, )</ID>
92
+ <ID>LoopWithTooManyJumpStatements:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$for</ID>
93
+ <ID>LoopWithTooManyJumpStatements:SearchParameterResolver.kt$SearchParameterResolver$for</ID>
94
+ <ID>LoopWithTooManyJumpStatements:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$for</ID>
95
+ <ID>LoopWithTooManyJumpStatements:TestDstu3ModelResolver.kt$TestDstu3ModelResolver$for</ID>
96
+ <ID>LoopWithTooManyJumpStatements:TestR4ModelResolver.kt$TestR4ModelResolver$for</ID>
97
+ <ID>MaxLineLength:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$"Expand value sets cannot be used without a terminology provider and no terminology provider is set."</ID>
98
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).isDistinct().not())"</ID>
99
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').exists())"</ID>
100
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime1').empty())"</ID>
101
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testSelect(Patient.name.select(given | family) = 'Peter' | 'James' | 'Chalmers' | 'Jim')"</ID>
102
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testVariables(%\"vs-administrative-gender\" = 'http://hl7.org/fhir/ValueSet/administrative-gender')"</ID>
103
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$$$"stu3/tests-fhir-r3/Dollar/testDollarThis1(Patient.name.given.where(substring($this.length()-3) = 'out'))"</ID>
104
+ <ID>MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$$$"stu3/tests-fhir-r3/Dollar/testDollarThis2(Patient.name.given.where(substring($this.length()-3) = 'ter'))"</ID>
105
+ <ID>MaxLineLength:CQLOperationsR4Test.kt$CQLOperationsR4Test.Companion$"r4/tests-fhir-r4/testInvariants/extension('http://hl7.org/fhir/us/cqfmeasures/StructureDefinition/cqfm-scoring').exists() and extension('http://hl7.org/fhir/us/cqfmeasures/StructureDefinition/cqfm-scoring').value = 'ratio' implies group.population.where(code.coding.where(system = 'http://terminology.hl7.org/CodeSystem/measure-population').code = 'initial-population').count() in (1 | 2)"</ID>
106
+ <ID>MaxLineLength:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$"Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time."</ID>
107
+ <ID>MaxLineLength:FhirModelResolver.kt$FhirModelResolver$"Could not resolve type $typeName. Primary package(s) for this resolver are ${this.packageNames.joinToString(",")}"</ID>
108
+ <ID>MaxLineLength:FhirModelResolver.kt$FhirModelResolver$"Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase."</ID>
109
+ <ID>MaxLineLength:FhirModelResolver.kt$FhirModelResolver$/* * type-to-class and contextPath resolutions are potentially expensive and can be cached * for improved performance. * * See &lt;a href="https://github.com/DBCG/cql-evaluator/blob/master/evaluator.engine/src/main/java/org/opencds/cqf/cql/evaluator/engine/model/CachingModelResolverDecorator.java"/> * for a decorator that adds caching logic for ModelResolvers. */</ID>
110
+ <ID>MaxLineLength:FhirModelResolverTest.kt$FhirModelResolverTest$*</ID>
111
+ <ID>MaxLineLength:Parser.kt$"Expected FHIR model for parsing FHIR resource, but got model ${model.modelInfo.name} with URL ${model.modelInfo.url}"</ID>
112
+ <ID>MaxLineLength:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$"Cannot process data requirements with subjects not specified using a code from http://hl7.org/fhir/resource-types"</ID>
113
+ <ID>MaxLineLength:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$"Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time."</ID>
114
+ <ID>MaxLineLength:TestFhirDataProviderDstu2.kt$TestFhirDataProviderDstu2$// FhirDataProviderDstu2().withEndpoint("http://fhirtest.uhn.ca/baseDstu2").withPackageName("ca.uhn.fhir.model.dstu2.composite");</ID>
115
+ <ID>MaxLineLength:TestFhirDataProviderDstu2.kt$TestFhirDataProviderDstu2$// FhirDataProviderDstu2().withEndpoint("http://fhirtest.uhn.ca/baseDstu2").withPackageName("ca.uhn.fhir.model.primitive");</ID>
116
+ <ID>MaxLineLength:TestFhirPath.kt$TestFhirPath$"%s failed as expected, but unable to determine the cause of the failure. Possible bug in engine. Skipping."</ID>
117
+ <ID>MaxLineLength:TestLibrarySourceProvider.kt$TestLibrarySourceProvider$"stu3/${libraryIdentifier.id}${if (libraryIdentifier.version != null) "-${libraryIdentifier.version}" else ""}.cql"</ID>
118
+ <ID>MaxLineLength:TestPrimitiveProfiles.kt$TestPrimitiveProfiles$/* define DistanceQuantity: FHIR.Quantity { value: FHIR.decimal { value: 1200.0 }, code: FHIR.code { value: 'km' } } define CastToDistance: DistanceQuantity as FHIR.Distance */</ID>
119
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code0,http://myterm.com/fhir/CodeSystem/MyValueSet|code1,http://myterm.com/fhir/CodeSystem/MyValueSet|code10,http://myterm.com/fhir/CodeSystem/MyValueSet|code11,http://myterm.com/fhir/CodeSystem/MyValueSet|code12,http://myterm.com/fhir/CodeSystem/MyValueSet|code13,http://myterm.com/fhir/CodeSystem/MyValueSet|code14,http://myterm.com/fhir/CodeSystem/MyValueSet|code15,http://myterm.com/fhir/CodeSystem/MyValueSet|code16,http://myterm.com/fhir/CodeSystem/MyValueSet|code17,http://myterm.com/fhir/CodeSystem/MyValueSet|code18,http://myterm.com/fhir/CodeSystem/MyValueSet|code19,http://myterm.com/fhir/CodeSystem/MyValueSet|code2,http://myterm.com/fhir/CodeSystem/MyValueSet|code20,http://myterm.com/fhir/CodeSystem/MyValueSet|code3,http://myterm.com/fhir/CodeSystem/MyValueSet|code4,http://myterm.com/fhir/CodeSystem/MyValueSet|code5,http://myterm.com/fhir/CodeSystem/MyValueSet|code6,http://myterm.com/fhir/CodeSystem/MyValueSet|code7,http://myterm.com/fhir/CodeSystem/MyValueSet|code8,http://myterm.com/fhir/CodeSystem/MyValueSet|code9&amp;subject=Patient/{{context.patientId}}"</ID>
120
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code0,http://myterm.com/fhir/CodeSystem/MyValueSet|code1,http://myterm.com/fhir/CodeSystem/MyValueSet|code2,http://myterm.com/fhir/CodeSystem/MyValueSet|code3&amp;subject=Patient/{{context.patientId}}"</ID>
121
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code0,http://myterm.com/fhir/CodeSystem/MyValueSet|code1,http://myterm.com/fhir/CodeSystem/MyValueSet|code2,http://myterm.com/fhir/CodeSystem/MyValueSet|code3,http://myterm.com/fhir/CodeSystem/MyValueSet|code4&amp;subject=Patient/{{context.patientId}}"</ID>
122
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code10,http://myterm.com/fhir/CodeSystem/MyValueSet|code11,http://myterm.com/fhir/CodeSystem/MyValueSet|code12,http://myterm.com/fhir/CodeSystem/MyValueSet|code13,http://myterm.com/fhir/CodeSystem/MyValueSet|code14&amp;subject=Patient/{{context.patientId}}"</ID>
123
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code15,http://myterm.com/fhir/CodeSystem/MyValueSet|code16,http://myterm.com/fhir/CodeSystem/MyValueSet|code17,http://myterm.com/fhir/CodeSystem/MyValueSet|code18,http://myterm.com/fhir/CodeSystem/MyValueSet|code19&amp;subject=Patient/{{context.patientId}}"</ID>
124
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code20&amp;subject=Patient/{{context.patientId}}"</ID>
125
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code4,http://myterm.com/fhir/CodeSystem/MyValueSet|code5,http://myterm.com/fhir/CodeSystem/MyValueSet|code6,http://myterm.com/fhir/CodeSystem/MyValueSet|code7&amp;subject=Patient/{{context.patientId}}"</ID>
126
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code5,http://myterm.com/fhir/CodeSystem/MyValueSet|code6,http://myterm.com/fhir/CodeSystem/MyValueSet|code7,http://myterm.com/fhir/CodeSystem/MyValueSet|code8,http://myterm.com/fhir/CodeSystem/MyValueSet|code9&amp;subject=Patient/{{context.patientId}}"</ID>
127
+ <ID>MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?date=ge${simpleDateFormatter.format(expectedRangeStartDateTime)}&amp;date=le${dateTimeFormatter.format(evaluationDateTimeAsLocal)}&amp;subject=Patient/{{context.patientId}}"</ID>
128
+ <ID>MemberNameEqualsClassName:ParserTest.kt$ParserTest$@Test fun parserTest()</ID>
129
+ <ID>MemberNameEqualsClassName:TestFHIRHelpers.kt$TestFHIRHelpers$@Test fun testFhirHelpers()</ID>
130
+ <ID>NestedBlockDepth:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$@JvmStatic fun dataMethod(): Array&lt;Array&lt;Any>></ID>
131
+ <ID>NestedBlockDepth:CQLOperationsR4Test.kt$CQLOperationsR4Test.Companion$@JvmStatic fun dataMethod(): Array&lt;Array&lt;Any>></ID>
132
+ <ID>NestedBlockDepth:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
133
+ <ID>NestedBlockDepth:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$fun setupCql( classToUse: Class&lt;*>, librariesToPopulate: MutableList&lt;Library?>, libraryManagerToUse: LibraryManager, )</ID>
134
+ <ID>NestedBlockDepth:FhirBundleCursor.kt$FhirBundleCursor.FhirBundleIterator$fun getTrustedEntries( entries: MutableList&lt;out IBaseResource>, templateId: String?, ): MutableList&lt;out IBaseResource></ID>
135
+ <ID>NestedBlockDepth:FhirExecutionTestBase.kt$FhirExecutionTestBase$@BeforeEach @Throws(IOException::class, UcumException::class) fun beforeEachTestMethod()</ID>
136
+ <ID>NestedBlockDepth:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance?</ID>
137
+ <ID>NestedBlockDepth:FhirModelResolver.kt$FhirModelResolver$private fun resolveChildren( children: List&lt;BaseRuntimeChildDefinition>, childName: String, ): Class&lt;*>?</ID>
138
+ <ID>NestedBlockDepth:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value?</ID>
139
+ <ID>NestedBlockDepth:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap&lt;String, String?>?, parameters: MutableMap&lt;String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList&lt;String></ID>
140
+ <ID>NestedBlockDepth:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$private fun executeQuery(dataType: String?, map: SearchParameterMap): IBaseResource?</ID>
141
+ <ID>NestedBlockDepth:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String</ID>
142
+ <ID>NestedBlockDepth:SearchParameterMap.kt$SearchParameterMap$private fun clean( theParamName: String?, theAndOrParams: MutableList&lt;MutableList&lt;IQueryParameterType>>, )</ID>
143
+ <ID>ObjectPropertyNaming:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$private const val _PATIENT_123 = "123"</ID>
144
+ <ID>PrintStackTrace:FhirExecutionTestBase.kt$FhirExecutionTestBase$e</ID>
145
+ <ID>PrintStackTrace:FhirHelpersDstu2Test.kt$FhirHelpersDstu2Test$e</ID>
146
+ <ID>PrintStackTrace:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$e</ID>
147
+ <ID>ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( codes: Iterable&lt;Code?>?, valueSet: String?, ): MutableList&lt;TokenOrListParam></ID>
148
+ <ID>ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( dataType: String?, codePath: String?, codes: Iterable&lt;Code?>?, valueSet: String?, ): Pair&lt;String, MutableList&lt;TokenOrListParam>>?</ID>
149
+ <ID>ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun innerSetupQueries( templateParam: Pair&lt;String, IQueryParameterType>?, contextParam: Pair&lt;String, IQueryParameterType>?, dateRangeParams: MutableList&lt;Pair&lt;String, DateRangeParam>>?, codeParams: MutableList&lt;Pair&lt;String, MutableList&lt;TokenOrListParam>>>?, ): MutableList&lt;SearchParameterMap></ID>
150
+ <ID>ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toCqlType(value: Any?): Value?</ID>
151
+ <ID>ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toFhirType(value: Value?): IBase?</ID>
152
+ <ID>ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime</ID>
153
+ <ID>ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toTime(calendar: Calendar, calendarConstant: Int): Time</ID>
154
+ <ID>ReturnCount:Dstu2FhirModelResolver.kt$Dstu2FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String?</ID>
155
+ <ID>ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval?</ID>
156
+ <ID>ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType&lt;Date>?): BaseTemporal?</ID>
157
+ <ID>ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType?</ID>
158
+ <ID>ReturnCount:Dstu2TypeConverterTests.kt$Dstu2TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean</ID>
159
+ <ID>ReturnCount:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String?</ID>
160
+ <ID>ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval?</ID>
161
+ <ID>ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType&lt;Date>?): BaseTemporal?</ID>
162
+ <ID>ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType?</ID>
163
+ <ID>ReturnCount:Dstu3TypeConverterTests.kt$Dstu3TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean</ID>
164
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance?</ID>
165
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$private fun resolveTypeUncached(typeName: String?): Class&lt;*>?</ID>
166
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun `is`(valueType: String, type: QName): kotlin.Boolean?</ID>
167
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun getContextPath( contextType: kotlin.String?, targetType: kotlin.String?, ): kotlin.String?</ID>
168
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun resolveId(target: Value?): kotlin.String?</ID>
169
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun innerGetContextPath( visitedElements: MutableSet&lt;String?>, child: BaseRuntimeChildDefinition, type: Class&lt;out IBase?>?, ): String?</ID>
170
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun resolveRuntimeDefinition(base: IBase): BaseRuntimeElementCompositeDefinition&lt;*></ID>
171
+ <ID>ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun toDateTime( value: BaseDateTimeType, calendarConstant: Int = this.getCalendarConstant(value), ): DateTime</ID>
172
+ <ID>ReturnCount:Issue1226.kt$Issue1226.&lt;no name provided>$override fun retrieve( context: String?, contextPath: String?, contextValue: String?, dataType: String, templateId: String?, codePath: String?, codes: Iterable&lt;Code>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, ): Iterable&lt;Value?></ID>
173
+ <ID>ReturnCount:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value?</ID>
174
+ <ID>ReturnCount:Parser.kt$private fun isFhirPrimitiveType(dataType: ClassType): kotlin.Boolean</ID>
175
+ <ID>ReturnCount:R4FhirModelResolver.kt$R4FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String?</ID>
176
+ <ID>ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval?</ID>
177
+ <ID>ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType&lt;Date>?): BaseTemporal?</ID>
178
+ <ID>ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType?</ID>
179
+ <ID>ReturnCount:R4TypeConverterTests.kt$R4TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean</ID>
180
+ <ID>ReturnCount:R5FhirModelResolver.kt$R5FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String?</ID>
181
+ <ID>ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval?</ID>
182
+ <ID>ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType&lt;Date>?): BaseTemporal?</ID>
183
+ <ID>ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType?</ID>
184
+ <ID>ReturnCount:R5TypeConverterTests.kt$R5TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean</ID>
185
+ <ID>ReturnCount:SearchParameterResolver.kt$SearchParameterResolver$fun createSearchParameter( context: String?, dataType: String?, path: String?, value: String?, ): Pair&lt;String, IQueryParameterType>?</ID>
186
+ <ID>ReturnCount:SearchParameterResolver.kt$SearchParameterResolver$fun getSearchParameterDefinition( dataType: String?, path: String?, paramType: RestSearchParameterTypeEnum?, ): RuntimeSearchParam?</ID>
187
+ <ID>ReturnCount:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.&lt;no name provided>$override fun retrieve( context: String?, contextPath: String?, contextValue: String?, dataType: String, templateId: String?, codePath: String?, codes: Iterable&lt;Code>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, ): Iterable&lt;Value?>?</ID>
188
+ <ID>ReturnCount:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$private fun codesEqual(codes: Iterable&lt;Code>?, equalTo: String): Boolean</ID>
189
+ <ID>ReturnCount:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver&lt;*, *, *, *, *, *, *, *>, )</ID>
190
+ <ID>SpreadOperator:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$(*codings)</ID>
191
+ <ID>SwallowedException:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$ex: Exception</ID>
192
+ <ID>SwallowedException:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$rnfe: ResourceNotFoundException</ID>
193
+ <ID>SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: IllegalAccessException</ID>
194
+ <ID>SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: InstantiationException</ID>
195
+ <ID>SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: InvocationTargetException</ID>
196
+ <ID>SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: NoSuchMethodException</ID>
197
+ <ID>SwallowedException:FhirModelResolverTest.kt$e: AssertionError</ID>
198
+ <ID>SwallowedException:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$ex: Exception</ID>
199
+ <ID>SwallowedException:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$rnfe: ResourceNotFoundException</ID>
200
+ <ID>SwallowedException:SearchParamFhirRetrieveProvider.kt$SearchParamFhirRetrieveProvider$exception: FhirVersionMisMatchException</ID>
201
+ <ID>SwallowedException:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$e: Exception</ID>
202
+ <ID>ThrowsCount:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$fun setupCql( classToUse: Class&lt;*>, librariesToPopulate: MutableList&lt;Library?>, libraryManagerToUse: LibraryManager, )</ID>
203
+ <ID>ThrowsCount:FhirModelResolver.kt$FhirModelResolver$protected fun createHapiInstance(clazz: Class&lt;*>): Any</ID>
204
+ <ID>ThrowsCount:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver&lt;*, *, *, *, *, *, *, *>, )</ID>
205
+ <ID>TooGenericExceptionCaught:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$ex: Exception</ID>
206
+ <ID>TooGenericExceptionCaught:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$e: Exception</ID>
207
+ <ID>TooGenericExceptionCaught:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$ex: Exception</ID>
208
+ <ID>TooGenericExceptionCaught:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$e: Exception</ID>
209
+ <ID>TooGenericExceptionThrown:Dstu3FhirTest.kt$Dstu3FhirTest.Companion$throw RuntimeException( "Failed to determine a port for the wiremock server", ex, )</ID>
210
+ <ID>TooGenericExceptionThrown:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$throw RuntimeException(error, exception)</ID>
211
+ <ID>TooGenericExceptionThrown:R4FhirTest.kt$R4FhirTest.Companion$throw RuntimeException( "Failed to determine a port for the wiremock server", ex, )</ID>
212
+ <ID>TooGenericExceptionThrown:SearchParamFhirRetrieveProvider.kt$SearchParamFhirRetrieveProvider$throw RuntimeException(exception.message)</ID>
213
+ <ID>TooManyFunctions:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator : FhirVersionIntegrityChecker</ID>
214
+ <ID>TooManyFunctions:BaseFhirTypeConverter.kt$BaseFhirTypeConverter : FhirTypeConverter</ID>
215
+ <ID>TooManyFunctions:Dstu2FhirModelResolver.kt$Dstu2FhirModelResolver : FhirModelResolver</ID>
216
+ <ID>TooManyFunctions:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter : BaseFhirTypeConverter</ID>
217
+ <ID>TooManyFunctions:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver : FhirModelResolver</ID>
218
+ <ID>TooManyFunctions:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter : BaseFhirTypeConverter</ID>
219
+ <ID>TooManyFunctions:FhirTypeConverter.kt$FhirTypeConverter</ID>
220
+ <ID>TooManyFunctions:R4FhirModelResolver.kt$R4FhirModelResolver : FhirModelResolver</ID>
221
+ <ID>TooManyFunctions:R4FhirTypeConverter.kt$R4FhirTypeConverter : BaseFhirTypeConverter</ID>
222
+ <ID>TooManyFunctions:R5FhirModelResolver.kt$R5FhirModelResolver : FhirModelResolver</ID>
223
+ <ID>TooManyFunctions:R5FhirTypeConverter.kt$R5FhirTypeConverter : BaseFhirTypeConverter</ID>
224
+ <ID>TooManyFunctions:SearchParameterMap.kt$SearchParameterMap : Serializable</ID>
225
+ <ID>TopLevelPropertyNaming:Constants.kt$const val fhirModelId = "FHIR"</ID>
226
+ <ID>TopLevelPropertyNaming:Constants.kt$const val fhirModelNamespaceUri = "http://hl7.org/fhir"</ID>
227
+ <ID>UnusedParameter:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$dateHighPath: String?</ID>
228
+ <ID>UnusedParameter:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$dateLowPath: String?</ID>
229
+ <ID>UnusedPrivateClass:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$TestRetrieveProvider : RetrieveProvider</ID>
230
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest$@Nonnull private fun getCqlEngineForFhirNewLibMgr(expressionCaching: Boolean): CqlEngine</ID>
231
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibraryEvaluationParams(): Stream&lt;Arguments?></ID>
232
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibrarySingleEvaluationAtATimeParams(): Stream&lt;Arguments?></ID>
233
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun singleLibraryEvaluationParams(): Stream&lt;Arguments></ID>
234
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiledParams(): List&lt;Arguments></ID>
235
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibParams(): List&lt;Arguments></ID>
236
+ <ID>UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun singleLibParams(): List&lt;Arguments></ID>
237
+ <ID>UnusedPrivateProperty:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator.Companion$i</ID>
238
+ <ID>UnusedPrivateProperty:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$index</ID>
239
+ <ID>UnusedPrivateProperty:TestCodeRef.kt$TestCodeRef$private val terminologyProvider = Dstu3FhirTerminologyProvider(fhirClient)</ID>
240
+ <ID>UseRequire:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime")</ID>
241
+ <ID>UseRequire:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period")</ID>
242
+ <ID>UseRequire:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime")</ID>
243
+ <ID>UseRequire:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period")</ID>
244
+ <ID>UseRequire:FhirModelResolver.kt$FhirModelResolver$throw IllegalArgumentException( "Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase." )</ID>
245
+ <ID>UseRequire:R4FhirTypeConverter.kt$R4FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime")</ID>
246
+ <ID>UseRequire:R4FhirTypeConverter.kt$R4FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period")</ID>
247
+ <ID>UseRequire:R5FhirTypeConverter.kt$R5FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime")</ID>
248
+ <ID>UseRequire:R5FhirTypeConverter.kt$R5FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period")</ID>
249
+ </CurrentIssues>
250
+ </SmellBaseline>
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/Constants.kt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir
2
+
3
+ const val fhirModelId = "FHIR"
4
+ const val fhirModelNamespaceUri = "http://hl7.org/fhir"
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/parser/Parser.kt ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.parser
2
+
3
+ import kotlinx.io.Source
4
+ import kotlinx.io.readString
5
+ import kotlinx.serialization.json.Json
6
+ import kotlinx.serialization.json.JsonArray
7
+ import kotlinx.serialization.json.JsonElement
8
+ import kotlinx.serialization.json.JsonNull
9
+ import kotlinx.serialization.json.JsonObject
10
+ import kotlinx.serialization.json.JsonPrimitive
11
+ import kotlinx.serialization.json.booleanOrNull
12
+ import kotlinx.serialization.json.contentOrNull
13
+ import kotlinx.serialization.json.intOrNull
14
+ import org.cqframework.cql.cql2elm.model.Model
15
+ import org.cqframework.cql.shared.BigDecimal
16
+ import org.cqframework.cql.shared.QName
17
+ import org.hl7.cql.model.ChoiceType
18
+ import org.hl7.cql.model.ClassType
19
+ import org.hl7.cql.model.DataType
20
+ import org.hl7.cql.model.ListType
21
+ import org.hl7.cql.model.NamedType
22
+ import org.hl7.cql.model.SimpleType
23
+ import org.opencds.cqf.cql.engine.fhir.fhirModelId
24
+ import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri
25
+ import org.opencds.cqf.cql.engine.runtime.ClassInstance
26
+ import org.opencds.cqf.cql.engine.runtime.Date
27
+ import org.opencds.cqf.cql.engine.runtime.DateTime
28
+ import org.opencds.cqf.cql.engine.runtime.Time
29
+ import org.opencds.cqf.cql.engine.runtime.Value
30
+ import org.opencds.cqf.cql.engine.runtime.toCqlBoolean
31
+ import org.opencds.cqf.cql.engine.runtime.toCqlDecimal
32
+ import org.opencds.cqf.cql.engine.runtime.toCqlInteger
33
+ import org.opencds.cqf.cql.engine.runtime.toCqlList
34
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
35
+ import org.opencds.cqf.cql.engine.util.offsetDateTimeParse
36
+ import org.opencds.cqf.cql.engine.util.zonedDateTimeNow
37
+
38
+ /** Parses a JSON [Source] representing a FHIR resource into a CQL [Value]. */
39
+ fun fhirResourceJsonToCqlValue(source: Source, model: Model): ClassInstance {
40
+ require(model.modelInfo.name == fhirModelId && model.modelInfo.url == fhirModelNamespaceUri) {
41
+ "Expected FHIR model for parsing FHIR resource, but got model ${model.modelInfo.name} with URL ${model.modelInfo.url}"
42
+ }
43
+
44
+ val jsonElement = Json.parseToJsonElement(source.readString())
45
+ require(jsonElement is JsonObject) {
46
+ "Expected JSON object for FHIR resource, but got $jsonElement"
47
+ }
48
+ return fhirResourceJsonObjectToCqlClassInstance(jsonElement, model)
49
+ }
50
+
51
+ /** Converts a JSON object representing a FHIR resource into a CQL [ClassInstance]. */
52
+ private fun fhirResourceJsonObjectToCqlClassInstance(
53
+ jsonObject: JsonObject,
54
+ model: Model,
55
+ ): ClassInstance {
56
+ val resourceType =
57
+ (jsonObject["resourceType"] as? JsonPrimitive)?.contentOrNull
58
+ ?: throw IllegalArgumentException("Missing or non-string resourceType")
59
+
60
+ val resourceClassType =
61
+ model.resolveTypeName(resourceType) as? ClassType
62
+ ?: throw IllegalArgumentException("Unsupported resource type $resourceType")
63
+
64
+ return jsonObjectToCqlClassInstance(jsonObject, resourceClassType, model)
65
+ }
66
+
67
+ /**
68
+ * Converts a JSON object representing a FHIR Resource, non-primitive type (complex datatype), or an
69
+ * objectified primitive type into a CQL [ClassInstance].
70
+ */
71
+ private fun jsonObjectToCqlClassInstance(
72
+ jsonObject: JsonObject,
73
+ dataType: ClassType,
74
+ model: Model,
75
+ ): ClassInstance {
76
+ if (dataType.name == "FHIR.Resource") {
77
+ return fhirResourceJsonObjectToCqlClassInstance(jsonObject, model)
78
+ }
79
+
80
+ return ClassInstance(
81
+ QName(fhirModelNamespaceUri, dataType.name.removePrefix(FHIR_PREFIX), fhirModelId),
82
+ dataType
83
+ .getAllElements()
84
+ .mapValues { (elementName, elementType) ->
85
+ extractPropertyFromJsonObjectAsCqlValue(jsonObject, elementName, elementType, model)
86
+ }
87
+ .toMutableMap(),
88
+ )
89
+ }
90
+
91
+ /**
92
+ * Extracts a property of a JSON object representing a FHIR Resource, non-primitive type (complex
93
+ * datatype), or an objectified primitive type as a CQL [Value].
94
+ */
95
+ private fun extractPropertyFromJsonObjectAsCqlValue(
96
+ jsonObject: JsonObject,
97
+ propertyKey: kotlin.String,
98
+ dataType: DataType,
99
+ model: Model,
100
+ ): Value? {
101
+ if (dataType is ChoiceType) {
102
+ // Elements that have a choice of datatype cannot repeat
103
+ for (type in dataType.types) {
104
+ require(type is NamedType) { "Expected named type $type but got $dataType" }
105
+ val fhirType = type.name.removePrefix(FHIR_PREFIX)
106
+ val propertyKeyWithType =
107
+ "$propertyKey${fhirType.replaceFirstChar { it.uppercaseChar() }}"
108
+ if (
109
+ jsonObject.containsKey(propertyKeyWithType) ||
110
+ (type is ClassType &&
111
+ isFhirPrimitiveType(type) &&
112
+ jsonObject.containsKey("_$propertyKeyWithType"))
113
+ ) {
114
+ return extractPropertyFromJsonObjectAsCqlValue(
115
+ jsonObject,
116
+ propertyKeyWithType,
117
+ type,
118
+ model,
119
+ )
120
+ }
121
+ }
122
+ return null
123
+ }
124
+
125
+ if (dataType is SimpleType) {
126
+ val jsonPrimitive = jsonObject[propertyKey] as? JsonPrimitive ?: return null
127
+
128
+ return when (dataType.name) {
129
+ "System.Boolean" -> jsonPrimitive.booleanOrNull?.toCqlBoolean()
130
+ "System.Integer" -> jsonPrimitive.intOrNull?.toCqlInteger()
131
+ "System.Decimal" -> jsonPrimitive.contentOrNull?.let { BigDecimal(it) }?.toCqlDecimal()
132
+ "System.String" -> jsonPrimitive.takeIf { it.isString }?.content?.toCqlString()
133
+ "System.Date" -> jsonPrimitive.takeIf { it.isString }?.content?.let { Date(it) }
134
+ "System.DateTime" ->
135
+ jsonPrimitive
136
+ .takeIf { it.isString }
137
+ ?.content
138
+ ?.let {
139
+ val zoneOffset =
140
+ try {
141
+ offsetDateTimeParse(it).getOffset()
142
+ } catch (_: Exception) {
143
+ zonedDateTimeNow().getOffset()
144
+ }
145
+
146
+ DateTime(it, zoneOffset)
147
+ }
148
+ "System.Time" -> jsonPrimitive.takeIf { it.isString }?.content?.let { Time(it) }
149
+ else -> throw IllegalArgumentException("Unsupported simple type $dataType")
150
+ }
151
+ }
152
+
153
+ if (dataType is ListType) {
154
+ val elementType = dataType.elementType
155
+ require(elementType is ClassType) { "Unsupported element type $elementType" }
156
+
157
+ if (isFhirPrimitiveType(elementType)) {
158
+ val primitiveValues = jsonObject[propertyKey] as? JsonArray
159
+ val extraPropertiesOfPrimitiveValues = jsonObject["_$propertyKey"] as? JsonArray
160
+ val len = maxOf(primitiveValues?.size ?: 0, extraPropertiesOfPrimitiveValues?.size ?: 0)
161
+
162
+ if (len == 0) return null
163
+
164
+ return List(len) { i ->
165
+ primitiveValueAndExtraPropertiesToCqlClassInstance(
166
+ primitiveValues?.getOrNull(i) ?: JsonNull,
167
+ extraPropertiesOfPrimitiveValues?.getOrNull(i) ?: JsonNull,
168
+ elementType,
169
+ model,
170
+ )
171
+ }
172
+ .toCqlList()
173
+ }
174
+
175
+ return (jsonObject[propertyKey] as? JsonArray)
176
+ ?.map { element ->
177
+ if (element is JsonObject) jsonObjectToCqlClassInstance(element, elementType, model)
178
+ else null
179
+ }
180
+ ?.toCqlList()
181
+ }
182
+
183
+ if (dataType is ClassType) {
184
+ if (isFhirPrimitiveType(dataType)) {
185
+ return primitiveValueAndExtraPropertiesToCqlClassInstance(
186
+ jsonObject[propertyKey] ?: JsonNull,
187
+ jsonObject["_$propertyKey"] ?: JsonNull,
188
+ dataType,
189
+ model,
190
+ )
191
+ }
192
+
193
+ val value = jsonObject[propertyKey]
194
+ return if (value is JsonObject) jsonObjectToCqlClassInstance(value, dataType, model)
195
+ else null
196
+ }
197
+
198
+ throw IllegalArgumentException("Unsupported data type $dataType")
199
+ }
200
+
201
+ /**
202
+ * Converts the JSON elements representing the FHIR primitive value and its extra properties (`id`,
203
+ * `extension`) into a CQL [ClassInstance] of the given FHIR primitive type.
204
+ */
205
+ private fun primitiveValueAndExtraPropertiesToCqlClassInstance(
206
+ primitiveValue: JsonElement,
207
+ extraProperties: JsonElement,
208
+ dataType: ClassType,
209
+ model: Model,
210
+ ): ClassInstance? {
211
+ if (primitiveValue is JsonNull && extraProperties is JsonNull) {
212
+ return null
213
+ }
214
+ val jsonObject =
215
+ JsonObject(
216
+ mapOf("value" to primitiveValue).let {
217
+ when (extraProperties) {
218
+ is JsonNull -> it
219
+ is JsonObject -> it + extraProperties
220
+ else ->
221
+ throw IllegalArgumentException(
222
+ "Expected JSON object or null but got $extraProperties"
223
+ )
224
+ }
225
+ }
226
+ )
227
+ return jsonObjectToCqlClassInstance(jsonObject, dataType, model)
228
+ }
229
+
230
+ private fun isFhirPrimitiveType(dataType: ClassType): kotlin.Boolean {
231
+ val typeName = dataType.name.removePrefix(FHIR_PREFIX)
232
+ val firstChar = typeName.firstOrNull() ?: return false
233
+ if (firstChar.lowercaseChar() == firstChar) {
234
+ return true
235
+ }
236
+ val baseType = dataType.baseType
237
+ if (baseType is ClassType && baseType.name == "FHIR.Element") {
238
+ val element = dataType.elements.singleOrNull() ?: return false
239
+ val elementType = element.type
240
+ if (
241
+ element.name == "value" &&
242
+ elementType is SimpleType &&
243
+ elementType.name == "System.String"
244
+ ) {
245
+ return true
246
+ }
247
+ }
248
+
249
+ return false
250
+ }
251
+
252
+ /** Collects all elements of a class type, including inherited elements. */
253
+ private fun ClassType.getAllElements(): Map<kotlin.String, DataType> {
254
+ return (if (baseType is ClassType) (baseType as ClassType).getAllElements() else emptyMap()) +
255
+ elements.associate { it.name to it.type }
256
+ }
257
+
258
+ private const val FHIR_PREFIX = "FHIR."
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu2/model/AnnotatedUuidType.kt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ package org.hl7.fhir.dstu2.model
2
+
3
+ import ca.uhn.fhir.model.api.annotation.DatatypeDef
4
+ import ca.uhn.fhir.model.primitive.UriDt
5
+
6
+ @DatatypeDef(name = "uuid") class AnnotatedUuidType : UriDt()
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu3/model/AnnotatedUuidType.kt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ package org.hl7.fhir.dstu3.model
2
+
3
+ import ca.uhn.fhir.model.api.annotation.DatatypeDef
4
+
5
+ @DatatypeDef(name = "uuid") class AnnotatedUuidType : UuidType()
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/r4/model/AnnotatedUuidType.kt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ package org.hl7.fhir.r4.model
2
+
3
+ import ca.uhn.fhir.model.api.annotation.DatatypeDef
4
+
5
+ @DatatypeDef(name = "uuid") class AnnotatedUuidType : UuidType()
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/BaseFhirTypeConverter.kt ADDED
@@ -0,0 +1,471 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
4
+ import java.io.PrintWriter
5
+ import java.io.StringWriter
6
+ import java.math.BigDecimal
7
+ import java.util.*
8
+ import org.apache.commons.lang3.NotImplementedException
9
+ import org.hl7.fhir.instance.model.api.IBase
10
+ import org.hl7.fhir.instance.model.api.IBaseCoding
11
+ import org.hl7.fhir.instance.model.api.ICompositeType
12
+ import org.hl7.fhir.instance.model.api.IIdType
13
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
14
+ import org.opencds.cqf.cql.engine.exception.InvalidPrecision
15
+ import org.opencds.cqf.cql.engine.runtime.Boolean
16
+ import org.opencds.cqf.cql.engine.runtime.Code
17
+ import org.opencds.cqf.cql.engine.runtime.Concept
18
+ import org.opencds.cqf.cql.engine.runtime.Date
19
+ import org.opencds.cqf.cql.engine.runtime.DateTime
20
+ import org.opencds.cqf.cql.engine.runtime.Decimal
21
+ import org.opencds.cqf.cql.engine.runtime.Integer
22
+ import org.opencds.cqf.cql.engine.runtime.Interval
23
+ import org.opencds.cqf.cql.engine.runtime.List
24
+ import org.opencds.cqf.cql.engine.runtime.Long
25
+ import org.opencds.cqf.cql.engine.runtime.Precision
26
+ import org.opencds.cqf.cql.engine.runtime.Quantity
27
+ import org.opencds.cqf.cql.engine.runtime.Ratio
28
+ import org.opencds.cqf.cql.engine.runtime.String
29
+ import org.opencds.cqf.cql.engine.runtime.TemporalHelper
30
+ import org.opencds.cqf.cql.engine.runtime.Time
31
+ import org.opencds.cqf.cql.engine.runtime.Tuple
32
+ import org.opencds.cqf.cql.engine.runtime.Value
33
+ import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName
34
+ import org.opencds.cqf.cql.engine.runtime.dateTypeName
35
+ import org.opencds.cqf.cql.engine.runtime.quantityTypeName
36
+ import org.opencds.cqf.cql.engine.runtime.toCqlBoolean
37
+ import org.opencds.cqf.cql.engine.runtime.toCqlDecimal
38
+ import org.opencds.cqf.cql.engine.runtime.toCqlInteger
39
+ import org.opencds.cqf.cql.engine.runtime.toCqlList
40
+ import org.opencds.cqf.cql.engine.runtime.toCqlLong
41
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
42
+
43
+ internal abstract class BaseFhirTypeConverter : FhirTypeConverter {
44
+ override fun isFhirType(value: Any): kotlin.Boolean {
45
+ require(value !is Iterable<*>) { "isFhirType can not be used for Iterables" }
46
+ return value is IBase
47
+ }
48
+
49
+ override fun toFhirTypes(values: List): MutableList<Any?> {
50
+ val converted: MutableList<Any?> = ArrayList<Any?>()
51
+ for (value in values) {
52
+ if (value == null) {
53
+ converted.add(null)
54
+ } else if (value is List) {
55
+ converted.add(toFhirTypes(value))
56
+ } else if (isFhirType(value)) {
57
+ converted.add(value)
58
+ } else {
59
+ converted.add(toFhirType(value))
60
+ }
61
+ }
62
+
63
+ return converted
64
+ }
65
+
66
+ override fun toFhirType(value: Value?): IBase? {
67
+ if (value == null) {
68
+ return null
69
+ }
70
+
71
+ require(value !is List) { "use toFhirTypes(Iterable<Object>) for iterables" }
72
+
73
+ if (value is Exception) {
74
+ return toFhirOperationOutcome(value)
75
+ }
76
+
77
+ if (isFhirType(value)) {
78
+ return value as IBase
79
+ }
80
+
81
+ require(isCqlType(value)) { "can't convert ${value.javaClass.name} to FHIR type" }
82
+
83
+ when (value) {
84
+ is Boolean -> return toFhirBoolean(value)
85
+ is Integer -> return toFhirInteger(value)
86
+ is Long -> return toFhirLong(value)
87
+ is Decimal -> return toFhirDecimal(value)
88
+ is Date -> return toFhirDate(value)
89
+ is DateTime -> return toFhirDateTime(value)
90
+ is Time -> return toFhirTime(value)
91
+ is String -> return toFhirString(value)
92
+ is Quantity -> return toFhirQuantity(value)
93
+ is Ratio -> return toFhirRatio(value)
94
+ is Code -> return toFhirCoding(value)
95
+ is Concept -> return toFhirCodeableConcept(value)
96
+ is Interval -> return toFhirInterval(value)
97
+ is Tuple -> return toFhirTuple(value)
98
+ else -> return toCqlText(value)
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Converts a Long to the FHIR type that System.Long maps to in this FHIR version. Defaults to
104
+ * integer64; versions without integer64 override this.
105
+ *
106
+ * @param value the value to convert
107
+ * @return the FHIR representation of the Long
108
+ */
109
+ protected open fun toFhirLong(value: Long): IBase? {
110
+ return toFhirInteger64(value)
111
+ }
112
+
113
+ /**
114
+ * Determines whether the given string is a CQL calendar unit
115
+ *
116
+ * @param unit
117
+ * @return true if the given unit is a CQL calendar unit
118
+ */
119
+ override fun isCqlCalendarUnit(unit: kotlin.String?): kotlin.Boolean {
120
+ if (unit == null) {
121
+ return false
122
+ }
123
+
124
+ return when (unit) {
125
+ "milliseconds",
126
+ "millisecond",
127
+ "seconds",
128
+ "second",
129
+ "minutes",
130
+ "minute",
131
+ "hours",
132
+ "hour",
133
+ "days",
134
+ "day",
135
+ "weeks",
136
+ "week",
137
+ "months",
138
+ "month",
139
+ "years",
140
+ "year" -> true
141
+ else -> false
142
+ }
143
+ }
144
+
145
+ /**
146
+ * Converts the given CQL unit to a UCUM definite-time duration unit according to the table and
147
+ * process defined in the CQL specification: https://cql.hl7.org/02-authorsguide.html#quantities
148
+ *
149
+ * @param unit
150
+ * @return An equivalent UCUM unit for the given CQL calendar duration unit, if the input is a
151
+ * CQL calendar duration unit, otherwise returns the input unit.
152
+ */
153
+ override fun toUcumUnit(unit: kotlin.String?): kotlin.String? {
154
+ if (unit == null) {
155
+ return null
156
+ }
157
+
158
+ return when (unit) {
159
+ "milliseconds",
160
+ "millisecond" -> "ms"
161
+ "seconds",
162
+ "second" -> "s"
163
+ "minutes",
164
+ "minute" -> "min"
165
+ "hours",
166
+ "hour" -> "h"
167
+ "days",
168
+ "day" -> "d"
169
+ "weeks",
170
+ "week" -> "wk"
171
+ "months",
172
+ "month" -> "mo"
173
+ "years",
174
+ "year" -> "a"
175
+ else -> unit
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Converts a Ucum unit to the equivalent CQL unit according to the table defined in the CQL
181
+ * specification: https://cql.hl7.org/02-authorsguide.html#quantities
182
+ *
183
+ * @param unit
184
+ * @return A CQL calendar unit if the input unit is a Ucum definite-duration unit, otherwise,
185
+ * the input unit
186
+ */
187
+ override fun toCqlCalendarUnit(unit: kotlin.String?): kotlin.String? {
188
+ return when (unit) {
189
+ null -> null
190
+ "ms" -> "millisecond"
191
+ "s" -> "second"
192
+ "min" -> "minute"
193
+ "h" -> "hour"
194
+ "d" -> "day"
195
+ "wk" -> "week"
196
+ "mo" -> "month"
197
+ "a" -> "year"
198
+ else -> unit
199
+ }
200
+ }
201
+
202
+ override fun toFhirInterval(value: Interval?): IBase? {
203
+ if (value == null) {
204
+ return null
205
+ }
206
+
207
+ return when (value.pointType) {
208
+ dateTypeName,
209
+ dateTimeTypeName -> toFhirPeriod(value)
210
+ quantityTypeName -> toFhirRange(value)
211
+ else -> toCqlText(value)
212
+ }
213
+ }
214
+
215
+ override fun isCqlType(value: Any): kotlin.Boolean {
216
+ return value is Value
217
+ }
218
+
219
+ override fun toCqlTypes(values: Iterable<*>): Iterable<Value?> {
220
+ val converted = mutableListOf<Value?>()
221
+ for (value in values) {
222
+ if (value == null) {
223
+ converted.add(null)
224
+ } else if (value is Iterable<*>) {
225
+ converted.add(toCqlTypes(value).toCqlList())
226
+ } else if (isCqlType(value)) {
227
+ converted.add(value as Value)
228
+ } else {
229
+ converted.add(toCqlType(value))
230
+ }
231
+ }
232
+
233
+ return converted
234
+ }
235
+
236
+ override fun toCqlType(value: Any?): Value? {
237
+ if (value == null) {
238
+ return null
239
+ }
240
+
241
+ require(value !is Iterable<*>) { "use toCqlTypes(Iterable<Object>) for iterables" }
242
+
243
+ if (isCqlType(value)) {
244
+ return value as Value
245
+ }
246
+
247
+ require(isFhirType(value)) { "can't convert ${value.javaClass.name} to CQL type" }
248
+
249
+ when (value.javaClass.getSimpleName()) {
250
+ "IdType" -> return toCqlId(value as IIdType)
251
+ "BooleanType" -> return toCqlBoolean(value.asIPrimitive())
252
+ "IntegerType" -> return toCqlInteger(value.asIPrimitive())
253
+ "Integer64Type" -> return toCqlLong(value.asIPrimitive())
254
+ "DecimalType" -> return toCqlDecimal(value.asIPrimitive())
255
+ "DateType" -> return toCqlDate(value.asIPrimitive())
256
+ "InstantType",
257
+ "DateTimeType" -> return toCqlDateTime(value.asIPrimitive())
258
+ "TimeType" -> return toCqlTime(value.asIPrimitive())
259
+ "StringType" -> return toCqlString(value.asIPrimitive())
260
+ "Quantity" -> return toCqlQuantity(value as ICompositeType)
261
+ "Ratio" -> return toCqlRatio(value as ICompositeType)
262
+ "Coding" -> return toCqlCode(value as IBaseCoding)
263
+ "CodeableConcept" -> return toCqlConcept(value as ICompositeType)
264
+ "Period",
265
+ "Range" -> return toCqlInterval(value as ICompositeType)
266
+ else ->
267
+ throw IllegalArgumentException(
268
+ "missing case statement for: ${value.javaClass.name}"
269
+ )
270
+ }
271
+ }
272
+
273
+ private fun <T> Any?.asIPrimitive(): IPrimitiveType<T>? {
274
+ @Suppress("UNCHECKED_CAST")
275
+ return this as? IPrimitiveType<T>
276
+ }
277
+
278
+ override fun toCqlId(value: IIdType?): String? {
279
+ if (value == null) {
280
+ return null
281
+ }
282
+
283
+ return value.idPart?.toCqlString()
284
+ }
285
+
286
+ override fun toCqlBoolean(value: IPrimitiveType<kotlin.Boolean>?): Boolean? {
287
+ if (value == null) {
288
+ return null
289
+ }
290
+
291
+ return value.getValue()?.toCqlBoolean()
292
+ }
293
+
294
+ override fun toCqlInteger(value: IPrimitiveType<Int>?): Integer? {
295
+ if (value == null) {
296
+ return null
297
+ }
298
+
299
+ return value.getValue()?.toCqlInteger()
300
+ }
301
+
302
+ override fun toCqlLong(value: IPrimitiveType<kotlin.Long>?): Long? {
303
+ if (value == null) {
304
+ return null
305
+ }
306
+
307
+ return value.getValue()?.toCqlLong()
308
+ }
309
+
310
+ override fun toCqlDecimal(value: IPrimitiveType<BigDecimal>?): Decimal? {
311
+ if (value == null) {
312
+ return null
313
+ }
314
+
315
+ return value.getValue()?.toCqlDecimal()
316
+ }
317
+
318
+ override fun toCqlTime(value: IPrimitiveType<kotlin.String>?): Time? {
319
+ if (value == null) {
320
+ return null
321
+ }
322
+
323
+ return Time(value.getValue())
324
+ }
325
+
326
+ override fun toCqlString(value: IPrimitiveType<kotlin.String>?): String? {
327
+ if (value == null) {
328
+ return null
329
+ }
330
+
331
+ return value.getValue()?.toCqlString()
332
+ }
333
+
334
+ override fun toCqlTuple(value: IBase?): Tuple? {
335
+ if (value == null) {
336
+ return null
337
+ }
338
+
339
+ throw NotImplementedException("toCqlTuple is not yet implemented")
340
+ }
341
+
342
+ protected fun toTime(calendar: Calendar, calendarConstant: Int): Time {
343
+ when (calendarConstant) {
344
+ Calendar.HOUR -> return Time(calendar.get(Calendar.HOUR))
345
+ Calendar.MINUTE ->
346
+ return Time(calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE))
347
+
348
+ Calendar.SECOND ->
349
+ return Time(
350
+ calendar.get(Calendar.HOUR),
351
+ calendar.get(Calendar.MINUTE),
352
+ calendar.get(Calendar.SECOND),
353
+ )
354
+
355
+ Calendar.MILLISECOND ->
356
+ return Time(
357
+ calendar.get(Calendar.HOUR),
358
+ calendar.get(Calendar.MINUTE),
359
+ calendar.get(Calendar.SECOND),
360
+ calendar.get(Calendar.MILLISECOND),
361
+ )
362
+
363
+ else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant")
364
+ }
365
+ }
366
+
367
+ protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime {
368
+ val tz =
369
+ if (calendar.getTimeZone() == null) TimeZone.getDefault() else calendar.getTimeZone()
370
+ val zoneOffset = tz.toZoneId().rules.getStandardOffset(calendar.toInstant())
371
+ when (calendarConstant) {
372
+ Calendar.YEAR ->
373
+ return DateTime(
374
+ TemporalHelper.zoneToOffset(zoneOffset),
375
+ calendar.get(Calendar.YEAR),
376
+ )
377
+ Calendar.MONTH ->
378
+ return DateTime(
379
+ TemporalHelper.zoneToOffset(zoneOffset),
380
+ calendar.get(Calendar.YEAR),
381
+ calendar.get(Calendar.MONTH) + 1,
382
+ )
383
+
384
+ Calendar.DAY_OF_MONTH ->
385
+ return DateTime(
386
+ TemporalHelper.zoneToOffset(zoneOffset),
387
+ calendar.get(Calendar.YEAR),
388
+ calendar.get(Calendar.MONTH) + 1,
389
+ calendar.get(Calendar.DAY_OF_MONTH),
390
+ )
391
+
392
+ Calendar.HOUR_OF_DAY ->
393
+ return DateTime(
394
+ TemporalHelper.zoneToOffset(zoneOffset),
395
+ calendar.get(Calendar.YEAR),
396
+ calendar.get(Calendar.MONTH) + 1,
397
+ calendar.get(Calendar.DAY_OF_MONTH),
398
+ calendar.get(Calendar.HOUR_OF_DAY),
399
+ )
400
+
401
+ Calendar.MINUTE ->
402
+ return DateTime(
403
+ TemporalHelper.zoneToOffset(zoneOffset),
404
+ calendar.get(Calendar.YEAR),
405
+ calendar.get(Calendar.MONTH) + 1,
406
+ calendar.get(Calendar.DAY_OF_MONTH),
407
+ calendar.get(Calendar.HOUR_OF_DAY),
408
+ calendar.get(Calendar.MINUTE),
409
+ )
410
+
411
+ Calendar.SECOND ->
412
+ return DateTime(
413
+ TemporalHelper.zoneToOffset(zoneOffset),
414
+ calendar.get(Calendar.YEAR),
415
+ calendar.get(Calendar.MONTH) + 1,
416
+ calendar.get(Calendar.DAY_OF_MONTH),
417
+ calendar.get(Calendar.HOUR_OF_DAY),
418
+ calendar.get(Calendar.MINUTE),
419
+ calendar.get(Calendar.SECOND),
420
+ )
421
+
422
+ Calendar.MILLISECOND ->
423
+ return DateTime(
424
+ TemporalHelper.zoneToOffset(zoneOffset),
425
+ calendar.get(Calendar.YEAR),
426
+ calendar.get(Calendar.MONTH) + 1,
427
+ calendar.get(Calendar.DAY_OF_MONTH),
428
+ calendar.get(Calendar.HOUR_OF_DAY),
429
+ calendar.get(Calendar.MINUTE),
430
+ calendar.get(Calendar.SECOND),
431
+ calendar.get(Calendar.MILLISECOND),
432
+ )
433
+
434
+ else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant")
435
+ }
436
+ }
437
+
438
+ protected fun toDate(calendar: Calendar, calendarConstant: Int): Date {
439
+ return when (calendarConstant) {
440
+ Calendar.YEAR -> Date(calendar.get(Calendar.YEAR))
441
+ Calendar.MONTH -> Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1)
442
+
443
+ Calendar.DAY_OF_MONTH ->
444
+ Date(
445
+ calendar.get(Calendar.YEAR),
446
+ calendar.get(Calendar.MONTH) + 1,
447
+ calendar.get(Calendar.DAY_OF_MONTH),
448
+ )
449
+
450
+ else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant")
451
+ }
452
+ }
453
+
454
+ protected fun toFhirPrecision(precision: Precision): TemporalPrecisionEnum {
455
+ val name =
456
+ when (precision) {
457
+ Precision.WEEK,
458
+ Precision.HOUR,
459
+ Precision.MINUTE -> TemporalPrecisionEnum.DAY.name
460
+ Precision.MILLISECOND -> TemporalPrecisionEnum.MILLI.name
461
+ else -> precision.name
462
+ }
463
+ return TemporalPrecisionEnum.valueOf(name)
464
+ }
465
+
466
+ protected fun getStackTraceAsString(exception: Exception): kotlin.String {
467
+ val sw = StringWriter()
468
+ PrintWriter(sw).use { pw -> exception.printStackTrace(pw) }
469
+ return sw.toString()
470
+ }
471
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2FhirTypeConverter.kt ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
4
+ import java.math.BigDecimal
5
+ import java.util.*
6
+ import java.util.stream.Collectors
7
+ import org.apache.commons.lang3.NotImplementedException
8
+ import org.hl7.fhir.dstu2.model.BaseDateTimeType
9
+ import org.hl7.fhir.dstu2.model.BooleanType
10
+ import org.hl7.fhir.dstu2.model.CodeType
11
+ import org.hl7.fhir.dstu2.model.CodeableConcept
12
+ import org.hl7.fhir.dstu2.model.Coding
13
+ import org.hl7.fhir.dstu2.model.DateTimeType
14
+ import org.hl7.fhir.dstu2.model.DateType
15
+ import org.hl7.fhir.dstu2.model.DecimalType
16
+ import org.hl7.fhir.dstu2.model.IdType
17
+ import org.hl7.fhir.dstu2.model.IntegerType
18
+ import org.hl7.fhir.dstu2.model.OperationOutcome
19
+ import org.hl7.fhir.dstu2.model.Parameters
20
+ import org.hl7.fhir.dstu2.model.Period
21
+ import org.hl7.fhir.dstu2.model.Range
22
+ import org.hl7.fhir.dstu2.model.Resource
23
+ import org.hl7.fhir.dstu2.model.SimpleQuantity
24
+ import org.hl7.fhir.dstu2.model.StringType
25
+ import org.hl7.fhir.dstu2.model.TimeType
26
+ import org.hl7.fhir.dstu2.model.Type
27
+ import org.hl7.fhir.instance.model.api.IBase
28
+ import org.hl7.fhir.instance.model.api.IBaseCoding
29
+ import org.hl7.fhir.instance.model.api.IBaseDatatype
30
+ import org.hl7.fhir.instance.model.api.IBaseOperationOutcome
31
+ import org.hl7.fhir.instance.model.api.ICompositeType
32
+ import org.hl7.fhir.instance.model.api.IIdType
33
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
34
+ import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator
35
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL
36
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL
37
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE
38
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL
39
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL
40
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL
41
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
42
+ import org.opencds.cqf.cql.engine.runtime.Boolean
43
+ import org.opencds.cqf.cql.engine.runtime.Code
44
+ import org.opencds.cqf.cql.engine.runtime.Concept
45
+ import org.opencds.cqf.cql.engine.runtime.DateTime
46
+ import org.opencds.cqf.cql.engine.runtime.Decimal
47
+ import org.opencds.cqf.cql.engine.runtime.Integer
48
+ import org.opencds.cqf.cql.engine.runtime.Interval
49
+ import org.opencds.cqf.cql.engine.runtime.List
50
+ import org.opencds.cqf.cql.engine.runtime.Long
51
+ import org.opencds.cqf.cql.engine.runtime.Quantity
52
+ import org.opencds.cqf.cql.engine.runtime.Ratio
53
+ import org.opencds.cqf.cql.engine.runtime.String
54
+ import org.opencds.cqf.cql.engine.runtime.Time
55
+ import org.opencds.cqf.cql.engine.runtime.Tuple
56
+ import org.opencds.cqf.cql.engine.runtime.Value
57
+ import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName
58
+ import org.opencds.cqf.cql.engine.runtime.dateTypeName
59
+ import org.opencds.cqf.cql.engine.runtime.quantityTypeName
60
+
61
+ internal class Dstu2FhirTypeConverter : BaseFhirTypeConverter() {
62
+ override fun toFhirId(value: String?): IIdType? {
63
+ if (value == null) {
64
+ return null
65
+ }
66
+
67
+ return IdType(value.value)
68
+ }
69
+
70
+ override fun toFhirBoolean(value: Boolean?): BooleanType? {
71
+ if (value == null) {
72
+ return null
73
+ }
74
+
75
+ return BooleanType(value.value)
76
+ }
77
+
78
+ override fun toFhirInteger(value: Integer?): IPrimitiveType<Int>? {
79
+ if (value == null) {
80
+ return null
81
+ }
82
+
83
+ return IntegerType(value.value)
84
+ }
85
+
86
+ override fun toFhirInteger64(value: Long?): IPrimitiveType<kotlin.Long> {
87
+ throw IllegalArgumentException("FHIR DSTU2 does not support Long/Integer64 values")
88
+ }
89
+
90
+ override fun toFhirDecimal(value: Decimal?): IPrimitiveType<BigDecimal>? {
91
+ if (value == null) {
92
+ return null
93
+ }
94
+
95
+ return DecimalType(value.value)
96
+ }
97
+
98
+ override fun toFhirDate(
99
+ value: org.opencds.cqf.cql.engine.runtime.Date?
100
+ ): IPrimitiveType<Date>? {
101
+ if (value == null) {
102
+ return null
103
+ }
104
+
105
+ return DateType(value.toStringInner())
106
+ }
107
+
108
+ override fun toFhirDateTime(value: DateTime?): IPrimitiveType<Date>? {
109
+ if (value == null) {
110
+ return null
111
+ }
112
+
113
+ val result = DateTimeType(value.toDateString())
114
+ result.precision = toFhirPrecision(value.precision!!)
115
+ return result
116
+ }
117
+
118
+ override fun toFhirTime(value: Time?): IPrimitiveType<kotlin.String>? {
119
+ if (value == null) {
120
+ return null
121
+ }
122
+
123
+ return TimeType(value.toStringInner())
124
+ }
125
+
126
+ override fun toFhirString(value: String?): IPrimitiveType<kotlin.String>? {
127
+ if (value == null) {
128
+ return null
129
+ }
130
+
131
+ return StringType(value.value)
132
+ }
133
+
134
+ override fun toFhirQuantity(value: Quantity?): ICompositeType? {
135
+ if (value == null) {
136
+ return null
137
+ }
138
+
139
+ val unit = value.unit
140
+ val system =
141
+ if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units"
142
+ else "http://unitsofmeasure.org"
143
+ val ucumUnit = toUcumUnit(unit)
144
+
145
+ return org.hl7.fhir.dstu2.model
146
+ .Quantity()
147
+ .setSystem(system)
148
+ .setCode(ucumUnit)
149
+ .setValue(value.value)
150
+ .setUnit(unit)
151
+ }
152
+
153
+ override fun toFhirRatio(value: Ratio?): ICompositeType? {
154
+ if (value == null) {
155
+ return null
156
+ }
157
+
158
+ return org.hl7.fhir.dstu2.model
159
+ .Ratio()
160
+ .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.dstu2.model.Quantity?)
161
+ .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.dstu2.model.Quantity?)
162
+ }
163
+
164
+ override fun toFhirCoding(value: Code?): IBaseCoding? {
165
+ if (value == null) {
166
+ return null
167
+ }
168
+
169
+ val coding = Coding()
170
+ coding.setSystem(value.system)
171
+ coding.setCode(value.code)
172
+ coding.setDisplay(value.display)
173
+ coding.setVersion(value.version)
174
+ return coding
175
+ }
176
+
177
+ override fun toFhirCodeableConcept(value: Concept?): ICompositeType? {
178
+ if (value == null) {
179
+ return null
180
+ }
181
+
182
+ val codeableConcept = CodeableConcept()
183
+ codeableConcept.setText(value.display)
184
+ if (value.codes != null) {
185
+ for (c in value.codes) {
186
+ codeableConcept.addCoding(toFhirCoding(c) as Coding?)
187
+ }
188
+ }
189
+
190
+ return codeableConcept
191
+ }
192
+
193
+ override fun toFhirPeriod(value: Interval?): ICompositeType? {
194
+ if (value == null) {
195
+ return null
196
+ }
197
+
198
+ val period = Period()
199
+ if (value.pointType == dateTimeTypeName) {
200
+ if (value.start != null) {
201
+ period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType?
202
+ }
203
+
204
+ if (value.end != null) {
205
+ period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType?
206
+ }
207
+
208
+ return period
209
+ } else if (value.pointType == dateTypeName) {
210
+ // TODO: This will construct DateTimeType values in FHIR with the system timezone id,
211
+ // not the
212
+ // timezoneoffset of the evaluation request..... this is a bug waiting to happen
213
+ if (value.start != null) {
214
+ period.setStart(
215
+ toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
216
+ )
217
+ }
218
+
219
+ if (value.end != null) {
220
+ period.setEnd(
221
+ toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
222
+ )
223
+ }
224
+
225
+ return period
226
+ }
227
+
228
+ throw IllegalArgumentException(
229
+ "FHIR Period can only be created from an Interval of Date or DateTime type"
230
+ )
231
+ }
232
+
233
+ override fun toFhirRange(value: Interval?): ICompositeType? {
234
+ if (value == null) {
235
+ return null
236
+ }
237
+
238
+ require(value.pointType == quantityTypeName) {
239
+ "FHIR Range can only be created from an Interval of Quantity type"
240
+ }
241
+
242
+ val range = Range()
243
+ val start = toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.dstu2.model.Quantity?
244
+ if (start != null) {
245
+ range.setLow(toSimpleQuantity(start))
246
+ }
247
+
248
+ val end = toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.dstu2.model.Quantity?
249
+ if (end != null) {
250
+ range.setHigh(toSimpleQuantity(end))
251
+ }
252
+
253
+ return range
254
+ }
255
+
256
+ private fun addElementToParameter(
257
+ param: Parameters.ParametersParameterComponent,
258
+ key: kotlin.String?,
259
+ value: Value?,
260
+ ) {
261
+ if (value == null) {
262
+ // Null value, add a single empty value with an extension indicating the reason
263
+ val dataAbsentValue: BooleanType =
264
+ emptyBooleanWithExtension(
265
+ DATA_ABSENT_REASON_EXT_URL,
266
+ CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE),
267
+ )
268
+ addPartWithNameAndValue(param, key, dataAbsentValue)
269
+ return
270
+ }
271
+
272
+ if (value !is List) {
273
+ // Single, non-null value
274
+ addPartWithNameAndValue(param, key, toFhirType(value)!!)
275
+ return
276
+ }
277
+
278
+ val iterable = value
279
+
280
+ if (!iterable.iterator().hasNext()) {
281
+ // Empty list
282
+ val emptyListValue: BooleanType =
283
+ emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true))
284
+ addPartWithNameAndValue(param, key, emptyListValue)
285
+ } else {
286
+ // Non-empty list, one part per value
287
+ val fhirTypes = this.toFhirTypes(iterable)
288
+ for (fhirType in fhirTypes) {
289
+ addPartWithNameAndValue(param, key, fhirType!!)
290
+ }
291
+ }
292
+ }
293
+
294
+ override fun toFhirTuple(value: Tuple?): IBase? {
295
+ if (value == null) {
296
+ return null
297
+ }
298
+
299
+ val parameters = Parameters()
300
+ val param = parameters.addParameter()
301
+
302
+ if (value.elements.isEmpty()) {
303
+ param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true)))
304
+ }
305
+
306
+ for (key in value.elements.keys) {
307
+ addElementToParameter(param, key, value.elements[key])
308
+ }
309
+
310
+ return param
311
+ }
312
+
313
+ override fun toCqlQuantity(value: ICompositeType?): Quantity? {
314
+ if (value == null) {
315
+ return null
316
+ }
317
+
318
+ require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" }
319
+
320
+ val quantity = value as org.hl7.fhir.dstu2.model.Quantity
321
+ require(!quantity.hasComparator()) {
322
+ "Cannot convert a FHIR Quantity with a comparator to a CQL quantity"
323
+ }
324
+ return Quantity()
325
+ .withUnit(toCqlCalendarUnit(quantity.getUnit()))
326
+ .withValue(quantity.getValue())
327
+ }
328
+
329
+ override fun toCqlRatio(value: ICompositeType?): Ratio? {
330
+ if (value == null) {
331
+ return null
332
+ }
333
+
334
+ require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" }
335
+
336
+ val ratio = value as org.hl7.fhir.dstu2.model.Ratio
337
+
338
+ return Ratio()
339
+ .withNumerator(toCqlQuantity(ratio.numerator))
340
+ .withDenominator(toCqlQuantity(ratio.denominator))
341
+ }
342
+
343
+ override fun toCqlAny(value: IBase?): Any? {
344
+ if (value == null) {
345
+ return null
346
+ }
347
+
348
+ throw NotImplementedException("Unable to convert to System.Any type")
349
+ }
350
+
351
+ override fun toCqlCode(value: IBaseCoding?): Code? {
352
+ if (value == null) {
353
+ return null
354
+ }
355
+
356
+ val coding = value as Coding
357
+
358
+ return Code()
359
+ .withSystem(coding.getSystem())
360
+ .withCode(coding.getCode())
361
+ .withVersion(coding.getVersion())
362
+ .withDisplay(coding.getDisplay())
363
+ }
364
+
365
+ override fun toCqlConcept(value: ICompositeType?): Concept? {
366
+ if (value == null) {
367
+ return null
368
+ }
369
+
370
+ require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" }
371
+
372
+ val codeableConcept = value as CodeableConcept
373
+
374
+ return Concept()
375
+ .withDisplay(codeableConcept.getText())
376
+ .withCodes(
377
+ codeableConcept
378
+ .getCoding()
379
+ .stream()
380
+ .map<Code?> { x: Coding? -> toCqlCode(x) }
381
+ .collect(Collectors.toList())
382
+ )
383
+ }
384
+
385
+ override fun toCqlInterval(value: ICompositeType?): Interval? {
386
+ if (value == null) {
387
+ return null
388
+ }
389
+
390
+ if (value.fhirType() == "Range") {
391
+ val range = value as Range
392
+ return Interval(
393
+ toCqlQuantity(range.getLow()),
394
+ true,
395
+ toCqlQuantity(range.getHigh()),
396
+ true,
397
+ )
398
+ } else if (value.fhirType() == "Period") {
399
+ val period = value as Period
400
+ return Interval(
401
+ toCqlTemporal(period.startElement),
402
+ true,
403
+ toCqlTemporal(period.endElement),
404
+ true,
405
+ )
406
+ } else {
407
+ throw IllegalArgumentException("value is not a FHIR Range or Period")
408
+ }
409
+ }
410
+
411
+ override fun toCqlDate(value: IPrimitiveType<Date>?): org.opencds.cqf.cql.engine.runtime.Date? {
412
+ if (value == null) {
413
+ return null
414
+ }
415
+
416
+ require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) {
417
+ "value is not a FHIR Date or DateTime"
418
+ }
419
+
420
+ val baseDateTime = value as BaseDateTimeType
421
+ when (baseDateTime.precision) {
422
+ TemporalPrecisionEnum.YEAR,
423
+ TemporalPrecisionEnum.DAY,
424
+ TemporalPrecisionEnum.MONTH ->
425
+ return toDate(toCalendar(baseDateTime)!!, baseDateTime.precision.calendarConstant)
426
+
427
+ TemporalPrecisionEnum.SECOND,
428
+ TemporalPrecisionEnum.MILLI,
429
+ TemporalPrecisionEnum.MINUTE ->
430
+ throw IllegalArgumentException("value has a precision higher than a CQL Date")
431
+
432
+ else -> throw IllegalArgumentException("value has a precision higher than a CQL Date")
433
+ }
434
+ }
435
+
436
+ override fun toCqlDateTime(value: IPrimitiveType<Date>?): DateTime? {
437
+ if (value == null) {
438
+ return null
439
+ }
440
+
441
+ if (value.fhirType() == "instant" || value.fhirType() == "dateTime") {
442
+ val baseDateTime = value as BaseDateTimeType
443
+ return toDateTime(toCalendar(baseDateTime)!!, baseDateTime.precision.calendarConstant)
444
+ } else {
445
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
446
+ }
447
+ }
448
+
449
+ override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? {
450
+ if (value == null) {
451
+ return null
452
+ }
453
+
454
+ if (
455
+ value.fhirType() == "instant" ||
456
+ value.fhirType() == "dateTime" ||
457
+ value.fhirType() == "date"
458
+ ) {
459
+ val baseDateTime = value as BaseDateTimeType
460
+ when (baseDateTime.precision) {
461
+ TemporalPrecisionEnum.YEAR,
462
+ TemporalPrecisionEnum.DAY,
463
+ TemporalPrecisionEnum.MONTH ->
464
+ return toDate(
465
+ toCalendar(baseDateTime)!!,
466
+ baseDateTime.precision.calendarConstant,
467
+ )
468
+
469
+ TemporalPrecisionEnum.SECOND,
470
+ TemporalPrecisionEnum.MILLI,
471
+ TemporalPrecisionEnum.MINUTE ->
472
+ return toDateTime(
473
+ toCalendar(baseDateTime)!!,
474
+ baseDateTime.precision.calendarConstant,
475
+ )
476
+
477
+ else ->
478
+ return toDateTime(
479
+ toCalendar(baseDateTime)!!,
480
+ baseDateTime.precision.calendarConstant,
481
+ )
482
+ }
483
+ } else {
484
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
485
+ }
486
+ }
487
+
488
+ override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? {
489
+ if (exception == null) {
490
+ return null
491
+ }
492
+
493
+ val outcome = OperationOutcome()
494
+ outcome
495
+ .addIssue()
496
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
497
+ .setCode(OperationOutcome.IssueType.EXCEPTION)
498
+ .setDiagnostics(exception.message)
499
+ .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception)))
500
+
501
+ return outcome
502
+ }
503
+
504
+ override fun toCqlText(value: Value?): IBaseDatatype? {
505
+ if (value == null) {
506
+ return null
507
+ }
508
+
509
+ val s = ToStringEvaluator.toString(value)?.value
510
+ val text = StringType(s)
511
+ text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true))
512
+ return text
513
+ }
514
+
515
+ // The built-in "toCalendar" function is bugged.
516
+ // It does not correctly populate the Calendar
517
+ private fun toCalendar(dateTimeType: BaseDateTimeType): Calendar? {
518
+ if (dateTimeType.value == null) {
519
+ return null
520
+ }
521
+ val cal =
522
+ if (dateTimeType.timeZone != null) {
523
+ GregorianCalendar(dateTimeType.timeZone)
524
+ } else {
525
+ GregorianCalendar()
526
+ }
527
+ cal.setTime(dateTimeType.value)
528
+
529
+ return cal
530
+ }
531
+
532
+ // The built-in "castToSimpleQuantity" automatically creates
533
+ // missing elements, which causes comparisons to fail
534
+ private fun toSimpleQuantity(quantity: org.hl7.fhir.dstu2.model.Quantity): SimpleQuantity {
535
+ val simple = SimpleQuantity()
536
+ simple.setValue(quantity.getValue())
537
+ simple.setCode(quantity.getCode())
538
+ simple.setSystem(quantity.getSystem())
539
+ simple.setComparator(quantity.getComparator())
540
+ return simple
541
+ }
542
+
543
+ companion object {
544
+ private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType {
545
+ val result = BooleanType(null as kotlin.String?)
546
+ result.addExtension().setUrl(url).setValue(value)
547
+ return result
548
+ }
549
+
550
+ private fun addPartWithNameAndValue(
551
+ param: Parameters.ParametersParameterComponent,
552
+ key: kotlin.String?,
553
+ value: Any,
554
+ ) {
555
+ if (value is Parameters.ParametersParameterComponent) {
556
+ value.setName(key)
557
+ param.addPart(value)
558
+ } else {
559
+ val part = param.addPart().setName(key)
560
+ when (value) {
561
+ is Resource -> {
562
+ part.setResource(value)
563
+ }
564
+
565
+ is Type -> {
566
+ part.setValue(value)
567
+ }
568
+
569
+ else -> {
570
+ throw IllegalArgumentException(
571
+ "Unsupported FHIR type: " + value.javaClass.getName()
572
+ )
573
+ }
574
+ }
575
+ }
576
+ }
577
+ }
578
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu3FhirTypeConverter.kt ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
4
+ import java.math.BigDecimal
5
+ import java.time.format.DateTimeFormatter
6
+ import java.util.*
7
+ import java.util.stream.Collectors
8
+ import org.apache.commons.lang3.NotImplementedException
9
+ import org.hl7.fhir.dstu3.model.BaseDateTimeType
10
+ import org.hl7.fhir.dstu3.model.BooleanType
11
+ import org.hl7.fhir.dstu3.model.CodeType
12
+ import org.hl7.fhir.dstu3.model.CodeableConcept
13
+ import org.hl7.fhir.dstu3.model.Coding
14
+ import org.hl7.fhir.dstu3.model.DateTimeType
15
+ import org.hl7.fhir.dstu3.model.DateType
16
+ import org.hl7.fhir.dstu3.model.DecimalType
17
+ import org.hl7.fhir.dstu3.model.IdType
18
+ import org.hl7.fhir.dstu3.model.IntegerType
19
+ import org.hl7.fhir.dstu3.model.OperationOutcome
20
+ import org.hl7.fhir.dstu3.model.Parameters
21
+ import org.hl7.fhir.dstu3.model.Period
22
+ import org.hl7.fhir.dstu3.model.Range
23
+ import org.hl7.fhir.dstu3.model.Resource
24
+ import org.hl7.fhir.dstu3.model.StringType
25
+ import org.hl7.fhir.dstu3.model.TimeType
26
+ import org.hl7.fhir.dstu3.model.Type
27
+ import org.hl7.fhir.instance.model.api.IBase
28
+ import org.hl7.fhir.instance.model.api.IBaseCoding
29
+ import org.hl7.fhir.instance.model.api.IBaseDatatype
30
+ import org.hl7.fhir.instance.model.api.IBaseOperationOutcome
31
+ import org.hl7.fhir.instance.model.api.ICompositeType
32
+ import org.hl7.fhir.instance.model.api.IIdType
33
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
34
+ import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator
35
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL
36
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL
37
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE
38
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL
39
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL
40
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL
41
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
42
+ import org.opencds.cqf.cql.engine.runtime.Boolean
43
+ import org.opencds.cqf.cql.engine.runtime.Code
44
+ import org.opencds.cqf.cql.engine.runtime.Concept
45
+ import org.opencds.cqf.cql.engine.runtime.DateTime
46
+ import org.opencds.cqf.cql.engine.runtime.Decimal
47
+ import org.opencds.cqf.cql.engine.runtime.Integer
48
+ import org.opencds.cqf.cql.engine.runtime.Interval
49
+ import org.opencds.cqf.cql.engine.runtime.List
50
+ import org.opencds.cqf.cql.engine.runtime.Long
51
+ import org.opencds.cqf.cql.engine.runtime.Quantity
52
+ import org.opencds.cqf.cql.engine.runtime.Ratio
53
+ import org.opencds.cqf.cql.engine.runtime.String
54
+ import org.opencds.cqf.cql.engine.runtime.Time
55
+ import org.opencds.cqf.cql.engine.runtime.Tuple
56
+ import org.opencds.cqf.cql.engine.runtime.Value
57
+ import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName
58
+ import org.opencds.cqf.cql.engine.runtime.dateTypeName
59
+ import org.opencds.cqf.cql.engine.runtime.quantityTypeName
60
+
61
+ internal class Dstu3FhirTypeConverter : BaseFhirTypeConverter() {
62
+ override fun toFhirId(value: String?): IIdType? {
63
+ if (value == null) {
64
+ return null
65
+ }
66
+
67
+ return IdType(value.value)
68
+ }
69
+
70
+ override fun toFhirBoolean(value: Boolean?): BooleanType? {
71
+ if (value == null) {
72
+ return null
73
+ }
74
+
75
+ return BooleanType(value.value)
76
+ }
77
+
78
+ override fun toFhirInteger(value: Integer?): IPrimitiveType<Int>? {
79
+ if (value == null) {
80
+ return null
81
+ }
82
+
83
+ return IntegerType(value.value)
84
+ }
85
+
86
+ override fun toFhirInteger64(value: Long?): IPrimitiveType<kotlin.Long> {
87
+ throw IllegalArgumentException("FHIR DSTU3 does not support Long/Integer64 values")
88
+ }
89
+
90
+ override fun toFhirDecimal(value: Decimal?): IPrimitiveType<BigDecimal>? {
91
+ if (value == null) {
92
+ return null
93
+ }
94
+
95
+ return DecimalType(value.value)
96
+ }
97
+
98
+ override fun toFhirDate(
99
+ value: org.opencds.cqf.cql.engine.runtime.Date?
100
+ ): IPrimitiveType<Date>? {
101
+ if (value == null) {
102
+ return null
103
+ }
104
+
105
+ return DateType(value.toStringInner())
106
+ }
107
+
108
+ override fun toFhirDateTime(value: DateTime?): IPrimitiveType<Date>? {
109
+ if (value == null) {
110
+ return null
111
+ }
112
+
113
+ val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
114
+ result.precision = toFhirPrecision(value.precision!!)
115
+ return result
116
+ }
117
+
118
+ override fun toFhirTime(value: Time?): IPrimitiveType<kotlin.String>? {
119
+ if (value == null) {
120
+ return null
121
+ }
122
+
123
+ return TimeType(value.toStringInner())
124
+ }
125
+
126
+ override fun toFhirString(value: String?): IPrimitiveType<kotlin.String>? {
127
+ if (value == null) {
128
+ return null
129
+ }
130
+
131
+ return StringType(value.value)
132
+ }
133
+
134
+ override fun toFhirQuantity(value: Quantity?): ICompositeType? {
135
+ if (value == null) {
136
+ return null
137
+ }
138
+
139
+ val unit = value.unit
140
+ val system =
141
+ if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units"
142
+ else "http://unitsofmeasure.org"
143
+ val ucumUnit = toUcumUnit(unit)
144
+
145
+ return org.hl7.fhir.dstu3.model
146
+ .Quantity()
147
+ .setSystem(system)
148
+ .setCode(ucumUnit)
149
+ .setValue(value.value)
150
+ .setUnit(unit)
151
+ }
152
+
153
+ override fun toFhirRatio(value: Ratio?): ICompositeType? {
154
+ if (value == null) {
155
+ return null
156
+ }
157
+
158
+ return org.hl7.fhir.dstu3.model
159
+ .Ratio()
160
+ .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.dstu3.model.Quantity?)
161
+ .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.dstu3.model.Quantity?)
162
+ }
163
+
164
+ override fun toFhirCoding(value: Code?): IBaseCoding? {
165
+ if (value == null) {
166
+ return null
167
+ }
168
+
169
+ val coding = Coding()
170
+ coding.setSystem(value.system)
171
+ coding.setCode(value.code)
172
+ coding.setDisplay(value.display)
173
+ coding.setVersion(value.version)
174
+ return coding
175
+ }
176
+
177
+ override fun toFhirCodeableConcept(value: Concept?): ICompositeType? {
178
+ if (value == null) {
179
+ return null
180
+ }
181
+
182
+ val codeableConcept = CodeableConcept()
183
+ codeableConcept.setText(value.display)
184
+ if (value.codes != null) {
185
+ for (c in value.codes) {
186
+ codeableConcept.addCoding(toFhirCoding(c) as Coding?)
187
+ }
188
+ }
189
+
190
+ return codeableConcept
191
+ }
192
+
193
+ override fun toFhirPeriod(value: Interval?): ICompositeType? {
194
+ if (value == null) {
195
+ return null
196
+ }
197
+
198
+ val period = Period()
199
+ if (value.pointType == dateTimeTypeName) {
200
+ if (value.start != null) {
201
+ period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType?
202
+ }
203
+
204
+ if (value.end != null) {
205
+ period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType?
206
+ }
207
+
208
+ return period
209
+ } else if (value.pointType == dateTypeName) {
210
+ // TODO: This will construct DateTimeType values in FHIR with the system timezone id,
211
+ // not the
212
+ // timezoneoffset of the evaluation request..... this is a bug waiting to happen
213
+ if (value.start != null) {
214
+ period.setStart(
215
+ toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
216
+ )
217
+ }
218
+
219
+ if (value.end != null) {
220
+ period.setEnd(
221
+ toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
222
+ )
223
+ }
224
+
225
+ return period
226
+ }
227
+
228
+ throw IllegalArgumentException(
229
+ "FHIR Period can only be created from an Interval of Date or DateTime type"
230
+ )
231
+ }
232
+
233
+ override fun toFhirRange(value: Interval?): ICompositeType? {
234
+ if (value == null) {
235
+ return null
236
+ }
237
+
238
+ require(value.pointType == quantityTypeName) {
239
+ "FHIR Range can only be created from an Interval of Quantity type"
240
+ }
241
+
242
+ val range = Range()
243
+ val start = toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.dstu3.model.Quantity?
244
+ if (start != null) {
245
+ range.setLow(start.castToSimpleQuantity(start))
246
+ }
247
+
248
+ val end = toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.dstu3.model.Quantity?
249
+ if (end != null) {
250
+ range.setHigh(end.castToSimpleQuantity(end))
251
+ }
252
+
253
+ return range
254
+ }
255
+
256
+ private fun addElementToParameter(
257
+ param: Parameters.ParametersParameterComponent,
258
+ key: kotlin.String?,
259
+ value: Value?,
260
+ ) {
261
+ if (value == null) {
262
+ // Null value, add a single empty value with an extension indicating the reason
263
+ val dataAbsentValue: BooleanType =
264
+ emptyBooleanWithExtension(
265
+ DATA_ABSENT_REASON_EXT_URL,
266
+ CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE),
267
+ )
268
+ addPartWithNameAndValue(param, key, dataAbsentValue)
269
+ return
270
+ }
271
+
272
+ if (value !is List) {
273
+ // Single, non-null value
274
+ addPartWithNameAndValue(param, key, toFhirType(value)!!)
275
+ return
276
+ }
277
+
278
+ val iterable = value
279
+
280
+ if (!iterable.iterator().hasNext()) {
281
+ // Empty list
282
+ val emptyListValue: BooleanType =
283
+ emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true))
284
+ addPartWithNameAndValue(param, key, emptyListValue)
285
+ } else {
286
+ // Non-empty list, one part per value
287
+ val fhirTypes = this.toFhirTypes(iterable)
288
+ for (fhirType in fhirTypes) {
289
+ addPartWithNameAndValue(param, key, fhirType!!)
290
+ }
291
+ }
292
+ }
293
+
294
+ override fun toFhirTuple(value: Tuple?): IBase? {
295
+ if (value == null) {
296
+ return null
297
+ }
298
+
299
+ val parameters = Parameters()
300
+ val param = parameters.addParameter()
301
+
302
+ if (value.elements.isEmpty()) {
303
+ param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true)))
304
+ }
305
+
306
+ for (key in value.elements.keys) {
307
+ addElementToParameter(param, key, value.elements[key])
308
+ }
309
+
310
+ return param
311
+ }
312
+
313
+ override fun toCqlQuantity(value: ICompositeType?): Quantity? {
314
+ if (value == null) {
315
+ return null
316
+ }
317
+
318
+ require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" }
319
+
320
+ val quantity = value as org.hl7.fhir.dstu3.model.Quantity
321
+ require(!quantity.hasComparator()) {
322
+ "Cannot convert a FHIR Quantity with a comparator to a CQL quantity"
323
+ }
324
+ return Quantity()
325
+ .withUnit(toCqlCalendarUnit(quantity.getUnit()))
326
+ .withValue(quantity.getValue())
327
+ }
328
+
329
+ override fun toCqlRatio(value: ICompositeType?): Ratio? {
330
+ if (value == null) {
331
+ return null
332
+ }
333
+
334
+ require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" }
335
+
336
+ val ratio = value as org.hl7.fhir.dstu3.model.Ratio
337
+
338
+ return Ratio()
339
+ .withNumerator(toCqlQuantity(ratio.numerator))
340
+ .withDenominator(toCqlQuantity(ratio.denominator))
341
+ }
342
+
343
+ override fun toCqlAny(value: IBase?): Any? {
344
+ if (value == null) {
345
+ return null
346
+ }
347
+
348
+ throw NotImplementedException("Unable to convert to System.Any type")
349
+ }
350
+
351
+ override fun toCqlCode(value: IBaseCoding?): Code? {
352
+ if (value == null) {
353
+ return null
354
+ }
355
+
356
+ val coding = value as Coding
357
+
358
+ return Code()
359
+ .withSystem(coding.getSystem())
360
+ .withCode(coding.getCode())
361
+ .withVersion(coding.getVersion())
362
+ .withDisplay(coding.getDisplay())
363
+ }
364
+
365
+ override fun toCqlConcept(value: ICompositeType?): Concept? {
366
+ if (value == null) {
367
+ return null
368
+ }
369
+
370
+ require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" }
371
+
372
+ val codeableConcept = value as CodeableConcept
373
+
374
+ return Concept()
375
+ .withDisplay(codeableConcept.getText())
376
+ .withCodes(
377
+ codeableConcept
378
+ .getCoding()
379
+ .stream()
380
+ .map<Code?> { x: Coding? -> toCqlCode(x) }
381
+ .collect(Collectors.toList())
382
+ )
383
+ }
384
+
385
+ override fun toCqlInterval(value: ICompositeType?): Interval? {
386
+ if (value == null) {
387
+ return null
388
+ }
389
+
390
+ if (value.fhirType() == "Range") {
391
+ val range = value as Range
392
+ return Interval(
393
+ toCqlQuantity(range.getLow()),
394
+ true,
395
+ toCqlQuantity(range.getHigh()),
396
+ true,
397
+ )
398
+ } else if (value.fhirType() == "Period") {
399
+ val period = value as Period
400
+ return Interval(
401
+ toCqlTemporal(period.startElement),
402
+ true,
403
+ toCqlTemporal(period.endElement),
404
+ true,
405
+ )
406
+ } else {
407
+ throw IllegalArgumentException("value is not a FHIR Range or Period")
408
+ }
409
+ }
410
+
411
+ override fun toCqlDate(value: IPrimitiveType<Date>?): org.opencds.cqf.cql.engine.runtime.Date? {
412
+ if (value == null) {
413
+ return null
414
+ }
415
+
416
+ require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) {
417
+ "value is not a FHIR Date or DateTime"
418
+ }
419
+
420
+ val baseDateTime = value as BaseDateTimeType
421
+ when (baseDateTime.precision) {
422
+ TemporalPrecisionEnum.YEAR,
423
+ TemporalPrecisionEnum.DAY,
424
+ TemporalPrecisionEnum.MONTH ->
425
+ return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
426
+
427
+ TemporalPrecisionEnum.SECOND,
428
+ TemporalPrecisionEnum.MILLI,
429
+ TemporalPrecisionEnum.MINUTE ->
430
+ throw IllegalArgumentException("value has a precision higher than a CQL Date")
431
+
432
+ else -> throw IllegalArgumentException("value has a precision higher than a CQL Date")
433
+ }
434
+ }
435
+
436
+ override fun toCqlDateTime(value: IPrimitiveType<Date>?): DateTime? {
437
+ if (value == null) {
438
+ return null
439
+ }
440
+
441
+ if (value.fhirType() == "instant" || value.fhirType() == "dateTime") {
442
+ val baseDateTime = value as BaseDateTimeType
443
+ return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
444
+ } else {
445
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
446
+ }
447
+ }
448
+
449
+ override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? {
450
+ if (value == null) {
451
+ return null
452
+ }
453
+
454
+ if (
455
+ value.fhirType() == "instant" ||
456
+ value.fhirType() == "dateTime" ||
457
+ value.fhirType() == "date"
458
+ ) {
459
+ val baseDateTime = value as BaseDateTimeType
460
+ when (baseDateTime.precision) {
461
+ TemporalPrecisionEnum.YEAR,
462
+ TemporalPrecisionEnum.DAY,
463
+ TemporalPrecisionEnum.MONTH ->
464
+ return toDate(
465
+ baseDateTime.valueAsCalendar,
466
+ baseDateTime.precision.calendarConstant,
467
+ )
468
+
469
+ TemporalPrecisionEnum.SECOND,
470
+ TemporalPrecisionEnum.MILLI,
471
+ TemporalPrecisionEnum.MINUTE ->
472
+ return toDateTime(
473
+ baseDateTime.valueAsCalendar,
474
+ baseDateTime.precision.calendarConstant,
475
+ )
476
+
477
+ else ->
478
+ return toDateTime(
479
+ baseDateTime.valueAsCalendar,
480
+ baseDateTime.precision.calendarConstant,
481
+ )
482
+ }
483
+ } else {
484
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
485
+ }
486
+ }
487
+
488
+ override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? {
489
+ if (exception == null) {
490
+ return null
491
+ }
492
+
493
+ val outcome = OperationOutcome()
494
+ outcome
495
+ .addIssue()
496
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
497
+ .setCode(OperationOutcome.IssueType.EXCEPTION)
498
+ .setDiagnostics(exception.message)
499
+ .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception)))
500
+
501
+ return outcome
502
+ }
503
+
504
+ override fun toCqlText(value: Value?): IBaseDatatype? {
505
+ if (value == null) {
506
+ return null
507
+ }
508
+
509
+ val s = ToStringEvaluator.toString(value)?.value
510
+ val text = StringType(s)
511
+ text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true))
512
+ return text
513
+ }
514
+
515
+ companion object {
516
+ private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType {
517
+ val result = BooleanType(null as kotlin.String?)
518
+ result.addExtension().setUrl(url).setValue(value)
519
+ return result
520
+ }
521
+
522
+ private fun addPartWithNameAndValue(
523
+ param: Parameters.ParametersParameterComponent,
524
+ key: kotlin.String?,
525
+ value: Any,
526
+ ) {
527
+ if (value is Parameters.ParametersParameterComponent) {
528
+ value.setName(key)
529
+ param.addPart(value)
530
+ } else {
531
+ val part = param.addPart().setName(key)
532
+ when (value) {
533
+ is Resource -> {
534
+ part.setResource(value)
535
+ }
536
+
537
+ is Type -> {
538
+ part.setValue(value)
539
+ }
540
+
541
+ else -> {
542
+ throw IllegalArgumentException(
543
+ "Unsupported FHIR type: " + value.javaClass.getName()
544
+ )
545
+ }
546
+ }
547
+ }
548
+ }
549
+ }
550
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverter.kt ADDED
@@ -0,0 +1,444 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import java.math.BigDecimal
4
+ import java.util.*
5
+ import org.hl7.fhir.instance.model.api.IBase
6
+ import org.hl7.fhir.instance.model.api.IBaseCoding
7
+ import org.hl7.fhir.instance.model.api.IBaseDatatype
8
+ import org.hl7.fhir.instance.model.api.IBaseOperationOutcome
9
+ import org.hl7.fhir.instance.model.api.ICompositeType
10
+ import org.hl7.fhir.instance.model.api.IIdType
11
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
12
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
13
+ import org.opencds.cqf.cql.engine.runtime.Boolean
14
+ import org.opencds.cqf.cql.engine.runtime.Code
15
+ import org.opencds.cqf.cql.engine.runtime.Concept
16
+ import org.opencds.cqf.cql.engine.runtime.DateTime
17
+ import org.opencds.cqf.cql.engine.runtime.Decimal
18
+ import org.opencds.cqf.cql.engine.runtime.Integer
19
+ import org.opencds.cqf.cql.engine.runtime.Interval
20
+ import org.opencds.cqf.cql.engine.runtime.List
21
+ import org.opencds.cqf.cql.engine.runtime.Long
22
+ import org.opencds.cqf.cql.engine.runtime.Quantity
23
+ import org.opencds.cqf.cql.engine.runtime.Ratio
24
+ import org.opencds.cqf.cql.engine.runtime.String
25
+ import org.opencds.cqf.cql.engine.runtime.Time
26
+ import org.opencds.cqf.cql.engine.runtime.Tuple
27
+ import org.opencds.cqf.cql.engine.runtime.Value
28
+
29
+ /**
30
+ * Provides functions for converting from CQL-to-FHIR and vice versa. The return types on the
31
+ * functions represent the most derived common type or interface across all FHIR versions. The
32
+ * implementations of this interface are expected to return the appropriate version specific
33
+ * structure for a given conversion (e.g. the interface for toFhirBoolean is defined as
34
+ * IPrimitiveType&lt;Boolean&gt; but it will return n dstu3.model.BooleanType or
35
+ * r4.model.BooleanType and so on).
36
+ */
37
+ interface FhirTypeConverter {
38
+ // CQL-to-FHIR conversions
39
+ /**
40
+ * Tests if an Object is a FHIR structure
41
+ *
42
+ * @param value the value to test
43
+ * @return true if value is a FHIR structure, false otherwise
44
+ * @throws NullPointerException if value is null
45
+ */
46
+ fun isFhirType(value: Any): kotlin.Boolean
47
+
48
+ /**
49
+ * Converts an Object to a FHIR structure.
50
+ *
51
+ * @param value the value to convert
52
+ * @return a FHIR structure
53
+ * @throws IllegalArgumentException is value is an Iterable
54
+ */
55
+ fun toFhirType(value: Value?): IBase?
56
+
57
+ /**
58
+ * Converts an iterable of Objects to FHIR structures. Preserves ordering, nulls, and sublist
59
+ * hierarchy
60
+ *
61
+ * @param values an Iterable containing CQL structures, nulls, or sublists
62
+ * @return n List containing FHIR types, nulls, and sublists
63
+ */
64
+ fun toFhirTypes(values: List): MutableList<Any?>?
65
+
66
+ /**
67
+ * Converts an Object to the equivalent CQL representation. This is used for arbitrary types
68
+ * that do not have well-defined FHIR mappings, such as CQL Integer Intervals.
69
+ *
70
+ * The default implementation should use the CQL ToString operator and embed add the cqf-cqlText
71
+ * extension to the FHIR structure.
72
+ *
73
+ * @param value the value to convert
74
+ * @return a FHIR String
75
+ * @return
76
+ */
77
+ fun toCqlText(value: Value?): IBaseDatatype?
78
+
79
+ /**
80
+ * Converts an Exception to a FHIR OperationOutcome.
81
+ *
82
+ * The default implementation should create an OperationOutcome with an issue of type
83
+ * "exception" and severity "error", and include the exception message and stack trace in the
84
+ * details.
85
+ *
86
+ * @param exception
87
+ * @return a FHIR OperationOutcome
88
+ */
89
+ fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome?
90
+
91
+ /**
92
+ * Converts a String to a FHIR Id
93
+ *
94
+ * @param value the value to convert
95
+ * @return a FHIR Id
96
+ */
97
+ fun toFhirId(value: String?): IIdType?
98
+
99
+ /**
100
+ * Converts a Boolean to a FHIR Boolean
101
+ *
102
+ * @param value the value to convert
103
+ * @return a FHIR Boolean
104
+ */
105
+ fun toFhirBoolean(value: Boolean?): IPrimitiveType<kotlin.Boolean>?
106
+
107
+ /**
108
+ * Converts an Integer to a FHIR Integer
109
+ *
110
+ * @param value the value to convert
111
+ * @return a FHIR Integer
112
+ */
113
+ fun toFhirInteger(value: Integer?): IPrimitiveType<Int>?
114
+
115
+ /**
116
+ * Converts a Long to a FHIR Integer64
117
+ *
118
+ * @param value the value to convert
119
+ * @return a FHIR Integer64
120
+ */
121
+ fun toFhirInteger64(value: Long?): IPrimitiveType<kotlin.Long>?
122
+
123
+ /**
124
+ * Converts a BigDecimal to a FHIR Decimal
125
+ *
126
+ * @param value the value to convert
127
+ * @return a FHIR Decimal
128
+ */
129
+ fun toFhirDecimal(value: Decimal?): IPrimitiveType<BigDecimal>?
130
+
131
+ /**
132
+ * Converts a CQL Date to a FHIR Date
133
+ *
134
+ * @param value the value to convert
135
+ * @return a FHIR Date
136
+ */
137
+ fun toFhirDate(value: org.opencds.cqf.cql.engine.runtime.Date?): IPrimitiveType<Date>?
138
+
139
+ /**
140
+ * Converts a CQL DateTime to a FHIR DateTime
141
+ *
142
+ * @param value the value to convert
143
+ * @return a FHIR DateTime
144
+ */
145
+ fun toFhirDateTime(value: DateTime?): IPrimitiveType<Date>?
146
+
147
+ /**
148
+ * Converts a CQL Time to a FHIR Time
149
+ *
150
+ * @param value the value to convert
151
+ * @return a FHIR Time
152
+ */
153
+ fun toFhirTime(value: Time?): IPrimitiveType<kotlin.String>?
154
+
155
+ /**
156
+ * Converts a String to a FHIR String
157
+ *
158
+ * @param value the value to convert
159
+ * @return a FHIR String
160
+ */
161
+ fun toFhirString(value: String?): IPrimitiveType<kotlin.String>?
162
+
163
+ /**
164
+ * Converts a CQL Quantity to a FHIR Quantity
165
+ *
166
+ * @param value the value to convert
167
+ * @return a FHIR Quantity
168
+ */
169
+ fun toFhirQuantity(value: Quantity?): ICompositeType?
170
+
171
+ /**
172
+ * Determines whether the given string is a CQL calendar unit
173
+ *
174
+ * @param unit
175
+ * @return true if the given unit is a CQL calendar unit
176
+ */
177
+ fun isCqlCalendarUnit(unit: kotlin.String?): kotlin.Boolean
178
+
179
+ /**
180
+ * Converts the given CQL unit to a UCUM definite-time duration unit according to the table and
181
+ * process defined in the CQL specification: https://cql.hl7.org/02-authorsguide.html#quantities
182
+ *
183
+ * @param unit
184
+ * @return An equivalent UCUM unit for the given CQL calendar duration unit, if the input is a
185
+ * CQL calendar duration unit, otherwise returns the input unit.
186
+ */
187
+ fun toUcumUnit(unit: kotlin.String?): kotlin.String?
188
+
189
+ /**
190
+ * Converts an Ucum unit to the equivalent CQL unit according to the table defined in the CQL
191
+ * specification: https://cql.hl7.org/02-authorsguide.html#quantities
192
+ *
193
+ * @param unit
194
+ * @return A CQL calendar unit if the input unit is an Ucum definite-duration unit, otherwise,
195
+ * the input unit
196
+ */
197
+ fun toCqlCalendarUnit(unit: kotlin.String?): kotlin.String?
198
+
199
+ /**
200
+ * Converts a CQL Ratio to a FHIR Ratio
201
+ *
202
+ * @param value the value to convert
203
+ * @return a FHIR Ratio
204
+ */
205
+ fun toFhirRatio(value: Ratio?): ICompositeType?
206
+
207
+ /**
208
+ * Converts a CQL Code to a FHIR Coding
209
+ *
210
+ * @param value the value to convert
211
+ * @return a FHIR Coding
212
+ */
213
+ fun toFhirCoding(value: Code?): IBaseCoding?
214
+
215
+ /**
216
+ * Converts a CQL Concept to a FHIR CodeableConcept
217
+ *
218
+ * @param value the value to convert
219
+ * @return a FHIR CodeableConcept
220
+ */
221
+ fun toFhirCodeableConcept(value: Concept?): ICompositeType?
222
+
223
+ /**
224
+ * Converts a CQL Interval to a FHIR Period
225
+ *
226
+ * @param value a Date or DateTime Interval
227
+ * @return a FHIR Period
228
+ */
229
+ fun toFhirPeriod(value: Interval?): ICompositeType?
230
+
231
+ /**
232
+ * Converts a CQL Interval to a FHIR Range
233
+ *
234
+ * @param value a Quantity Interval
235
+ * @return a FHIR Range
236
+ */
237
+ fun toFhirRange(value: Interval?): ICompositeType?
238
+
239
+ /**
240
+ * Converts a CQL Interval to FHIR Range or Period
241
+ *
242
+ * @param value a Quantity, Date, or DateTime interval
243
+ * @return A FHIR Range or Period
244
+ */
245
+ fun toFhirInterval(value: Interval?): IBase?
246
+
247
+ /**
248
+ * Converts a CQL Tuple to a FHIR Structure
249
+ *
250
+ * @param value the value to convert
251
+ * @return a FHIR Structure
252
+ */
253
+ fun toFhirTuple(value: Tuple?): IBase?
254
+
255
+ // FHIR-to-CQL conversions
256
+ /**
257
+ * Tests if an Object is a CQL type
258
+ *
259
+ * @param value the value to convert
260
+ * @return true if value is a CQL type, false otherwise
261
+ * @throws NullPointerException if value is null
262
+ */
263
+ fun isCqlType(value: Any): kotlin.Boolean
264
+
265
+ /**
266
+ * Converts an Object to a CQL type.
267
+ *
268
+ * @param value the value to convert a FHIR structure
269
+ * @return a CQL type
270
+ * @throws IllegalArgumentException is value is an Iterable
271
+ */
272
+ fun toCqlType(value: Any?): Any?
273
+
274
+ /**
275
+ * Converts an iterable of Objects to CQL types. Preserves ordering, nulls, and sublist
276
+ * hierarchy
277
+ *
278
+ * @param values the values to convert an Iterable containing FHIR structures, nulls, or
279
+ * sublists
280
+ * @return an Iterable containing CQL types, nulls, and sublists
281
+ */
282
+ fun toCqlTypes(values: Iterable<*>): Iterable<Any?>?
283
+
284
+ /**
285
+ * Converts a FHIR Id to a CQL String
286
+ *
287
+ * @param value the value to convert
288
+ * @return a String
289
+ */
290
+ fun toCqlId(value: IIdType?): String?
291
+
292
+ /**
293
+ * Converts a FHIR Boolean to a CQL Boolean
294
+ *
295
+ * @param value the value to convert
296
+ * @return a Boolean
297
+ */
298
+ fun toCqlBoolean(value: IPrimitiveType<kotlin.Boolean>?): Boolean?
299
+
300
+ /**
301
+ * Converts a FHIR Integer to a CQL Integer
302
+ *
303
+ * @param value the value to convert
304
+ * @return an Integer
305
+ */
306
+ fun toCqlInteger(value: IPrimitiveType<Int>?): Integer?
307
+
308
+ /**
309
+ * Converts a FHIR Integer64 to a CQL Long
310
+ *
311
+ * @param value the value to convert
312
+ * @return a Long
313
+ */
314
+ fun toCqlLong(value: IPrimitiveType<kotlin.Long>?): Long?
315
+
316
+ /**
317
+ * Converts a FHIR Decimal to a CQL Decimal
318
+ *
319
+ * @param value the value to convert
320
+ * @return a BigDecimal
321
+ */
322
+ fun toCqlDecimal(value: IPrimitiveType<BigDecimal>?): Decimal?
323
+
324
+ /**
325
+ * Converts a FHIR Date to a CQL Date
326
+ *
327
+ * @param value the value to convert
328
+ * @return a CQL Date
329
+ * @throws IllegalArgumentException if value is not a Date
330
+ */
331
+ fun toCqlDate(value: IPrimitiveType<Date>?): org.opencds.cqf.cql.engine.runtime.Date?
332
+
333
+ /**
334
+ * Converts a FHIR DateTime to a CQL DateTime
335
+ *
336
+ * @param value the value to convert
337
+ * @return a CQL DateTime
338
+ * @throws IllegalArgumentException if value is not a DateTime
339
+ */
340
+ fun toCqlDateTime(value: IPrimitiveType<Date>?): DateTime?
341
+
342
+ /**
343
+ * Converts a FHIR DateTime, Date, or Instance to a CQL BaseTemporal
344
+ *
345
+ * @param value the value to convert
346
+ * @return a CQL BaseTemporal
347
+ * @throws IllegalArgumentException if value is not a DateTime, Date, or Instant
348
+ */
349
+ fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal?
350
+
351
+ /**
352
+ * Converts a FHIR Time to a CQL Time
353
+ *
354
+ * @param value the value to convert
355
+ * @return a CQL Time
356
+ * @throws IllegalArgumentException if value is not a Time
357
+ */
358
+ fun toCqlTime(value: IPrimitiveType<kotlin.String>?): Time?
359
+
360
+ /**
361
+ * Converts a FHIR String to a CQL String
362
+ *
363
+ * @param value the value to convert
364
+ * @return a String
365
+ */
366
+ fun toCqlString(value: IPrimitiveType<kotlin.String>?): String?
367
+
368
+ /**
369
+ * Converts a FHIR Quantity to a CQL Quantity
370
+ *
371
+ * @param value the value to convert
372
+ * @return a CQL Quantity
373
+ * @throws IllegalArgumentException if value is not a Quantity
374
+ */
375
+ fun toCqlQuantity(value: ICompositeType?): Quantity?
376
+
377
+ /**
378
+ * Converts a FHIR Ratio to a CQL Ratio
379
+ *
380
+ * @param value the value to convert
381
+ * @return a CQL Ratio
382
+ * @throws IllegalArgumentException if value is not a Ratio
383
+ */
384
+ fun toCqlRatio(value: ICompositeType?): Ratio?
385
+
386
+ /**
387
+ * Converts a FHIR Any to a CQL Any
388
+ *
389
+ * @param value the value to convert
390
+ * @return a CQL Any
391
+ */
392
+ fun toCqlAny(value: IBase?): Any?
393
+
394
+ /**
395
+ * Converts a FHIR Coding to a CQL Code
396
+ *
397
+ * @param value the value to convert
398
+ * @return a CQL Code
399
+ */
400
+ fun toCqlCode(value: IBaseCoding?): Code?
401
+
402
+ /**
403
+ * Converts a FHIR CodeableConcept to a CQL Concept
404
+ *
405
+ * @param value the value to convert
406
+ * @return a CQL Concept
407
+ * @throws IllegalArgumentException if value is not a CodeableConcept
408
+ */
409
+ fun toCqlConcept(value: ICompositeType?): Concept?
410
+
411
+ /**
412
+ * Converts a FHIR Range or Period to a CQL Interval
413
+ *
414
+ * @param value the value to convert
415
+ * @return a CQL Interval
416
+ * @throws IllegalArgumentException if value is not a Range or Period
417
+ */
418
+ fun toCqlInterval(value: ICompositeType?): Interval?
419
+
420
+ /**
421
+ * Converts a FHIR Structure to a CQL Tuple
422
+ *
423
+ * @param value the value to convert
424
+ * @return a CQL Tuple
425
+ */
426
+ fun toCqlTuple(value: IBase?): Tuple?
427
+
428
+ companion object {
429
+ const val EMPTY_LIST_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-isEmptyList"
430
+ const val EMPTY_TUPLE_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-isEmptyTuple"
431
+ const val DATA_ABSENT_REASON_EXT_URL =
432
+ "http://hl7.org/fhir/StructureDefinition/data-absent-reason"
433
+ const val DATA_ABSENT_REASON_UNKNOWN_CODE = "unknown"
434
+ const val CQL_TYPE_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-cqlType"
435
+
436
+ // Stacktrace of an exception that occurred during CQL evaluation, as the native platform
437
+ // represents it (e.g. Java)
438
+ const val NATIVE_STACK_TRACE_EXT_URL =
439
+ "http://hl7.org/fhir/StructureDefinition/cqf-nativeStackTrace"
440
+
441
+ // The CQL representation of a FHIR structure.
442
+ const val CQL_TEXT_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-cqlText"
443
+ }
444
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverterFactory.kt ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+
5
+ class FhirTypeConverterFactory {
6
+ /**
7
+ * Creates a FHIR version specific FhirTypeConverter
8
+ *
9
+ * @param fhirVersionEnum the version of FHIR to create a converter for
10
+ * @return a FhirTypeConverter
11
+ * @throws IllegalArgumentException if the FHIR version specified is not supported
12
+ */
13
+ fun create(fhirVersionEnum: FhirVersionEnum): FhirTypeConverter {
14
+ return when (fhirVersionEnum) {
15
+ FhirVersionEnum.DSTU2_HL7ORG -> Dstu2FhirTypeConverter()
16
+ FhirVersionEnum.DSTU3 -> Dstu3FhirTypeConverter()
17
+ FhirVersionEnum.R4 -> R4FhirTypeConverter()
18
+ FhirVersionEnum.R5 -> R5FhirTypeConverter()
19
+ else ->
20
+ throw IllegalArgumentException(
21
+ "Unsupported FHIR version for type conversion: $fhirVersionEnum"
22
+ )
23
+ }
24
+ }
25
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R4FhirTypeConverter.kt ADDED
@@ -0,0 +1,545 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
4
+ import java.math.BigDecimal
5
+ import java.time.format.DateTimeFormatter
6
+ import java.util.*
7
+ import java.util.stream.Collectors
8
+ import org.apache.commons.lang3.NotImplementedException
9
+ import org.hl7.fhir.instance.model.api.IBase
10
+ import org.hl7.fhir.instance.model.api.IBaseCoding
11
+ import org.hl7.fhir.instance.model.api.IBaseDatatype
12
+ import org.hl7.fhir.instance.model.api.IBaseOperationOutcome
13
+ import org.hl7.fhir.instance.model.api.ICompositeType
14
+ import org.hl7.fhir.instance.model.api.IIdType
15
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
16
+ import org.hl7.fhir.r4.model.BaseDateTimeType
17
+ import org.hl7.fhir.r4.model.BooleanType
18
+ import org.hl7.fhir.r4.model.CodeType
19
+ import org.hl7.fhir.r4.model.CodeableConcept
20
+ import org.hl7.fhir.r4.model.Coding
21
+ import org.hl7.fhir.r4.model.DateTimeType
22
+ import org.hl7.fhir.r4.model.DateType
23
+ import org.hl7.fhir.r4.model.DecimalType
24
+ import org.hl7.fhir.r4.model.IdType
25
+ import org.hl7.fhir.r4.model.IntegerType
26
+ import org.hl7.fhir.r4.model.OperationOutcome
27
+ import org.hl7.fhir.r4.model.Parameters
28
+ import org.hl7.fhir.r4.model.Period
29
+ import org.hl7.fhir.r4.model.Range
30
+ import org.hl7.fhir.r4.model.Resource
31
+ import org.hl7.fhir.r4.model.StringType
32
+ import org.hl7.fhir.r4.model.TimeType
33
+ import org.hl7.fhir.r4.model.Type
34
+ import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator
35
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL
36
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TYPE_EXT_URL
37
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL
38
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE
39
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL
40
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL
41
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL
42
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
43
+ import org.opencds.cqf.cql.engine.runtime.Boolean
44
+ import org.opencds.cqf.cql.engine.runtime.Code
45
+ import org.opencds.cqf.cql.engine.runtime.Concept
46
+ import org.opencds.cqf.cql.engine.runtime.DateTime
47
+ import org.opencds.cqf.cql.engine.runtime.Decimal
48
+ import org.opencds.cqf.cql.engine.runtime.Integer
49
+ import org.opencds.cqf.cql.engine.runtime.Interval
50
+ import org.opencds.cqf.cql.engine.runtime.List
51
+ import org.opencds.cqf.cql.engine.runtime.Long
52
+ import org.opencds.cqf.cql.engine.runtime.Quantity
53
+ import org.opencds.cqf.cql.engine.runtime.Ratio
54
+ import org.opencds.cqf.cql.engine.runtime.String
55
+ import org.opencds.cqf.cql.engine.runtime.Time
56
+ import org.opencds.cqf.cql.engine.runtime.Tuple
57
+ import org.opencds.cqf.cql.engine.runtime.Value
58
+ import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName
59
+ import org.opencds.cqf.cql.engine.runtime.dateTypeName
60
+ import org.opencds.cqf.cql.engine.runtime.quantityTypeName
61
+
62
+ internal class R4FhirTypeConverter : BaseFhirTypeConverter() {
63
+ override fun toFhirId(value: String?): IIdType? {
64
+ if (value == null) {
65
+ return null
66
+ }
67
+
68
+ return IdType(value.value)
69
+ }
70
+
71
+ override fun toFhirBoolean(value: Boolean?): BooleanType? {
72
+ if (value == null) {
73
+ return null
74
+ }
75
+
76
+ return BooleanType(value.value)
77
+ }
78
+
79
+ override fun toFhirInteger(value: Integer?): IPrimitiveType<Int>? {
80
+ if (value == null) {
81
+ return null
82
+ }
83
+
84
+ return IntegerType(value.value)
85
+ }
86
+
87
+ override fun toFhirInteger64(value: Long?): IPrimitiveType<kotlin.Long> {
88
+ throw IllegalArgumentException("FHIR R4 does not support Long/Integer64 values")
89
+ }
90
+
91
+ // R4 has no integer64, so Using CQL with FHIR maps System.Long to FHIR.string, without the L
92
+ // suffix of the CQL literal. cqf-cqlType keeps the result from reading as a System.String.
93
+ override fun toFhirLong(value: Long): IBase? {
94
+ val result = StringType(value.value.toString())
95
+ result.addExtension(CQL_TYPE_EXT_URL, StringType("System.Long"))
96
+ return result
97
+ }
98
+
99
+ override fun toFhirDecimal(value: Decimal?): IPrimitiveType<BigDecimal>? {
100
+ if (value == null) {
101
+ return null
102
+ }
103
+
104
+ return DecimalType(value.value)
105
+ }
106
+
107
+ override fun toFhirDate(
108
+ value: org.opencds.cqf.cql.engine.runtime.Date?
109
+ ): IPrimitiveType<Date>? {
110
+ if (value == null) {
111
+ return null
112
+ }
113
+
114
+ return DateType(value.toStringInner())
115
+ }
116
+
117
+ override fun toFhirDateTime(value: DateTime?): IPrimitiveType<Date>? {
118
+ if (value == null) {
119
+ return null
120
+ }
121
+
122
+ val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
123
+ result.precision = toFhirPrecision(value.precision!!)
124
+ return result
125
+ }
126
+
127
+ override fun toFhirTime(value: Time?): IPrimitiveType<kotlin.String>? {
128
+ if (value == null) {
129
+ return null
130
+ }
131
+
132
+ return TimeType(value.toStringInner())
133
+ }
134
+
135
+ override fun toFhirString(value: String?): IPrimitiveType<kotlin.String>? {
136
+ if (value == null) {
137
+ return null
138
+ }
139
+
140
+ return StringType(value.value)
141
+ }
142
+
143
+ override fun toFhirQuantity(value: Quantity?): ICompositeType? {
144
+ if (value == null) {
145
+ return null
146
+ }
147
+
148
+ val unit = value.unit
149
+ val system =
150
+ if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units"
151
+ else "http://unitsofmeasure.org"
152
+ val ucumUnit = toUcumUnit(unit)
153
+
154
+ return org.hl7.fhir.r4.model
155
+ .Quantity()
156
+ .setSystem(system)
157
+ .setCode(ucumUnit)
158
+ .setValue(value.value)
159
+ .setUnit(unit)
160
+ }
161
+
162
+ override fun toFhirRatio(value: Ratio?): ICompositeType? {
163
+ if (value == null) {
164
+ return null
165
+ }
166
+
167
+ return org.hl7.fhir.r4.model
168
+ .Ratio()
169
+ .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.r4.model.Quantity?)
170
+ .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.r4.model.Quantity?)
171
+ }
172
+
173
+ override fun toFhirCoding(value: Code?): IBaseCoding? {
174
+ if (value == null) {
175
+ return null
176
+ }
177
+
178
+ val coding = Coding()
179
+ coding.setSystem(value.system)
180
+ coding.setCode(value.code)
181
+ coding.setDisplay(value.display)
182
+ coding.setVersion(value.version)
183
+ return coding
184
+ }
185
+
186
+ override fun toFhirCodeableConcept(value: Concept?): ICompositeType? {
187
+ if (value == null) {
188
+ return null
189
+ }
190
+
191
+ val codeableConcept = CodeableConcept()
192
+ codeableConcept.setText(value.display)
193
+ if (value.codes != null) {
194
+ for (c in value.codes) {
195
+ codeableConcept.addCoding(toFhirCoding(c) as Coding?)
196
+ }
197
+ }
198
+
199
+ return codeableConcept
200
+ }
201
+
202
+ override fun toFhirPeriod(value: Interval?): ICompositeType? {
203
+ if (value == null) {
204
+ return null
205
+ }
206
+
207
+ val period = Period()
208
+ if (value.pointType == dateTimeTypeName) {
209
+ if (value.start != null) {
210
+ period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType?
211
+ }
212
+
213
+ if (value.end != null) {
214
+ period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType?
215
+ }
216
+
217
+ return period
218
+ } else if (value.pointType == dateTypeName) {
219
+ // TODO: This will construct DateTimeType values in FHIR with the system
220
+ // timezone id, not the
221
+ // timezoneoffset of the evaluation request..... this is a bug waiting to happen
222
+ if (value.start != null) {
223
+ period.setStart(
224
+ toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
225
+ )
226
+ }
227
+
228
+ if (value.end != null) {
229
+ period.setEnd(
230
+ toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
231
+ )
232
+ }
233
+
234
+ return period
235
+ }
236
+
237
+ throw IllegalArgumentException(
238
+ "FHIR Period can only be created from an Interval of Date or DateTime type"
239
+ )
240
+ }
241
+
242
+ override fun toFhirRange(value: Interval?): ICompositeType? {
243
+ if (value == null) {
244
+ return null
245
+ }
246
+
247
+ require(value.pointType == quantityTypeName) {
248
+ "FHIR Range can only be created from an Interval of Quantity type"
249
+ }
250
+
251
+ val range = Range()
252
+ range.setLow(toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.r4.model.Quantity?)
253
+ range.setHigh(toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.r4.model.Quantity?)
254
+
255
+ return range
256
+ }
257
+
258
+ private fun addElementToParameter(
259
+ param: Parameters.ParametersParameterComponent,
260
+ key: kotlin.String?,
261
+ value: Value?,
262
+ ) {
263
+ if (value == null) {
264
+ // Null value, add a single empty value with an extension indicating the reason
265
+ val dataAbsentValue: BooleanType =
266
+ emptyBooleanWithExtension(
267
+ DATA_ABSENT_REASON_EXT_URL,
268
+ CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE),
269
+ )
270
+ addPartWithNameAndValue(param, key, dataAbsentValue)
271
+ return
272
+ }
273
+
274
+ if (value !is List) {
275
+ // Single, non-null value
276
+ addPartWithNameAndValue(param, key, toFhirType(value)!!)
277
+ return
278
+ }
279
+
280
+ val iterable = value
281
+
282
+ if (!iterable.iterator().hasNext()) {
283
+ // Empty list
284
+ val emptyListValue: BooleanType =
285
+ emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true))
286
+ addPartWithNameAndValue(param, key, emptyListValue)
287
+ } else {
288
+ // Non-empty list, one part per value
289
+ val fhirTypes = this.toFhirTypes(iterable)
290
+ for (fhirType in fhirTypes) {
291
+ addPartWithNameAndValue(param, key, fhirType!!)
292
+ }
293
+ }
294
+ }
295
+
296
+ override fun toFhirTuple(value: Tuple?): IBase? {
297
+ if (value == null) {
298
+ return null
299
+ }
300
+
301
+ val parameters = Parameters()
302
+ val param = parameters.addParameter()
303
+
304
+ if (value.elements.isEmpty()) {
305
+ param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true)))
306
+ }
307
+
308
+ for (key in value.elements.keys) {
309
+ addElementToParameter(param, key, value.elements[key])
310
+ }
311
+
312
+ return param
313
+ }
314
+
315
+ override fun toCqlQuantity(value: ICompositeType?): Quantity? {
316
+ if (value == null) {
317
+ return null
318
+ }
319
+
320
+ require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" }
321
+
322
+ val quantity = value as org.hl7.fhir.r4.model.Quantity
323
+ require(!quantity.hasComparator()) {
324
+ "Cannot convert a FHIR Quantity with a comparator to a CQL quantity"
325
+ }
326
+ return Quantity()
327
+ .withUnit(toCqlCalendarUnit(quantity.getUnit()))
328
+ .withValue(quantity.getValue())
329
+ }
330
+
331
+ override fun toCqlRatio(value: ICompositeType?): Ratio? {
332
+ if (value == null) {
333
+ return null
334
+ }
335
+
336
+ require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" }
337
+
338
+ val ratio = value as org.hl7.fhir.r4.model.Ratio
339
+
340
+ return Ratio()
341
+ .withNumerator(toCqlQuantity(ratio.getNumerator()))
342
+ .withDenominator(toCqlQuantity(ratio.getDenominator()))
343
+ }
344
+
345
+ override fun toCqlAny(value: IBase?): Any? {
346
+ if (value == null) {
347
+ return null
348
+ }
349
+
350
+ throw NotImplementedException("Unable to convert to System.Any type")
351
+ }
352
+
353
+ override fun toCqlCode(value: IBaseCoding?): Code? {
354
+ if (value == null) {
355
+ return null
356
+ }
357
+
358
+ val coding = value as Coding
359
+
360
+ return Code()
361
+ .withSystem(coding.getSystem())
362
+ .withCode(coding.getCode())
363
+ .withVersion(coding.getVersion())
364
+ .withDisplay(coding.getDisplay())
365
+ }
366
+
367
+ override fun toCqlConcept(value: ICompositeType?): Concept? {
368
+ if (value == null) {
369
+ return null
370
+ }
371
+
372
+ require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" }
373
+
374
+ val codeableConcept = value as CodeableConcept
375
+
376
+ return Concept()
377
+ .withDisplay(codeableConcept.getText())
378
+ .withCodes(
379
+ codeableConcept
380
+ .getCoding()
381
+ .stream()
382
+ .map<Code?> { x: Coding? -> toCqlCode(x) }
383
+ .collect(Collectors.toList())
384
+ )
385
+ }
386
+
387
+ override fun toCqlInterval(value: ICompositeType?): Interval? {
388
+ if (value == null) {
389
+ return null
390
+ }
391
+
392
+ if (value.fhirType() == "Range") {
393
+ val range = value as Range
394
+ return Interval(
395
+ toCqlQuantity(range.getLow()),
396
+ true,
397
+ toCqlQuantity(range.getHigh()),
398
+ true,
399
+ )
400
+ } else if (value.fhirType() == "Period") {
401
+ val period = value as Period
402
+ return Interval(
403
+ toCqlTemporal(period.startElement),
404
+ true,
405
+ toCqlTemporal(period.endElement),
406
+ true,
407
+ )
408
+ } else {
409
+ throw IllegalArgumentException("value is not a FHIR Range or Period")
410
+ }
411
+ }
412
+
413
+ override fun toCqlDate(value: IPrimitiveType<Date>?): org.opencds.cqf.cql.engine.runtime.Date? {
414
+ if (value == null) {
415
+ return null
416
+ }
417
+
418
+ require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) {
419
+ "value is not a FHIR Date or DateTime"
420
+ }
421
+
422
+ val baseDateTime = value as BaseDateTimeType
423
+ when (baseDateTime.precision) {
424
+ TemporalPrecisionEnum.YEAR,
425
+ TemporalPrecisionEnum.DAY,
426
+ TemporalPrecisionEnum.MONTH ->
427
+ return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
428
+
429
+ TemporalPrecisionEnum.SECOND,
430
+ TemporalPrecisionEnum.MILLI,
431
+ TemporalPrecisionEnum.MINUTE ->
432
+ throw IllegalArgumentException("value has a precision higher than a CQL Date")
433
+
434
+ else -> throw IllegalArgumentException("value has a precision higher than a CQL Date")
435
+ }
436
+ }
437
+
438
+ override fun toCqlDateTime(value: IPrimitiveType<Date>?): DateTime? {
439
+ if (value == null) {
440
+ return null
441
+ }
442
+
443
+ if (value.fhirType() == "instant" || value.fhirType() == "dateTime") {
444
+ val baseDateTime = value as BaseDateTimeType
445
+ return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
446
+ } else {
447
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
448
+ }
449
+ }
450
+
451
+ override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? {
452
+ if (value == null) {
453
+ return null
454
+ }
455
+
456
+ if (
457
+ value.fhirType() == "instant" ||
458
+ value.fhirType() == "dateTime" ||
459
+ value.fhirType() == "date"
460
+ ) {
461
+ val baseDateTime = value as BaseDateTimeType
462
+ when (baseDateTime.precision) {
463
+ TemporalPrecisionEnum.YEAR,
464
+ TemporalPrecisionEnum.DAY,
465
+ TemporalPrecisionEnum.MONTH ->
466
+ return toDate(
467
+ baseDateTime.valueAsCalendar,
468
+ baseDateTime.precision.calendarConstant,
469
+ )
470
+
471
+ TemporalPrecisionEnum.SECOND,
472
+ TemporalPrecisionEnum.MILLI,
473
+ TemporalPrecisionEnum.MINUTE ->
474
+ return toDateTime(
475
+ baseDateTime.valueAsCalendar,
476
+ baseDateTime.precision.calendarConstant,
477
+ )
478
+
479
+ else ->
480
+ return toDateTime(
481
+ baseDateTime.valueAsCalendar,
482
+ baseDateTime.precision.calendarConstant,
483
+ )
484
+ }
485
+ } else {
486
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
487
+ }
488
+ }
489
+
490
+ override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? {
491
+ if (exception == null) {
492
+ return null
493
+ }
494
+
495
+ val outcome = OperationOutcome()
496
+ outcome
497
+ .addIssue()
498
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
499
+ .setCode(OperationOutcome.IssueType.EXCEPTION)
500
+ .setDiagnostics(exception.message)
501
+ .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception)))
502
+
503
+ return outcome
504
+ }
505
+
506
+ override fun toCqlText(value: Value?): IBaseDatatype? {
507
+ if (value == null) {
508
+ return null
509
+ }
510
+
511
+ val s = ToStringEvaluator.toString(value)?.value
512
+ val text = StringType(s)
513
+ text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true))
514
+ return text
515
+ }
516
+
517
+ companion object {
518
+ private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType {
519
+ val result = BooleanType(null as kotlin.String?)
520
+ result.addExtension().setUrl(url).setValue(value)
521
+ return result
522
+ }
523
+
524
+ private fun addPartWithNameAndValue(
525
+ param: Parameters.ParametersParameterComponent,
526
+ key: kotlin.String?,
527
+ value: Any,
528
+ ) {
529
+ if (value is Parameters.ParametersParameterComponent) {
530
+ value.setName(key)
531
+ param.addPart(value)
532
+ } else {
533
+ val part = param.addPart().setName(key)
534
+ when (value) {
535
+ is Resource -> part.setResource(value)
536
+ is Type -> part.setValue(value)
537
+ else ->
538
+ throw IllegalArgumentException(
539
+ "Unsupported FHIR type: " + value.javaClass.getName()
540
+ )
541
+ }
542
+ }
543
+ }
544
+ }
545
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R5FhirTypeConverter.kt ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
4
+ import java.math.BigDecimal
5
+ import java.time.format.DateTimeFormatter
6
+ import java.util.*
7
+ import java.util.stream.Collectors
8
+ import org.apache.commons.lang3.NotImplementedException
9
+ import org.hl7.fhir.instance.model.api.IBase
10
+ import org.hl7.fhir.instance.model.api.IBaseCoding
11
+ import org.hl7.fhir.instance.model.api.IBaseDatatype
12
+ import org.hl7.fhir.instance.model.api.IBaseOperationOutcome
13
+ import org.hl7.fhir.instance.model.api.ICompositeType
14
+ import org.hl7.fhir.instance.model.api.IIdType
15
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
16
+ import org.hl7.fhir.r5.model.BaseDateTimeType
17
+ import org.hl7.fhir.r5.model.BooleanType
18
+ import org.hl7.fhir.r5.model.CodeType
19
+ import org.hl7.fhir.r5.model.CodeableConcept
20
+ import org.hl7.fhir.r5.model.Coding
21
+ import org.hl7.fhir.r5.model.DataType
22
+ import org.hl7.fhir.r5.model.DateTimeType
23
+ import org.hl7.fhir.r5.model.DateType
24
+ import org.hl7.fhir.r5.model.DecimalType
25
+ import org.hl7.fhir.r5.model.IdType
26
+ import org.hl7.fhir.r5.model.Integer64Type
27
+ import org.hl7.fhir.r5.model.IntegerType
28
+ import org.hl7.fhir.r5.model.OperationOutcome
29
+ import org.hl7.fhir.r5.model.Parameters
30
+ import org.hl7.fhir.r5.model.Period
31
+ import org.hl7.fhir.r5.model.Range
32
+ import org.hl7.fhir.r5.model.Resource
33
+ import org.hl7.fhir.r5.model.StringType
34
+ import org.hl7.fhir.r5.model.TimeType
35
+ import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator
36
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL
37
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL
38
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE
39
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL
40
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL
41
+ import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL
42
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
43
+ import org.opencds.cqf.cql.engine.runtime.Boolean
44
+ import org.opencds.cqf.cql.engine.runtime.Code
45
+ import org.opencds.cqf.cql.engine.runtime.Concept
46
+ import org.opencds.cqf.cql.engine.runtime.DateTime
47
+ import org.opencds.cqf.cql.engine.runtime.Decimal
48
+ import org.opencds.cqf.cql.engine.runtime.Integer
49
+ import org.opencds.cqf.cql.engine.runtime.Interval
50
+ import org.opencds.cqf.cql.engine.runtime.List
51
+ import org.opencds.cqf.cql.engine.runtime.Long
52
+ import org.opencds.cqf.cql.engine.runtime.Quantity
53
+ import org.opencds.cqf.cql.engine.runtime.Ratio
54
+ import org.opencds.cqf.cql.engine.runtime.String
55
+ import org.opencds.cqf.cql.engine.runtime.Time
56
+ import org.opencds.cqf.cql.engine.runtime.Tuple
57
+ import org.opencds.cqf.cql.engine.runtime.Value
58
+ import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName
59
+ import org.opencds.cqf.cql.engine.runtime.dateTypeName
60
+ import org.opencds.cqf.cql.engine.runtime.quantityTypeName
61
+
62
+ internal class R5FhirTypeConverter : BaseFhirTypeConverter() {
63
+ override fun toFhirId(value: String?): IIdType? {
64
+ if (value == null) {
65
+ return null
66
+ }
67
+
68
+ return IdType(value.value)
69
+ }
70
+
71
+ override fun toFhirBoolean(value: Boolean?): BooleanType? {
72
+ if (value == null) {
73
+ return null
74
+ }
75
+
76
+ return BooleanType(value.value)
77
+ }
78
+
79
+ override fun toFhirInteger(value: Integer?): IPrimitiveType<Int>? {
80
+ if (value == null) {
81
+ return null
82
+ }
83
+
84
+ return IntegerType(value.value)
85
+ }
86
+
87
+ override fun toFhirInteger64(value: Long?): IPrimitiveType<kotlin.Long>? {
88
+ if (value == null) {
89
+ return null
90
+ }
91
+
92
+ return Integer64Type(value.value)
93
+ }
94
+
95
+ override fun toFhirDecimal(value: Decimal?): IPrimitiveType<BigDecimal>? {
96
+ if (value == null) {
97
+ return null
98
+ }
99
+
100
+ return DecimalType(value.value)
101
+ }
102
+
103
+ override fun toFhirDate(
104
+ value: org.opencds.cqf.cql.engine.runtime.Date?
105
+ ): IPrimitiveType<Date>? {
106
+ if (value == null) {
107
+ return null
108
+ }
109
+
110
+ return DateType(value.toStringInner())
111
+ }
112
+
113
+ override fun toFhirDateTime(value: DateTime?): IPrimitiveType<Date>? {
114
+ if (value == null) {
115
+ return null
116
+ }
117
+
118
+ val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
119
+ result.precision = toFhirPrecision(value.precision!!)
120
+ return result
121
+ }
122
+
123
+ override fun toFhirTime(value: Time?): IPrimitiveType<kotlin.String>? {
124
+ if (value == null) {
125
+ return null
126
+ }
127
+
128
+ return TimeType(value.toStringInner())
129
+ }
130
+
131
+ override fun toFhirString(value: String?): IPrimitiveType<kotlin.String>? {
132
+ if (value == null) {
133
+ return null
134
+ }
135
+
136
+ return StringType(value.value)
137
+ }
138
+
139
+ override fun toFhirQuantity(value: Quantity?): ICompositeType? {
140
+ if (value == null) {
141
+ return null
142
+ }
143
+
144
+ val unit = value.unit
145
+ val system =
146
+ if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units"
147
+ else "http://unitsofmeasure.org"
148
+ val ucumUnit = toUcumUnit(unit)
149
+
150
+ return org.hl7.fhir.r5.model
151
+ .Quantity()
152
+ .setSystem(system)
153
+ .setCode(ucumUnit)
154
+ .setValue(value.value)
155
+ .setUnit(unit)
156
+ }
157
+
158
+ override fun toFhirRatio(value: Ratio?): ICompositeType? {
159
+ if (value == null) {
160
+ return null
161
+ }
162
+
163
+ return org.hl7.fhir.r5.model
164
+ .Ratio()
165
+ .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.r5.model.Quantity?)
166
+ .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.r5.model.Quantity?)
167
+ }
168
+
169
+ override fun toFhirCoding(value: Code?): IBaseCoding? {
170
+ if (value == null) {
171
+ return null
172
+ }
173
+
174
+ val coding = Coding()
175
+ coding.setSystem(value.system)
176
+ coding.setCode(value.code)
177
+ coding.setDisplay(value.display)
178
+ coding.setVersion(value.version)
179
+ return coding
180
+ }
181
+
182
+ override fun toFhirCodeableConcept(value: Concept?): ICompositeType? {
183
+ if (value == null) {
184
+ return null
185
+ }
186
+
187
+ val codeableConcept = CodeableConcept()
188
+ codeableConcept.setText(value.display)
189
+ if (value.codes != null) {
190
+ for (c in value.codes) {
191
+ codeableConcept.addCoding(toFhirCoding(c) as Coding?)
192
+ }
193
+ }
194
+
195
+ return codeableConcept
196
+ }
197
+
198
+ override fun toFhirPeriod(value: Interval?): ICompositeType? {
199
+ if (value == null) {
200
+ return null
201
+ }
202
+
203
+ val period = Period()
204
+ if (value.pointType == dateTimeTypeName) {
205
+ if (value.start != null) {
206
+ period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType?
207
+ }
208
+
209
+ if (value.end != null) {
210
+ period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType?
211
+ }
212
+
213
+ return period
214
+ } else if (value.pointType == dateTypeName) {
215
+ // TODO: This will construct DateTimeType values in FHIR with the system timezone id,
216
+ // not the
217
+ // timezoneoffset of the evaluation request..... this is a bug waiting to happen
218
+ if (value.start != null) {
219
+ period.setStart(
220
+ toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
221
+ )
222
+ }
223
+
224
+ if (value.end != null) {
225
+ period.setEnd(
226
+ toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue()
227
+ )
228
+ }
229
+
230
+ return period
231
+ }
232
+
233
+ throw IllegalArgumentException(
234
+ "FHIR Period can only be created from an Interval of Date or DateTime type"
235
+ )
236
+ }
237
+
238
+ override fun toFhirRange(value: Interval?): ICompositeType? {
239
+ if (value == null) {
240
+ return null
241
+ }
242
+
243
+ require(value.pointType == quantityTypeName) {
244
+ "FHIR Range can only be created from an Interval of Quantity type"
245
+ }
246
+
247
+ val range = Range()
248
+ range.setLow(toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.r5.model.Quantity?)
249
+ range.setHigh(toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.r5.model.Quantity?)
250
+
251
+ return range
252
+ }
253
+
254
+ private fun addElementToParameter(
255
+ param: Parameters.ParametersParameterComponent,
256
+ key: kotlin.String?,
257
+ value: Value?,
258
+ ) {
259
+ if (value == null) {
260
+ // Null value, add a single empty value with an extension indicating the reason
261
+ val dataAbsentValue: BooleanType =
262
+ emptyBooleanWithExtension(
263
+ DATA_ABSENT_REASON_EXT_URL,
264
+ CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE),
265
+ )
266
+ addPartWithNameAndValue(param, key, dataAbsentValue)
267
+ return
268
+ }
269
+
270
+ if (value !is List) {
271
+ // Single, non-null value
272
+ addPartWithNameAndValue(param, key, toFhirType(value)!!)
273
+ return
274
+ }
275
+
276
+ val iterable = value
277
+
278
+ if (!iterable.iterator().hasNext()) {
279
+ // Empty list
280
+ val emptyListValue: BooleanType =
281
+ emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true))
282
+ addPartWithNameAndValue(param, key, emptyListValue)
283
+ } else {
284
+ // Non-empty list, one part per value
285
+ val fhirTypes = this.toFhirTypes(iterable)
286
+ for (fhirType in fhirTypes) {
287
+ addPartWithNameAndValue(param, key, fhirType!!)
288
+ }
289
+ }
290
+ }
291
+
292
+ override fun toFhirTuple(value: Tuple?): IBase? {
293
+ if (value == null) {
294
+ return null
295
+ }
296
+
297
+ val parameters = Parameters()
298
+ val param = parameters.addParameter()
299
+
300
+ if (value.elements.isEmpty()) {
301
+ param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true)))
302
+ }
303
+
304
+ for (key in value.elements.keys) {
305
+ addElementToParameter(param, key, value.elements[key])
306
+ }
307
+
308
+ return param
309
+ }
310
+
311
+ override fun toCqlQuantity(value: ICompositeType?): Quantity? {
312
+ if (value == null) {
313
+ return null
314
+ }
315
+
316
+ require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" }
317
+
318
+ val quantity = value as org.hl7.fhir.r5.model.Quantity
319
+ require(!quantity.hasComparator()) {
320
+ "Cannot convert a FHIR Quantity with a comparator to a CQL quantity"
321
+ }
322
+ return Quantity()
323
+ .withUnit(toCqlCalendarUnit(quantity.getUnit()))
324
+ .withValue(quantity.getValue())
325
+ }
326
+
327
+ override fun toCqlRatio(value: ICompositeType?): Ratio? {
328
+ if (value == null) {
329
+ return null
330
+ }
331
+
332
+ require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" }
333
+
334
+ val ratio = value as org.hl7.fhir.r5.model.Ratio
335
+
336
+ return Ratio()
337
+ .withNumerator(toCqlQuantity(ratio.getNumerator()))
338
+ .withDenominator(toCqlQuantity(ratio.getDenominator()))
339
+ }
340
+
341
+ override fun toCqlAny(value: IBase?): Any? {
342
+ if (value == null) {
343
+ return null
344
+ }
345
+
346
+ throw NotImplementedException("Unable to convert to System.Any type")
347
+ }
348
+
349
+ override fun toCqlCode(value: IBaseCoding?): Code? {
350
+ if (value == null) {
351
+ return null
352
+ }
353
+
354
+ val coding = value as Coding
355
+
356
+ return Code()
357
+ .withSystem(coding.getSystem())
358
+ .withCode(coding.getCode())
359
+ .withVersion(coding.getVersion())
360
+ .withDisplay(coding.getDisplay())
361
+ }
362
+
363
+ override fun toCqlConcept(value: ICompositeType?): Concept? {
364
+ if (value == null) {
365
+ return null
366
+ }
367
+
368
+ require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" }
369
+
370
+ val codeableConcept = value as CodeableConcept
371
+
372
+ return Concept()
373
+ .withDisplay(codeableConcept.getText())
374
+ .withCodes(
375
+ codeableConcept
376
+ .getCoding()
377
+ .stream()
378
+ .map<Code?> { value: Coding? -> this.toCqlCode(value) }
379
+ .collect(Collectors.toList())
380
+ )
381
+ }
382
+
383
+ override fun toCqlInterval(value: ICompositeType?): Interval? {
384
+ if (value == null) {
385
+ return null
386
+ }
387
+
388
+ if (value.fhirType() == "Range") {
389
+ val range = value as Range
390
+ return Interval(
391
+ toCqlQuantity(range.getLow()),
392
+ true,
393
+ toCqlQuantity(range.getHigh()),
394
+ true,
395
+ )
396
+ } else if (value.fhirType() == "Period") {
397
+ val period = value as Period
398
+ return Interval(
399
+ toCqlTemporal(period.startElement),
400
+ true,
401
+ toCqlTemporal(period.endElement),
402
+ true,
403
+ )
404
+ } else {
405
+ throw IllegalArgumentException("value is not a FHIR Range or Period")
406
+ }
407
+ }
408
+
409
+ override fun toCqlDate(value: IPrimitiveType<Date>?): org.opencds.cqf.cql.engine.runtime.Date? {
410
+ if (value == null) {
411
+ return null
412
+ }
413
+
414
+ require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) {
415
+ "value is not a FHIR Date or DateTime"
416
+ }
417
+
418
+ val baseDateTime = value as BaseDateTimeType
419
+ when (baseDateTime.precision) {
420
+ TemporalPrecisionEnum.YEAR,
421
+ TemporalPrecisionEnum.DAY,
422
+ TemporalPrecisionEnum.MONTH ->
423
+ return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
424
+
425
+ TemporalPrecisionEnum.SECOND,
426
+ TemporalPrecisionEnum.MILLI,
427
+ TemporalPrecisionEnum.MINUTE ->
428
+ throw IllegalArgumentException("value has a precision higher than a CQL Date")
429
+
430
+ else -> throw IllegalArgumentException("value has a precision higher than a CQL Date")
431
+ }
432
+ }
433
+
434
+ override fun toCqlDateTime(value: IPrimitiveType<Date>?): DateTime? {
435
+ if (value == null) {
436
+ return null
437
+ }
438
+
439
+ if (value.fhirType() == "instant" || value.fhirType() == "dateTime") {
440
+ val baseDateTime = value as BaseDateTimeType
441
+ return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant)
442
+ } else {
443
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
444
+ }
445
+ }
446
+
447
+ override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? {
448
+ if (value == null) {
449
+ return null
450
+ }
451
+
452
+ if (
453
+ value.fhirType() == "instant" ||
454
+ value.fhirType() == "dateTime" ||
455
+ value.fhirType() == "date"
456
+ ) {
457
+ val baseDateTime = value as BaseDateTimeType
458
+ when (baseDateTime.precision) {
459
+ TemporalPrecisionEnum.YEAR,
460
+ TemporalPrecisionEnum.DAY,
461
+ TemporalPrecisionEnum.MONTH ->
462
+ return toDate(
463
+ baseDateTime.valueAsCalendar,
464
+ baseDateTime.precision.calendarConstant,
465
+ )
466
+
467
+ TemporalPrecisionEnum.SECOND,
468
+ TemporalPrecisionEnum.MILLI,
469
+ TemporalPrecisionEnum.MINUTE ->
470
+ return toDateTime(
471
+ baseDateTime.valueAsCalendar,
472
+ baseDateTime.precision.calendarConstant,
473
+ )
474
+
475
+ else ->
476
+ return toDateTime(
477
+ baseDateTime.valueAsCalendar,
478
+ baseDateTime.precision.calendarConstant,
479
+ )
480
+ }
481
+ } else {
482
+ throw IllegalArgumentException("value is not a FHIR Instant or DateTime")
483
+ }
484
+ }
485
+
486
+ override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? {
487
+ if (exception == null) {
488
+ return null
489
+ }
490
+
491
+ val outcome = OperationOutcome()
492
+ outcome
493
+ .addIssue()
494
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
495
+ .setCode(OperationOutcome.IssueType.EXCEPTION)
496
+ .setDiagnostics(exception.message)
497
+ .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception)))
498
+
499
+ return outcome
500
+ }
501
+
502
+ override fun toCqlText(value: Value?): IBaseDatatype? {
503
+ if (value == null) {
504
+ return null
505
+ }
506
+
507
+ val s = ToStringEvaluator.toString(value)?.value
508
+ val text = StringType(s)
509
+ text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true))
510
+ return text
511
+ }
512
+
513
+ companion object {
514
+ private fun emptyBooleanWithExtension(url: kotlin.String?, value: DataType?): BooleanType {
515
+ val result = BooleanType(null as kotlin.String?)
516
+ result.addExtension().setUrl(url).setValue(value)
517
+ return result
518
+ }
519
+
520
+ private fun addPartWithNameAndValue(
521
+ param: Parameters.ParametersParameterComponent,
522
+ key: kotlin.String?,
523
+ value: Any,
524
+ ) {
525
+ if (value is Parameters.ParametersParameterComponent) {
526
+ value.setName(key)
527
+ param.addPart(value)
528
+ } else {
529
+ val part = param.addPart().setName(key)
530
+ when (value) {
531
+ is Resource -> part.setResource(value)
532
+ is DataType -> part.setValue(value)
533
+ else ->
534
+ throw IllegalArgumentException(
535
+ "Unsupported FHIR type: " + value.javaClass.getName()
536
+ )
537
+ }
538
+ }
539
+ }
540
+ }
541
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/FhirVersionMisMatchException.kt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.exception
2
+
3
+ class FhirVersionMisMatchException(message: String?) : RuntimeException(message)
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownElement.kt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.exception
2
+
3
+ import org.opencds.cqf.cql.engine.exception.DataProviderException
4
+
5
+ class UnknownElement(message: String?) : DataProviderException(message)
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownPath.kt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.exception
2
+
3
+ import org.opencds.cqf.cql.engine.exception.DataProviderException
4
+
5
+ class UnknownPath(message: String?) : DataProviderException(message)
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownType.kt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.exception
2
+
3
+ import org.opencds.cqf.cql.engine.exception.DataProviderException
4
+
5
+ class UnknownType(message: String?) : DataProviderException(message)
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu2FhirModelResolver.kt ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.model
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import java.util.*
6
+ import org.hl7.fhir.dstu2.model.AnnotatedUuidType
7
+ import org.hl7.fhir.dstu2.model.Base
8
+ import org.hl7.fhir.dstu2.model.BaseDateTimeType
9
+ import org.hl7.fhir.dstu2.model.EnumFactory
10
+ import org.hl7.fhir.dstu2.model.Enumeration
11
+ import org.hl7.fhir.dstu2.model.Enumerations
12
+ import org.hl7.fhir.dstu2.model.IdType
13
+ import org.hl7.fhir.dstu2.model.Resource
14
+ import org.hl7.fhir.dstu2.model.SimpleQuantity
15
+ import org.hl7.fhir.dstu2.model.TimeType
16
+ import org.hl7.fhir.instance.model.api.IBaseResource
17
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
18
+
19
+ open class Dstu2FhirModelResolver(fhirContext: FhirContext) :
20
+ FhirModelResolver<
21
+ Base,
22
+ BaseDateTimeType,
23
+ TimeType,
24
+ SimpleQuantity,
25
+ IdType,
26
+ Resource,
27
+ Enumeration<*>,
28
+ EnumFactory<*>,
29
+ >(fhirContext) {
30
+ constructor() : this(FhirContext.forDstu2())
31
+
32
+ init {
33
+ this.packageNames =
34
+ (mutableListOf(
35
+ "ca.uhn.fhir.model.dstu2",
36
+ "org.hl7.fhir.dstu2.model",
37
+ "ca.uhn.fhir.model.primitive",
38
+ ))
39
+ require(fhirContext.version.version == FhirVersionEnum.DSTU2) {
40
+ "The supplied context is not configured for DSTU2"
41
+ }
42
+ }
43
+
44
+ override fun initialize() {
45
+ // HAPI has some bugs where it's missing annotations on certain types. This patches that.
46
+ this.fhirContext.registerCustomType(AnnotatedUuidType::class.java)
47
+
48
+ // The context loads Resources on demand which can cause resolution to fail in certain cases
49
+ // This forces all Resource types to be loaded.
50
+
51
+ // force calling of validateInitialized();
52
+ this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode())
53
+
54
+ val myNameToResourceType: MutableMap<String?, Class<out IBaseResource?>>
55
+ try {
56
+ val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType")
57
+ f.setAccessible(true)
58
+
59
+ // This is magic reflection to handle the fact that we need to manually
60
+ // initialize this map, but it's a private field with no accessor.
61
+ @Suppress("UNCHECKED_CAST")
62
+ myNameToResourceType =
63
+ f.get(this.fhirContext) as MutableMap<String?, Class<out IBaseResource?>>
64
+
65
+ val toLoad: MutableList<Class<out IBaseResource?>> =
66
+ ArrayList<Class<out IBaseResource?>>(myNameToResourceType.size)
67
+
68
+ for (type in Enumerations.ResourceType.entries) {
69
+ // These are abstract types that should never be resolved directly.
70
+ when (type) {
71
+ Enumerations.ResourceType.DOMAINRESOURCE,
72
+ Enumerations.ResourceType.RESOURCE,
73
+ Enumerations.ResourceType.NULL -> continue
74
+ else -> {}
75
+ }
76
+ if (myNameToResourceType.containsKey(type.toCode().lowercase()))
77
+ toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!)
78
+ }
79
+
80
+ // Sends a list of all classes to be loaded in bulk.
81
+ val m =
82
+ this.fhirContext.javaClass.getDeclaredMethod(
83
+ "scanResourceTypes",
84
+ MutableCollection::class.java,
85
+ )
86
+ m.setAccessible(true)
87
+ m.invoke(this.fhirContext, toLoad)
88
+ } catch (_: Exception) {
89
+ // intentionally ignored
90
+ }
91
+ }
92
+
93
+ override fun castToSimpleQuantity(base: Base): SimpleQuantity {
94
+ return base.castToSimpleQuantity(base)
95
+ }
96
+
97
+ override fun getCalendar(dateTime: BaseDateTimeType): Calendar {
98
+ return dateTime.toCalendar()
99
+ }
100
+
101
+ override fun getCalendarConstant(dateTime: BaseDateTimeType): Int {
102
+ return dateTime.precision.calendarConstant
103
+ }
104
+
105
+ override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) {
106
+ target.setPrecision(toTemporalPrecisionEnum(value.precision!!))
107
+ }
108
+
109
+ override fun timeToString(time: TimeType): String {
110
+ return time.value
111
+ }
112
+
113
+ override fun idToString(id: IdType): String {
114
+ return id.idPart
115
+ }
116
+
117
+ override fun getResourceType(resource: Resource): String {
118
+ return resource.fhirType()
119
+ }
120
+
121
+ override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> {
122
+ return Enumeration(factory)
123
+ }
124
+
125
+ override fun enumChecker(`object`: Any): Boolean {
126
+ return `object` is Enumeration<*>
127
+ }
128
+
129
+ override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> {
130
+ val value: Enum<*>? = enumeration.getValue()
131
+ if (value != null) {
132
+ val enumSimpleName = value.javaClass.getSimpleName()
133
+ return this.resolveType(enumSimpleName + "EnumFactory")!!
134
+ } else {
135
+ val myEnumFactoryField = enumeration.javaClass.getDeclaredField("myEnumFactory")
136
+ myEnumFactoryField.setAccessible(true)
137
+ val factory = myEnumFactoryField.get(enumeration) as EnumFactory<*>
138
+ return factory.javaClass
139
+ }
140
+ }
141
+
142
+ override fun getContextPath(contextType: String?, targetType: String?): String? {
143
+ if (targetType == null || contextType == null) {
144
+ return null
145
+ }
146
+
147
+ if ("Patient" == contextType) {
148
+ when (targetType) {
149
+ "QuestionnaireResponse" -> return "subject"
150
+ else -> {}
151
+ }
152
+ }
153
+
154
+ return super.getContextPath(contextType, targetType)
155
+ }
156
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu3FhirModelResolver.kt ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.model
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import java.util.*
6
+ import org.hl7.fhir.dstu3.model.AnnotatedUuidType
7
+ import org.hl7.fhir.dstu3.model.Base
8
+ import org.hl7.fhir.dstu3.model.BaseDateTimeType
9
+ import org.hl7.fhir.dstu3.model.EnumFactory
10
+ import org.hl7.fhir.dstu3.model.Enumeration
11
+ import org.hl7.fhir.dstu3.model.Enumerations
12
+ import org.hl7.fhir.dstu3.model.IdType
13
+ import org.hl7.fhir.dstu3.model.Resource
14
+ import org.hl7.fhir.dstu3.model.SimpleQuantity
15
+ import org.hl7.fhir.dstu3.model.TimeType
16
+ import org.hl7.fhir.instance.model.api.IBaseResource
17
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
18
+
19
+ open class Dstu3FhirModelResolver(fhirContext: FhirContext) :
20
+ FhirModelResolver<
21
+ Base,
22
+ BaseDateTimeType,
23
+ TimeType,
24
+ SimpleQuantity,
25
+ IdType,
26
+ Resource,
27
+ Enumeration<*>,
28
+ EnumFactory<*>,
29
+ >(fhirContext) {
30
+ constructor() : this(FhirContext.forDstu3())
31
+
32
+ init {
33
+ this.packageNames = mutableListOf("org.hl7.fhir.dstu3.model")
34
+ require(fhirContext.version.version == FhirVersionEnum.DSTU3) {
35
+ "The supplied context is not configured for DSTU3"
36
+ }
37
+ }
38
+
39
+ override fun initialize() {
40
+ // HAPI has some bugs where it's missing annotations on certain types. This patches that.
41
+ this.fhirContext.registerCustomType(AnnotatedUuidType::class.java)
42
+
43
+ // The context loads Resources on demand which can cause resolution to fail in certain cases
44
+ // This forces all Resource types to be loaded.
45
+
46
+ // force calling of validateInitialized();
47
+ this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode())
48
+
49
+ val myNameToResourceType: MutableMap<String?, Class<out IBaseResource?>>
50
+ try {
51
+ val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType")
52
+ f.setAccessible(true)
53
+
54
+ // This is magic reflection to handle the fact that we need to manually
55
+ // initialize this map, but it's a private field with no accessor.
56
+ @Suppress("UNCHECKED_CAST")
57
+ myNameToResourceType =
58
+ f.get(this.fhirContext) as MutableMap<String?, Class<out IBaseResource?>>
59
+
60
+ val toLoad: MutableList<Class<out IBaseResource?>> =
61
+ ArrayList<Class<out IBaseResource?>>(myNameToResourceType.size)
62
+
63
+ for (type in Enumerations.ResourceType.entries) {
64
+ // These are abstract types that should never be resolved directly.
65
+ when (type) {
66
+ Enumerations.ResourceType.DOMAINRESOURCE,
67
+ Enumerations.ResourceType.RESOURCE,
68
+ Enumerations.ResourceType.NULL -> continue
69
+ else -> {}
70
+ }
71
+ if (myNameToResourceType.containsKey(type.toCode().lowercase()))
72
+ toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!)
73
+ }
74
+
75
+ // Sends a list of all classes to be loaded in bulk.
76
+ val m =
77
+ this.fhirContext.javaClass.getDeclaredMethod(
78
+ "scanResourceTypes",
79
+ MutableCollection::class.java,
80
+ )
81
+ m.setAccessible(true)
82
+ m.invoke(this.fhirContext, toLoad)
83
+ } catch (_: Exception) {
84
+ // intentionally ignored
85
+ }
86
+ }
87
+
88
+ override fun castToSimpleQuantity(base: Base): SimpleQuantity {
89
+ return base.castToSimpleQuantity(base)
90
+ }
91
+
92
+ override fun getCalendar(dateTime: BaseDateTimeType): Calendar {
93
+ return dateTime.valueAsCalendar
94
+ }
95
+
96
+ override fun getCalendarConstant(dateTime: BaseDateTimeType): Int {
97
+ return dateTime.precision.calendarConstant
98
+ }
99
+
100
+ override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) {
101
+ target.precision = toTemporalPrecisionEnum(value.precision!!)
102
+ }
103
+
104
+ override fun timeToString(time: TimeType): String {
105
+ return time.value
106
+ }
107
+
108
+ override fun idToString(id: IdType): String {
109
+ return id.idPart
110
+ }
111
+
112
+ override fun getResourceType(resource: Resource): String {
113
+ return resource.fhirType()
114
+ }
115
+
116
+ override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> {
117
+ return Enumeration(factory)
118
+ }
119
+
120
+ override fun enumChecker(`object`: Any): Boolean {
121
+ return `object` is Enumeration<*>
122
+ }
123
+
124
+ override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> {
125
+ return enumeration.getEnumFactory().javaClass
126
+ }
127
+
128
+ override fun resolveType(typeName: String?): Class<*>? {
129
+ // TODO: Might be able to patch some of these by registering custom types in HAPI.
130
+
131
+ var typeName = typeName
132
+ when (typeName) {
133
+ "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality"
134
+ "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus"
135
+ "EventStatus" -> typeName = $$"Procedure$ProcedureStatus"
136
+ "qualityType" -> typeName = $$"Sequence$QualityType"
137
+ "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus"
138
+ "repositoryType" -> typeName = $$"Sequence$RepositoryType"
139
+ "SampledDataDataType" -> typeName = "StringType"
140
+ }
141
+
142
+ return super.resolveType(typeName)
143
+ }
144
+
145
+ override fun getContextPath(contextType: String?, targetType: String?): String? {
146
+ if (targetType == null || contextType == null) {
147
+ return null
148
+ }
149
+
150
+ if ("Patient" == contextType) {
151
+ when (targetType) {
152
+ "MedicationStatement",
153
+ "QuestionnaireResponse" -> return "subject"
154
+ "Task" -> return "for"
155
+ "Coverage" -> return "beneficiary"
156
+ else -> {}
157
+ }
158
+ }
159
+
160
+ return super.getContextPath(contextType, targetType)
161
+ }
162
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/FhirModelResolver.kt ADDED
@@ -0,0 +1,768 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.model
2
+
3
+ import ca.uhn.fhir.context.BaseRuntimeChildDefinition
4
+ import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition
5
+ import ca.uhn.fhir.context.FhirContext
6
+ import ca.uhn.fhir.context.RuntimeChildResourceBlockDefinition
7
+ import ca.uhn.fhir.context.RuntimeChildResourceDefinition
8
+ import ca.uhn.fhir.model.api.TemporalPrecisionEnum
9
+ import java.lang.reflect.InvocationTargetException
10
+ import java.util.Calendar
11
+ import java.util.GregorianCalendar
12
+ import java.util.Optional
13
+ import java.util.concurrent.ConcurrentHashMap
14
+ import javax.xml.namespace.QName
15
+ import org.hl7.fhir.instance.model.api.IAnyResource
16
+ import org.hl7.fhir.instance.model.api.IBase
17
+ import org.hl7.fhir.instance.model.api.IBaseBackboneElement
18
+ import org.hl7.fhir.instance.model.api.IBaseElement
19
+ import org.hl7.fhir.instance.model.api.IBaseEnumFactory
20
+ import org.hl7.fhir.instance.model.api.IBaseEnumeration
21
+ import org.hl7.fhir.instance.model.api.IBaseHasExtensions
22
+ import org.hl7.fhir.instance.model.api.IBaseResource
23
+ import org.hl7.fhir.instance.model.api.ICompositeType
24
+ import org.hl7.fhir.instance.model.api.IIdType
25
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
26
+ import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator
27
+ import org.opencds.cqf.cql.engine.exception.InvalidPrecision
28
+ import org.opencds.cqf.cql.engine.fhir.exception.UnknownType
29
+ import org.opencds.cqf.cql.engine.fhir.fhirModelId
30
+ import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri
31
+ import org.opencds.cqf.cql.engine.model.ModelResolver
32
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
33
+ import org.opencds.cqf.cql.engine.runtime.Boolean
34
+ import org.opencds.cqf.cql.engine.runtime.ClassInstance
35
+ import org.opencds.cqf.cql.engine.runtime.Date
36
+ import org.opencds.cqf.cql.engine.runtime.DateTime
37
+ import org.opencds.cqf.cql.engine.runtime.Precision
38
+ import org.opencds.cqf.cql.engine.runtime.TemporalHelper
39
+ import org.opencds.cqf.cql.engine.runtime.Time
40
+ import org.opencds.cqf.cql.engine.runtime.Value
41
+ import org.opencds.cqf.cql.engine.runtime.anyTypeName
42
+ import org.opencds.cqf.cql.engine.runtime.toCqlBoolean
43
+ import org.opencds.cqf.cql.engine.runtime.toCqlDecimal
44
+ import org.opencds.cqf.cql.engine.runtime.toCqlInteger
45
+ import org.opencds.cqf.cql.engine.runtime.toCqlList
46
+ import org.opencds.cqf.cql.engine.runtime.toCqlLong
47
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
48
+
49
+ // TODO: Probably quite a bit of redundancy here. Probably only really need the BaseType and the
50
+ // PrimitiveType
51
+ /*
52
+ * type-to-class and contextPath resolutions are potentially expensive and can be cached
53
+ * for improved performance.
54
+ *
55
+ * See <a href="https://github.com/DBCG/cql-evaluator/blob/master/evaluator.engine/src/main/java/org/opencds/cqf/cql/evaluator/engine/model/CachingModelResolverDecorator.java"/>
56
+ * for a decorator that adds caching logic for ModelResolvers.
57
+ */
58
+ @Suppress("TooManyFunctions")
59
+ abstract class FhirModelResolver<
60
+ BaseType : IBase,
61
+ BaseDateTimeType : IPrimitiveType<java.util.Date>,
62
+ TimeType : IPrimitiveType<String>,
63
+ SimpleQuantityType : ICompositeType,
64
+ IdType : IIdType,
65
+ ResourceType : IBaseResource,
66
+ EnumerationType : IBaseEnumeration<*>,
67
+ EnumFactoryType : IBaseEnumFactory<*>,
68
+ >( // getters & setters
69
+ // Data members
70
+ var fhirContext: FhirContext
71
+ ) : ModelResolver {
72
+ /** Memo for [resolveType]; see the note there. Concurrent because a resolver is shared. */
73
+ private val resolvedTypes = ConcurrentHashMap<String, Optional<Class<*>>>()
74
+
75
+ protected abstract fun initialize()
76
+
77
+ abstract fun castToSimpleQuantity(base: BaseType): SimpleQuantityType
78
+
79
+ protected abstract fun getCalendar(dateTime: BaseDateTimeType): Calendar
80
+
81
+ protected abstract fun getCalendarConstant(dateTime: BaseDateTimeType): Int
82
+
83
+ protected abstract fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal)
84
+
85
+ protected abstract fun idToString(id: IdType): String
86
+
87
+ protected abstract fun timeToString(time: TimeType): String
88
+
89
+ protected abstract fun getResourceType(resource: ResourceType): String
90
+
91
+ protected abstract fun enumConstructor(factory: EnumFactoryType): EnumerationType
92
+
93
+ protected abstract fun enumChecker(`object`: Any): kotlin.Boolean
94
+
95
+ protected abstract fun enumFactoryTypeGetter(enumeration: EnumerationType): Class<*>
96
+
97
+ init {
98
+ this.initialize()
99
+ }
100
+
101
+ override fun resolveId(target: Value?): kotlin.String? {
102
+ if (target is ClassInstance && target.type.namespaceURI == fhirModelNamespaceUri) {
103
+ val clazz = this.resolveType(target.type.localPart) ?: return null
104
+ if (IBaseResource::class.java.isAssignableFrom(clazz)) {
105
+ val id = target.elements["id"] as? ClassInstance ?: return null
106
+ return (id.elements["value"] as? org.opencds.cqf.cql.engine.runtime.String)?.value
107
+ }
108
+ }
109
+ return null
110
+ }
111
+
112
+ override fun getContextPath(
113
+ contextType: kotlin.String?,
114
+ targetType: kotlin.String?,
115
+ ): kotlin.String? {
116
+ if (targetType == null || contextType == null) {
117
+ return null
118
+ }
119
+
120
+ if (
121
+ contextType == "Unfiltered" ||
122
+ contextType == "Unspecified" ||
123
+ contextType == "Population"
124
+ ) {
125
+ return null
126
+ }
127
+
128
+ if (targetType == contextType) {
129
+ return "id"
130
+ }
131
+
132
+ val resourceDefinition = this.fhirContext.getResourceDefinition(targetType)
133
+ val theValue = this.createHapiInstance(contextType)
134
+
135
+ // Because we created this instance from the local FhirContext, we know it is an IBase
136
+ // The model resolver interface is not generic, so we have to cast here
137
+ @Suppress("UNCHECKED_CAST") val type = theValue.javaClass as Class<out IBase>
138
+
139
+ val children = resourceDefinition.children
140
+ for (child in children) {
141
+ val visitedElements: MutableSet<String?> = HashSet()
142
+ val path = this.innerGetContextPath(visitedElements, child, type)
143
+ if (path != null) {
144
+ return path
145
+ }
146
+ }
147
+
148
+ return null
149
+ }
150
+
151
+ protected fun innerGetContextPath(
152
+ visitedElements: MutableSet<String?>,
153
+ child: BaseRuntimeChildDefinition,
154
+ type: Class<out IBase?>?,
155
+ ): String? {
156
+ visitedElements.add(child.elementName)
157
+
158
+ if (child is RuntimeChildResourceDefinition) {
159
+ for (resourceClass in child.resourceTypes) {
160
+ if (resourceClass == type) {
161
+ return child.elementName
162
+ }
163
+ }
164
+
165
+ return null
166
+ }
167
+
168
+ if (child is RuntimeChildResourceBlockDefinition) {
169
+ val currentName = child.elementName
170
+ val element = child.getChildByName(currentName)
171
+
172
+ // Potential Kotlin/Java interop issue here?
173
+ // element.getChildren() returns ListBaseRuntimeChildDefinition>
174
+ @Suppress("UNCHECKED_CAST")
175
+ val children = element.getChildren() as List<BaseRuntimeChildDefinition>
176
+
177
+ for (nextChild in children) {
178
+ if (visitedElements.contains(nextChild.elementName)) {
179
+ continue
180
+ }
181
+
182
+ val path = this.innerGetContextPath(visitedElements, nextChild, type)
183
+ if (path != null) {
184
+ return "$currentName.$path"
185
+ }
186
+ }
187
+ }
188
+
189
+ return null
190
+ }
191
+
192
+ override fun `is`(valueType: String, type: QName): kotlin.Boolean? {
193
+ // System.Any is a supertype of all types
194
+ if (type == anyTypeName) {
195
+ return true
196
+ }
197
+
198
+ if (type.namespaceURI != fhirModelNamespaceUri) {
199
+ // FHIR model types only extend System.Any or other FHIR model types
200
+ return false
201
+ }
202
+
203
+ val valueTypeClass = resolveType(valueType) ?: return null
204
+ val typeClass = resolveType(type.localPart) ?: return null
205
+
206
+ return typeClass.isAssignableFrom(valueTypeClass)
207
+ }
208
+
209
+ override fun objectEquivalent(
210
+ left: ClassInstance,
211
+ right: ClassInstance,
212
+ equivalent: (l: Value?, r: Value?) -> Boolean,
213
+ ): Boolean {
214
+ // "id" elements are excluded from equivalence checking for instances of FHIR.Resource and
215
+ // FHIR.Element (see https://hl7.org/fhir/fhirpath.html#changes)
216
+ if (
217
+ `is`(left.type.localPart, QName(fhirModelNamespaceUri, "Resource")) == true ||
218
+ `is`(left.type.localPart, QName(fhirModelNamespaceUri, "Element")) == true
219
+ ) {
220
+ return EquivalentEvaluator.structuredValueElementsEquivalent(
221
+ left.elements.filterKeys { it != "id" },
222
+ right.elements.filterKeys { it != "id" },
223
+ equivalent,
224
+ )
225
+ }
226
+
227
+ return EquivalentEvaluator.structuredValueElementsEquivalent(
228
+ left.elements,
229
+ right.elements,
230
+ equivalent,
231
+ )
232
+ }
233
+
234
+ override fun createInstance(typeName: String?): Value {
235
+ return toCqlValue(createHapiInstance(typeName!!), true)!!
236
+ }
237
+
238
+ /** The package names of Java objects supported by this model */
239
+ open var packageNames = mutableListOf<String>()
240
+
241
+ /**
242
+ * Resolve the Java class that corresponds to the given model type.
243
+ *
244
+ * @param typeName E.g. "Patient"
245
+ * @return The Java class that corresponds to the given model type, e.g.
246
+ * `org.hl7.fhir.r4.model.Patient`.
247
+ */
248
+ /**
249
+ * Resolution is deterministic for a given type name, and a miss is expensive: the lookups below
250
+ * fall through to a `Class.forName` per configured package -- twice -- each throwing and
251
+ * discarding a `ClassNotFoundException`, and then to a scan of every registered resource. The
252
+ * set of type names a model produces is small and closed, so the answers are cached.
253
+ *
254
+ * Negative results are cached too. They cost the most to compute and recur just as often.
255
+ *
256
+ * Read-then-write rather than `computeIfAbsent`: the result does not depend on what else is in
257
+ * the map, so a racing duplicate computation is harmless, and this cannot deadlock if a
258
+ * resolution path ever re-enters this method.
259
+ */
260
+ open fun resolveType(typeName: String?): Class<*>? {
261
+ if (typeName == null) {
262
+ return resolveTypeUncached(null)
263
+ }
264
+ // A present entry is authoritative even when it holds null: a name that resolved to nothing
265
+ // must not be recomputed, or negative results would never actually be cached.
266
+ val cached = resolvedTypes[typeName]
267
+ return if (cached != null) cached.orElse(null)
268
+ else
269
+ resolveTypeUncached(typeName).also { resolvedTypes[typeName] = Optional.ofNullable(it) }
270
+ }
271
+
272
+ private fun resolveTypeUncached(typeName: String?): Class<*>? {
273
+ // For Dstu2
274
+ var typeName = typeName
275
+ if (typeName!!.startsWith("FHIR.")) {
276
+ typeName = typeName.replace("FHIR.", "")
277
+ }
278
+ // dataTypes
279
+ val definition = this.fhirContext.getElementDefinition(typeName)
280
+ if (definition != null) {
281
+ return definition.getImplementingClass()
282
+ }
283
+
284
+ try {
285
+ // Resources
286
+ return this.fhirContext.getResourceDefinition(typeName).implementingClass
287
+ } catch (_: Exception) {}
288
+
289
+ try {
290
+ if (typeName.contains(".")) {
291
+ val path = typeName.split(".")
292
+ val resourceDefinition =
293
+ if (this.fhirContext.resourceTypes.contains(path[0]))
294
+ this.fhirContext.getResourceDefinition(path[0])
295
+ else this.fhirContext.getElementDefinition(path[0])
296
+ var childName = path[1][0].lowercaseChar().toString() + path[1].substring(1)
297
+ var childDefinition =
298
+ resourceDefinition!!.getChildByName(childName)
299
+ ?: return resolveChildren(resourceDefinition.children, childName)
300
+ var childElement = childDefinition.getChildByName(childName)
301
+ for (i in 2..<path.size) {
302
+ childName = path[i][0].lowercaseChar().toString() + path[i].substring(1)
303
+ childDefinition = childElement.getChildByName(childName)
304
+ childElement = childDefinition.getChildByName(childName)
305
+ }
306
+ return childElement.getImplementingClass()
307
+ }
308
+ } catch (_: Exception) {}
309
+
310
+ // Special case for enumerations. They are often in the "Enumerations" class.
311
+ for (packageName in this.packageNames) {
312
+ try {
313
+ return Class.forName("$packageName.Enumerations$$typeName")
314
+ } catch (_: ClassNotFoundException) {}
315
+ }
316
+
317
+ // Other Types in package.
318
+ for (packageName in this.packageNames) {
319
+ try {
320
+ return Class.forName("$packageName.$typeName")
321
+ } catch (_: ClassNotFoundException) {}
322
+ }
323
+
324
+ // Scan all resources.
325
+ // Really, HAPI ought to register inner classes, right?
326
+ val clazz = deepSearch(typeName)
327
+ if (clazz != null) {
328
+ return clazz
329
+ }
330
+
331
+ try {
332
+ // Just give me SOMETHING.
333
+ return Class.forName(typeName)
334
+ } catch (_: ClassNotFoundException) {
335
+ throw UnknownType(
336
+ "Could not resolve type $typeName. Primary package(s) for this resolver are ${this.packageNames.joinToString(",")}"
337
+ )
338
+ }
339
+ }
340
+
341
+ // This method walks the entire child tree of a resource/element until the specified child is
342
+ // found
343
+ // This is for cases when the child path is not well-defined (STU3 and 4.0.0)
344
+ private fun resolveChildren(
345
+ children: List<BaseRuntimeChildDefinition>,
346
+ childName: String,
347
+ ): Class<*>? {
348
+ for (c in children) {
349
+ if (c.validChildNames.contains(childName)) {
350
+ return c.getChildByName(childName).getImplementingClass()
351
+ }
352
+ if (c is RuntimeChildResourceBlockDefinition) {
353
+ for (childrenName in c.validChildNames) {
354
+ if (c.elementName == childrenName) continue
355
+
356
+ @Suppress("UNCHECKED_CAST")
357
+ val nextChildren =
358
+ c.getChildByName(childrenName).getChildren()
359
+ as List<BaseRuntimeChildDefinition>
360
+ resolveChildren(nextChildren, childName)
361
+ }
362
+ }
363
+ }
364
+ return null
365
+ }
366
+
367
+ // Resolutions
368
+ protected fun resolveRuntimeDefinition(base: IBase): BaseRuntimeElementCompositeDefinition<*> {
369
+ when (base) {
370
+ is IAnyResource -> {
371
+ return this.fhirContext.getResourceDefinition(base)
372
+ }
373
+
374
+ is IBaseBackboneElement,
375
+ is IBaseElement -> {
376
+ return (this.fhirContext.getElementDefinition(base.javaClass)
377
+ as BaseRuntimeElementCompositeDefinition<*>?)!!
378
+ }
379
+
380
+ is ICompositeType -> {
381
+ @Suppress("UNCHECKED_CAST")
382
+ return this.fhirContext.getElementDefinition(base.javaClass)
383
+ as BaseRuntimeElementCompositeDefinition<ICompositeType?>
384
+ }
385
+
386
+ else ->
387
+ throw UnknownType(
388
+ "Unable to resolve the runtime definition for ${base.javaClass.name}"
389
+ )
390
+ }
391
+ }
392
+
393
+ private fun deepSearch(typeName: String): Class<*>? {
394
+ // Special case for "Codes". This suffix is often removed from the HAPI type.
395
+ val codelessName = typeName.replace("Codes", "").lowercase()
396
+ val lowerName = typeName.lowercase()
397
+
398
+ val elements = this.fhirContext.elementDefinitions
399
+ for (element in elements) {
400
+ val innerClasses = element.getImplementingClass().getDeclaredClasses()
401
+ for (clazz in innerClasses) {
402
+ val clazzLowerName = clazz.getSimpleName().lowercase()
403
+ if (clazzLowerName == lowerName || clazzLowerName == codelessName) {
404
+ return clazz
405
+ }
406
+ }
407
+ }
408
+
409
+ return null
410
+ }
411
+
412
+ // Creators
413
+
414
+ /**
415
+ * Creates an instance of the Java class that corresponds to the given model type.
416
+ *
417
+ * @param typeName E.g. "Patient"
418
+ * @return An instance of the HAPI FHIR class like `org.hl7.fhir.r4.model.Patient`.
419
+ */
420
+ fun createHapiInstance(typeName: String): Any {
421
+ val clazz =
422
+ this.resolveType(typeName) ?: throw UnknownType("Could not resolve type $typeName")
423
+ return createHapiInstance(clazz)
424
+ }
425
+
426
+ protected fun createHapiInstance(clazz: Class<*>): Any {
427
+ try {
428
+ if (clazz.isEnum) {
429
+ val factoryClass = this.resolveType(clazz.getName() + "EnumFactory")
430
+
431
+ @Suppress("UNCHECKED_CAST")
432
+ val factory = this.createHapiInstance(factoryClass!!) as EnumFactoryType
433
+ return this.enumConstructor(factory)
434
+ }
435
+
436
+ return clazz.getDeclaredConstructor().newInstance()
437
+ } catch (e: NoSuchMethodException) {
438
+ throw UnknownType(
439
+ "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}"
440
+ )
441
+ } catch (e: InvocationTargetException) {
442
+ throw UnknownType(
443
+ "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}"
444
+ )
445
+ } catch (e: InstantiationException) {
446
+ throw UnknownType(
447
+ "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}"
448
+ )
449
+ } catch (e: IllegalAccessException) {
450
+ throw UnknownType(
451
+ "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}"
452
+ )
453
+ }
454
+ }
455
+
456
+ protected fun toTime(value: TimeType): Time {
457
+ return Time(timeToString(value))
458
+ }
459
+
460
+ // Transformations
461
+ protected fun toDateTime(
462
+ value: BaseDateTimeType,
463
+ calendarConstant: Int = this.getCalendarConstant(value),
464
+ ): DateTime {
465
+ val calendar = this.getCalendar(value)
466
+
467
+ // TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() :
468
+ // calendar.getTimeZone();
469
+ // ZoneOffset zoneOffset =
470
+ // tz.toZoneId().getRules().getStandardOffset(calendar.toInstant());
471
+ val zoneOffset = (calendar as GregorianCalendar).toZonedDateTime().offset
472
+ when (calendarConstant) {
473
+ Calendar.YEAR ->
474
+ return DateTime(
475
+ TemporalHelper.zoneToOffset(zoneOffset),
476
+ calendar.get(Calendar.YEAR),
477
+ )
478
+ Calendar.MONTH ->
479
+ return DateTime(
480
+ TemporalHelper.zoneToOffset(zoneOffset),
481
+ calendar.get(Calendar.YEAR),
482
+ calendar.get(Calendar.MONTH) + 1,
483
+ )
484
+
485
+ Calendar.DAY_OF_MONTH ->
486
+ return DateTime(
487
+ TemporalHelper.zoneToOffset(zoneOffset),
488
+ calendar.get(Calendar.YEAR),
489
+ calendar.get(Calendar.MONTH) + 1,
490
+ calendar.get(Calendar.DAY_OF_MONTH),
491
+ )
492
+
493
+ Calendar.HOUR_OF_DAY ->
494
+ return DateTime(
495
+ TemporalHelper.zoneToOffset(zoneOffset),
496
+ calendar.get(Calendar.YEAR),
497
+ calendar.get(Calendar.MONTH) + 1,
498
+ calendar.get(Calendar.DAY_OF_MONTH),
499
+ calendar.get(Calendar.HOUR_OF_DAY),
500
+ )
501
+
502
+ Calendar.MINUTE ->
503
+ return DateTime(
504
+ TemporalHelper.zoneToOffset(zoneOffset),
505
+ calendar.get(Calendar.YEAR),
506
+ calendar.get(Calendar.MONTH) + 1,
507
+ calendar.get(Calendar.DAY_OF_MONTH),
508
+ calendar.get(Calendar.HOUR_OF_DAY),
509
+ calendar.get(Calendar.MINUTE),
510
+ )
511
+
512
+ Calendar.SECOND ->
513
+ return DateTime(
514
+ TemporalHelper.zoneToOffset(zoneOffset),
515
+ calendar.get(Calendar.YEAR),
516
+ calendar.get(Calendar.MONTH) + 1,
517
+ calendar.get(Calendar.DAY_OF_MONTH),
518
+ calendar.get(Calendar.HOUR_OF_DAY),
519
+ calendar.get(Calendar.MINUTE),
520
+ calendar.get(Calendar.SECOND),
521
+ )
522
+
523
+ Calendar.MILLISECOND ->
524
+ return DateTime(
525
+ TemporalHelper.zoneToOffset(zoneOffset),
526
+ calendar.get(Calendar.YEAR),
527
+ calendar.get(Calendar.MONTH) + 1,
528
+ calendar.get(Calendar.DAY_OF_MONTH),
529
+ calendar.get(Calendar.HOUR_OF_DAY),
530
+ calendar.get(Calendar.MINUTE),
531
+ calendar.get(Calendar.SECOND),
532
+ calendar.get(Calendar.MILLISECOND),
533
+ )
534
+
535
+ else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant")
536
+ }
537
+ }
538
+
539
+ protected fun toDate(
540
+ value: BaseDateTimeType,
541
+ calendarConstant: Int = this.getCalendarConstant(value),
542
+ ): Date {
543
+ val calendar = this.getCalendar(value)
544
+ // TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() :
545
+ // calendar.getTimeZone();
546
+ // ZoneOffset zoneOffset =
547
+ // tz.toZoneId().getRules().getStandardOffset(calendar.toInstant());
548
+ return when (calendarConstant) {
549
+ Calendar.YEAR -> Date(calendar.get(Calendar.YEAR))
550
+ Calendar.MONTH -> Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1)
551
+
552
+ Calendar.DAY_OF_MONTH ->
553
+ Date(
554
+ calendar.get(Calendar.YEAR),
555
+ calendar.get(Calendar.MONTH) + 1,
556
+ calendar.get(Calendar.DAY_OF_MONTH),
557
+ )
558
+
559
+ else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant")
560
+ }
561
+ }
562
+
563
+ fun setBaseValue(value: Any?, target: IBase?): IBase? {
564
+ if (target is IPrimitiveType<*>) {
565
+ setPrimitiveValue(value, target)
566
+ }
567
+ return value as IBase?
568
+ }
569
+
570
+ fun setPrimitiveValue(value: Any?, target: IPrimitiveType<*>) {
571
+ val simpleName = target.javaClass.getSimpleName()
572
+ when (simpleName) {
573
+ "DateTimeType",
574
+ "InstantType" -> {
575
+ // Ensure offset is taken into account from the ISO datetime String instead of the
576
+ // default timezone
577
+ target.valueAsString = (value as DateTime).toDateString()
578
+
579
+ @Suppress("UNCHECKED_CAST")
580
+ setCalendarConstant(target as BaseDateTimeType, value as BaseTemporal)
581
+ }
582
+ "DateType" -> {
583
+ val targetValue = (value as Date).toJavaDate()
584
+
585
+ @Suppress("UNCHECKED_CAST")
586
+ target as BaseDateTimeType
587
+ target.value = targetValue
588
+ setCalendarConstant(target, value as BaseTemporal)
589
+ }
590
+
591
+ "TimeType" -> target.asIPrimitive<String>().value = value.toString()
592
+ "Base64BinaryType" -> target.valueAsString = value as String?
593
+ else -> target.asIPrimitive<Any>().value = value
594
+ }
595
+ }
596
+
597
+ private fun <T : Any> Any?.asIPrimitive(): IPrimitiveType<T?> {
598
+ @Suppress("UNCHECKED_CAST")
599
+ return this as IPrimitiveType<T?>
600
+ }
601
+
602
+ fun toTemporalPrecisionEnum(precision: Precision): TemporalPrecisionEnum {
603
+ return when (precision) {
604
+ Precision.YEAR -> TemporalPrecisionEnum.YEAR
605
+ Precision.MONTH -> TemporalPrecisionEnum.MONTH
606
+ Precision.DAY -> TemporalPrecisionEnum.DAY
607
+ Precision.HOUR,
608
+ Precision.MINUTE -> TemporalPrecisionEnum.MINUTE
609
+ Precision.SECOND -> TemporalPrecisionEnum.SECOND
610
+ Precision.MILLISECOND -> TemporalPrecisionEnum.MILLI
611
+ else -> throw IllegalArgumentException("Unknown precision $precision")
612
+ }
613
+ }
614
+
615
+ /*
616
+ * // TODO: Find HAPI registry of Primitive Type conversions public Object
617
+ * fromJavaPrimitive(Object value, Object target) { String simpleName =
618
+ * target.getClass().getSimpleName(); switch(simpleName) { case "DateTimeType":
619
+ * case "InstantType": return ((DateTime)value).toJavaDate(); case "DateType":
620
+ * return ((org.opencds.cqf.cql.engine.runtime.Date)value).toJavaDate(); case
621
+ * "TimeType": return ((Time) value).toString(); }
622
+ *
623
+ * if (value instanceof Time) { return ((Time) value).toString(); } else {
624
+ * return value; } }
625
+ */
626
+ fun toSimpleCqlType(primitiveType: IPrimitiveType<*>): Value? {
627
+ val value = primitiveType.value
628
+
629
+ if (value == null) {
630
+ return null
631
+ }
632
+
633
+ val simpleName = primitiveType.javaClass.getSimpleName()
634
+ @Suppress("UNCHECKED_CAST")
635
+ return when (simpleName) {
636
+ "InstantType",
637
+ "DateTimeType" -> toDateTime(primitiveType as BaseDateTimeType)
638
+ "DateType" -> toDate(primitiveType as BaseDateTimeType)
639
+ "TimeType" -> toTime(primitiveType as TimeType)
640
+ "IdType" -> this.idToString(primitiveType as IdType).toCqlString()
641
+ "Base64BinaryType" -> primitiveType.valueAsString?.toCqlString()
642
+ else ->
643
+ when (value) {
644
+ is kotlin.Boolean -> value.toCqlBoolean()
645
+ is kotlin.Int -> value.toCqlInteger()
646
+ is kotlin.Long -> value.toCqlLong()
647
+ is java.math.BigDecimal -> value.toCqlDecimal()
648
+ is kotlin.String -> value.toCqlString()
649
+ else ->
650
+ throw IllegalArgumentException(
651
+ "Unable to convert a value of type ${value.javaClass.name} to a CQL simple type."
652
+ )
653
+ }
654
+ }
655
+ }
656
+
657
+ /**
658
+ * Recursively converts a HAPI FHIR construct to a CQL-native equivalent.
659
+ *
660
+ * @param target The HAPI FHIR object to convert
661
+ * @param expandPrimitivesAndEnumerationsWithNoValues Whether to convert a HAPI FHIR
662
+ * primitive/enumeration with no value to a structured type instance with a null `value`
663
+ * child, or to null.
664
+ */
665
+ fun toCqlValue(
666
+ target: Any?,
667
+ expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false,
668
+ ): ClassInstance? {
669
+ if (target == null) {
670
+ return null
671
+ }
672
+
673
+ if (target !is IBase) {
674
+ throw IllegalArgumentException(
675
+ "Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase."
676
+ )
677
+ }
678
+
679
+ if (this.enumChecker(target)) {
680
+ @Suppress("UNCHECKED_CAST")
681
+ target as EnumerationType
682
+
683
+ val elements = primitiveElements(target)
684
+
685
+ // If the instance is a primitive (including or even especially an enumeration), and it
686
+ // has no value, return null
687
+ if (
688
+ !expandPrimitivesAndEnumerationsWithNoValues &&
689
+ !target.hasValue() &&
690
+ elements.all { it.value == null }
691
+ ) {
692
+ return null
693
+ }
694
+
695
+ // For FHIR enumerations, use the type of the backing Enum
696
+ val factoryName = this.enumFactoryTypeGetter(target).simpleName
697
+ val typeName = factoryName.substringBefore("EnumFactory")
698
+
699
+ elements["value"] = target.valueAsString?.toCqlString()
700
+
701
+ return ClassInstance(QName(fhirModelNamespaceUri, typeName, fhirModelId), elements)
702
+ }
703
+
704
+ if (target is IPrimitiveType<*>) {
705
+ val elements = primitiveElements(target)
706
+
707
+ // If the instance is a primitive (including or even especially an enumeration), and it
708
+ // has no value, return null
709
+ if (
710
+ !expandPrimitivesAndEnumerationsWithNoValues &&
711
+ !target.hasValue() &&
712
+ elements.all { it.value == null }
713
+ ) {
714
+ return null
715
+ }
716
+
717
+ val elementDefinition = this.fhirContext.getElementDefinition(target.javaClass)
718
+
719
+ elements["value"] = toSimpleCqlType(target)
720
+
721
+ return ClassInstance(
722
+ QName(fhirModelNamespaceUri, elementDefinition.name, fhirModelId),
723
+ elements,
724
+ )
725
+ }
726
+
727
+ // Composite definitions include id, extension and modifierExtension (where applicable) as
728
+ // children, so they're converted here along with the rest of the children.
729
+ val definition = resolveRuntimeDefinition(target)
730
+ val elements = mutableMapOf<kotlin.String, Value?>()
731
+
732
+ for (child in definition.children) {
733
+ elements[child.elementName] =
734
+ child.accessor
735
+ .getValues(target)
736
+ .map { toCqlValue(it) }
737
+ .let {
738
+ if (child.max == 1) {
739
+ it.firstOrNull()
740
+ } else {
741
+ if (it.isEmpty()) null else it.toCqlList()
742
+ }
743
+ }
744
+ }
745
+
746
+ return ClassInstance(QName(fhirModelNamespaceUri, definition.name, fhirModelId), elements)
747
+ }
748
+
749
+ /**
750
+ * The id and extension elements of a FHIR primitive. Like all FHIR types, primitives may have
751
+ * an id and extensions, with or without a value.
752
+ */
753
+ private fun primitiveElements(target: IBase): MutableMap<kotlin.String, Value?> {
754
+ val elements = mutableMapOf<kotlin.String, Value?>()
755
+
756
+ if (target is IBaseHasExtensions) {
757
+ val extensionsAsCqlValues = target.extension.map { toCqlValue(it) }
758
+ elements["extension"] =
759
+ if (extensionsAsCqlValues.isEmpty()) null else extensionsAsCqlValues.toCqlList()
760
+ }
761
+
762
+ if (target is IBaseElement) {
763
+ elements["id"] = target.id?.toCqlString()
764
+ }
765
+
766
+ return elements
767
+ }
768
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R4FhirModelResolver.kt ADDED
@@ -0,0 +1,169 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.model
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import java.util.*
6
+ import org.hl7.fhir.instance.model.api.IBaseResource
7
+ import org.hl7.fhir.r4.model.AnnotatedUuidType
8
+ import org.hl7.fhir.r4.model.Base
9
+ import org.hl7.fhir.r4.model.BaseDateTimeType
10
+ import org.hl7.fhir.r4.model.EnumFactory
11
+ import org.hl7.fhir.r4.model.Enumeration
12
+ import org.hl7.fhir.r4.model.Enumerations
13
+ import org.hl7.fhir.r4.model.IdType
14
+ import org.hl7.fhir.r4.model.Resource
15
+ import org.hl7.fhir.r4.model.SimpleQuantity
16
+ import org.hl7.fhir.r4.model.TimeType
17
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
18
+
19
+ open class R4FhirModelResolver(fhirContext: FhirContext) :
20
+ FhirModelResolver<
21
+ Base,
22
+ BaseDateTimeType,
23
+ TimeType,
24
+ SimpleQuantity,
25
+ IdType,
26
+ Resource,
27
+ Enumeration<*>,
28
+ EnumFactory<*>,
29
+ >(fhirContext) {
30
+ constructor() : this(FhirContext.forR4())
31
+
32
+ init {
33
+ this.packageNames = mutableListOf("org.hl7.fhir.r4.model")
34
+ require(fhirContext.version.version == FhirVersionEnum.R4) {
35
+ "The supplied context is not configured for R4"
36
+ }
37
+ }
38
+
39
+ override fun initialize() {
40
+ // HAPI has some bugs where it's missing annotations on certain types. This patches that.
41
+ this.fhirContext.registerCustomType(AnnotatedUuidType::class.java)
42
+
43
+ // The context loads Resources on demand which can cause resolution to fail in certain cases
44
+ // This forces all Resource types to be loaded.
45
+
46
+ // force calling of validateInitialized();
47
+ this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode())
48
+
49
+ val myNameToResourceType: MutableMap<String?, Class<out IBaseResource?>>
50
+ try {
51
+ val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType")
52
+ f.setAccessible(true)
53
+
54
+ // This is magic reflection to handle the fact that we need to manually
55
+ // initialize this map, but it's a private field with no accessor.
56
+ @Suppress("UNCHECKED_CAST")
57
+ myNameToResourceType =
58
+ f.get(this.fhirContext) as MutableMap<String?, Class<out IBaseResource?>>
59
+
60
+ val toLoad: MutableList<Class<out IBaseResource?>> =
61
+ ArrayList<Class<out IBaseResource?>>(myNameToResourceType.size)
62
+
63
+ for (type in Enumerations.ResourceType.entries) {
64
+ // These are abstract types that should never be resolved directly.
65
+ when (type) {
66
+ Enumerations.ResourceType.DOMAINRESOURCE,
67
+ Enumerations.ResourceType.RESOURCE,
68
+ Enumerations.ResourceType.NULL -> continue
69
+ else -> {}
70
+ }
71
+ if (myNameToResourceType.containsKey(type.toCode().lowercase(Locale.getDefault())))
72
+ toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!)
73
+ }
74
+
75
+ // Sends a list of all classes to be loaded in bulk.
76
+ val m =
77
+ this.fhirContext.javaClass.getDeclaredMethod(
78
+ "scanResourceTypes",
79
+ MutableCollection::class.java,
80
+ )
81
+ m.setAccessible(true)
82
+ m.invoke(this.fhirContext, toLoad)
83
+ } catch (_: Exception) {
84
+ // intentionally ignored
85
+ }
86
+ }
87
+
88
+ override fun castToSimpleQuantity(base: Base): SimpleQuantity {
89
+ return base.castToSimpleQuantity(base)
90
+ }
91
+
92
+ override fun getCalendar(dateTime: BaseDateTimeType): Calendar {
93
+ return dateTime.valueAsCalendar
94
+ }
95
+
96
+ override fun getCalendarConstant(dateTime: BaseDateTimeType): Int {
97
+ return dateTime.precision.calendarConstant
98
+ }
99
+
100
+ override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) {
101
+ target.precision = toTemporalPrecisionEnum(value.precision!!)
102
+ }
103
+
104
+ override fun timeToString(time: TimeType): String {
105
+ return time.value
106
+ }
107
+
108
+ override fun idToString(id: IdType): String {
109
+ return id.idPart
110
+ }
111
+
112
+ override fun getResourceType(resource: Resource): String {
113
+ return resource.fhirType()
114
+ }
115
+
116
+ override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> {
117
+ return Enumeration(factory)
118
+ }
119
+
120
+ override fun enumChecker(`object`: Any): Boolean {
121
+ return `object` is Enumeration<*>
122
+ }
123
+
124
+ override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> {
125
+ return enumeration.getEnumFactory().javaClass
126
+ }
127
+
128
+ override fun resolveType(typeName: String?): Class<*>? {
129
+ // TODO: Might be able to patch some of these by registering custom types in HAPI.
130
+
131
+ var typeName = typeName
132
+ when (typeName) {
133
+ "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality"
134
+ "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus"
135
+ "EventStatus" -> typeName = $$"Procedure$ProcedureStatus"
136
+ "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus"
137
+ "SampledDataDataType" -> typeName = "StringType"
138
+ "ClaimProcessingCodes" -> typeName = $$"ClaimResponse$RemittanceOutcome"
139
+ "vConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality"
140
+ "ContractResourcePublicationStatusCodes" ->
141
+ typeName = $$"Contract$ContractPublicationStatus"
142
+ "CurrencyCode" -> typeName = "CodeType"
143
+ "Messageheader_Response_Request" ->
144
+ typeName = $$"MessageDefinition$MessageheaderResponseRequest"
145
+ "MimeType" -> typeName = "CodeType"
146
+ else -> {}
147
+ }
148
+
149
+ return super.resolveType(typeName)
150
+ }
151
+
152
+ override fun getContextPath(contextType: String?, targetType: String?): String? {
153
+ if (targetType == null || contextType == null) {
154
+ return null
155
+ }
156
+
157
+ if ("Patient" == contextType) {
158
+ when (targetType) {
159
+ "MedicationStatement",
160
+ "QuestionnaireResponse" -> return "subject"
161
+ "Task" -> return "for"
162
+ "Coverage" -> return "beneficiary"
163
+ else -> {}
164
+ }
165
+ }
166
+
167
+ return super.getContextPath(contextType, targetType)
168
+ }
169
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R5FhirModelResolver.kt ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.model
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import java.util.*
6
+ import org.hl7.fhir.exceptions.FHIRException
7
+ import org.hl7.fhir.instance.model.api.IBaseResource
8
+ import org.hl7.fhir.r5.model.Base
9
+ import org.hl7.fhir.r5.model.BaseDateTimeType
10
+ import org.hl7.fhir.r5.model.EnumFactory
11
+ import org.hl7.fhir.r5.model.Enumeration
12
+ import org.hl7.fhir.r5.model.Enumerations.FHIRTypes
13
+ import org.hl7.fhir.r5.model.IdType
14
+ import org.hl7.fhir.r5.model.Quantity
15
+ import org.hl7.fhir.r5.model.Resource
16
+ import org.hl7.fhir.r5.model.SimpleQuantity
17
+ import org.hl7.fhir.r5.model.TimeType
18
+ import org.opencds.cqf.cql.engine.runtime.BaseTemporal
19
+
20
+ open class R5FhirModelResolver(fhirContext: FhirContext) :
21
+ FhirModelResolver<
22
+ Base,
23
+ BaseDateTimeType,
24
+ TimeType,
25
+ SimpleQuantity,
26
+ IdType,
27
+ Resource,
28
+ Enumeration<*>,
29
+ EnumFactory<*>,
30
+ >(fhirContext) {
31
+ constructor() : this(FhirContext.forR5())
32
+
33
+ init {
34
+ this.packageNames = mutableListOf("org.hl7.fhir.r5.model")
35
+ require(fhirContext.version.version == FhirVersionEnum.R5) {
36
+ "The supplied context is not configured for R5"
37
+ }
38
+ }
39
+
40
+ override fun initialize() {
41
+ // The context loads Resources on demand which can cause resolution to fail in
42
+ // certain cases
43
+ // This forces all Resource types to be loaded.
44
+
45
+ // force calling of validateInitialized();
46
+
47
+ this.fhirContext.getResourceDefinition(FHIRTypes.ACCOUNT.toCode())
48
+
49
+ val myNameToResourceType: MutableMap<String?, Class<out IBaseResource?>>
50
+ try {
51
+ val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType")
52
+ f.setAccessible(true)
53
+
54
+ // This is magic reflection to handle the fact that we need to manually
55
+ // initialize this map, but it's a private field with no accessor.
56
+ @Suppress("UNCHECKED_CAST")
57
+ myNameToResourceType =
58
+ f.get(this.fhirContext) as MutableMap<String?, Class<out IBaseResource?>>
59
+
60
+ val toLoad = ArrayList<Class<out IBaseResource?>?>(myNameToResourceType.size)
61
+
62
+ for (type in FHIRTypes.entries) {
63
+ // These are abstract types that should never be resolved directly.
64
+ when (type) {
65
+ FHIRTypes.DOMAINRESOURCE,
66
+ FHIRTypes.RESOURCE,
67
+ FHIRTypes.NULL -> continue
68
+ else -> {}
69
+ }
70
+ if (myNameToResourceType.containsKey(type.toCode().lowercase(Locale.getDefault())))
71
+ toLoad.add(myNameToResourceType[type.toCode().lowercase(Locale.getDefault())])
72
+ }
73
+
74
+ // Sends a list of all classes to be loaded in bulk.
75
+ val m =
76
+ this.fhirContext.javaClass.getDeclaredMethod(
77
+ "scanResourceTypes",
78
+ MutableCollection::class.java,
79
+ )
80
+ m.setAccessible(true)
81
+ m.invoke(this.fhirContext, toLoad)
82
+ } catch (_: Exception) {
83
+ // intentionally ignored
84
+ }
85
+ }
86
+
87
+ override fun castToSimpleQuantity(base: Base): SimpleQuantity {
88
+ when (base) {
89
+ is SimpleQuantity -> return base
90
+ is Quantity -> {
91
+ val sq = SimpleQuantity()
92
+ sq.valueElement = base.valueElement
93
+ sq.comparatorElement = base.comparatorElement
94
+ sq.unitElement = base.unitElement
95
+ sq.systemElement = base.systemElement
96
+ sq.codeElement = base.codeElement
97
+ return sq
98
+ }
99
+
100
+ else ->
101
+ throw FHIRException(
102
+ "Unable to convert a " + base.javaClass.getName() + " to an SimpleQuantity"
103
+ )
104
+ }
105
+ }
106
+
107
+ override fun getCalendar(dateTime: BaseDateTimeType): Calendar {
108
+ return dateTime.valueAsCalendar
109
+ }
110
+
111
+ override fun getCalendarConstant(dateTime: BaseDateTimeType): Int {
112
+ return dateTime.precision.calendarConstant
113
+ }
114
+
115
+ override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) {
116
+ target.precision = toTemporalPrecisionEnum(value.precision!!)
117
+ }
118
+
119
+ override fun timeToString(time: TimeType): String {
120
+ return time.value
121
+ }
122
+
123
+ override fun idToString(id: IdType): String {
124
+ return id.idPart
125
+ }
126
+
127
+ override fun getResourceType(resource: Resource): String {
128
+ return resource.fhirType()
129
+ }
130
+
131
+ override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> {
132
+ return Enumeration(factory)
133
+ }
134
+
135
+ override fun enumChecker(`object`: Any): Boolean {
136
+ return `object` is Enumeration<*>
137
+ }
138
+
139
+ override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> {
140
+ return enumeration.getEnumFactory().javaClass
141
+ }
142
+
143
+ override fun resolveType(typeName: String?): Class<*>? {
144
+ // TODO: Might be able to patch some of these by registering custom types in
145
+ // HAPI.
146
+
147
+ var typeName = typeName
148
+ when (typeName) {
149
+ "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality"
150
+ "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus"
151
+ "EventStatus" -> typeName = $$"Procedure$ProcedureStatus"
152
+ "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus"
153
+ "SampledDataDataType" -> typeName = "StringType"
154
+ "ClaimProcessingCodes" -> typeName = $$"ClaimResponse$RemittanceOutcome"
155
+ "vConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality"
156
+ "ContractResourcePublicationStatusCodes" ->
157
+ typeName = $$"Contract$ContractPublicationStatus"
158
+ "CurrencyCode" -> typeName = "CodeType"
159
+ "MedicationAdministrationStatus" -> typeName = "CodeType"
160
+ "MedicationDispenseStatus" -> typeName = "CodeType"
161
+ "MedicationKnowledgeStatus" -> typeName = "CodeType"
162
+ "Messageheader_Response_Request" -> typeName = "CodeType"
163
+ "MimeType" -> typeName = "CodeType"
164
+ else -> {}
165
+ }
166
+
167
+ return super.resolveType(typeName)
168
+ }
169
+
170
+ override fun getContextPath(contextType: String?, targetType: String?): String? {
171
+ if (targetType == null || contextType == null) {
172
+ return null
173
+ }
174
+
175
+ if ("Patient" == contextType) {
176
+ when (targetType) {
177
+ "MedicationStatement",
178
+ "QuestionnaireResponse" -> return "subject"
179
+ "Task" -> return "for"
180
+ "Coverage" -> return "beneficiary"
181
+ else -> {}
182
+ }
183
+ }
184
+
185
+ return super.getContextPath(contextType, targetType)
186
+ }
187
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/BaseFhirQueryGenerator.kt ADDED
@@ -0,0 +1,460 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import ca.uhn.fhir.model.api.IQueryParameterType
6
+ import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum
7
+ import ca.uhn.fhir.rest.param.DateParam
8
+ import ca.uhn.fhir.rest.param.DateRangeParam
9
+ import ca.uhn.fhir.rest.param.ParamPrefixEnum
10
+ import ca.uhn.fhir.rest.param.TokenOrListParam
11
+ import ca.uhn.fhir.rest.param.TokenParam
12
+ import ca.uhn.fhir.rest.param.TokenParamModifier
13
+ import java.util.*
14
+ import org.apache.commons.lang3.tuple.Pair
15
+ import org.hl7.fhir.instance.model.api.IBaseConformance
16
+ import org.hl7.fhir.instance.model.api.ICompositeType
17
+ import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException
18
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap
19
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
20
+ import org.opencds.cqf.cql.engine.model.ModelResolver
21
+ import org.opencds.cqf.cql.engine.runtime.Code
22
+ import org.opencds.cqf.cql.engine.runtime.DateTime
23
+ import org.opencds.cqf.cql.engine.runtime.Interval
24
+ import org.opencds.cqf.cql.engine.runtime.Value
25
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
26
+ import org.opencds.cqf.cql.engine.terminology.ValueSetInfo
27
+
28
+ abstract class BaseFhirQueryGenerator
29
+ protected constructor(
30
+ protected var searchParameterResolver: SearchParameterResolver,
31
+ protected var terminologyProvider: TerminologyProvider?,
32
+ protected var modelResolver: ModelResolver,
33
+ fhirContext: FhirContext,
34
+ ) : FhirVersionIntegrityChecker {
35
+ protected var fhirContext: FhirContext
36
+
37
+ var pageSize: Int? = null
38
+ set(value) {
39
+ require(value != null && value > 0) { "value must be a non-null integer > 0" }
40
+ field = value
41
+ }
42
+
43
+ var maxCodesPerQuery: Int? = null
44
+ set(value) {
45
+ require(value != null && value > 0) { "value must be non-null integer > 0" }
46
+ field = value
47
+ }
48
+
49
+ var queryBatchThreshold: Int? = null
50
+ set(value) {
51
+ require(value != null && value > 0) { "value must be non-null integer > 0" }
52
+ field = value
53
+ }
54
+
55
+ // TODO: Think about how to best handle the decision to expand value sets... Should it be part
56
+ // of the
57
+ // terminology provider if it detects support for "code:in"? How does that feed back to the
58
+ // retriever?
59
+ var isExpandValueSets: Boolean = false
60
+
61
+ init {
62
+ this.isExpandValueSets = DEFAULT_SHOULD_EXPAND_VALUESETS
63
+
64
+ this.fhirContext = fhirContext
65
+ validateFhirVersionIntegrity(fetchFhirVersionEnum(this.fhirContext))
66
+ }
67
+
68
+ @Throws(FhirVersionMisMatchException::class)
69
+ override fun validateFhirVersionIntegrity(fhirVersion: FhirVersionEnum) {
70
+ require(fetchFhirVersionEnum(this.searchParameterResolver.fhirContext) == fhirVersion)
71
+ }
72
+
73
+ fun fetchFhirVersionEnum(fhirContext: FhirContext): FhirVersionEnum {
74
+ return fhirContext.version.version
75
+ }
76
+
77
+ abstract fun generateFhirQueries(
78
+ dataRequirement: ICompositeType?,
79
+ evaluationDateTime: DateTime?,
80
+ contextValues: MutableMap<String, String?>?,
81
+ parameters: MutableMap<String, Value?>?,
82
+ capabilityStatement: IBaseConformance?,
83
+ ): MutableList<String>
84
+
85
+ protected fun getTemplateParam(
86
+ dataType: String?,
87
+ templateId: String?,
88
+ ): Pair<String, IQueryParameterType>? {
89
+ if (templateId == null || templateId == "") {
90
+ return null
91
+ }
92
+
93
+ // Do something?
94
+ return null
95
+ }
96
+
97
+ fun getDateRangeParam(
98
+ dataType: String?,
99
+ datePath: String?,
100
+ dateLowPath: String?,
101
+ dateHighPath: String?,
102
+ dateRange: Interval?,
103
+ ): Pair<String, DateRangeParam>? {
104
+ if (dateRange == null) {
105
+ return null
106
+ }
107
+
108
+ var low: DateParam? = null
109
+ var high: DateParam? = null
110
+ if (dateRange.low != null) {
111
+ if (dateRange.low is Date) {
112
+ low =
113
+ DateParam(
114
+ ParamPrefixEnum.GREATERTHAN_OR_EQUALS,
115
+ Date.from((dateRange.low as Date).toInstant()),
116
+ )
117
+ } else if (dateRange.low is DateTime) {
118
+ low =
119
+ DateParam(
120
+ ParamPrefixEnum.GREATERTHAN_OR_EQUALS,
121
+ Date.from((dateRange.low as DateTime).dateTime!!.toInstant()),
122
+ )
123
+ }
124
+ }
125
+
126
+ if (dateRange.high != null) {
127
+ if (dateRange.low is Date) {
128
+ high =
129
+ DateParam(
130
+ ParamPrefixEnum.LESSTHAN_OR_EQUALS,
131
+ Date.from((dateRange.high as Date).toInstant()),
132
+ )
133
+ } else if (dateRange.low is DateTime) {
134
+ high =
135
+ DateParam(
136
+ ParamPrefixEnum.LESSTHAN_OR_EQUALS,
137
+ Date.from((dateRange.high as DateTime).dateTime!!.toInstant()),
138
+ )
139
+ }
140
+ }
141
+ val rangeParam =
142
+ if (high == null && low != null) {
143
+ DateRangeParam(low)
144
+ } else {
145
+ DateRangeParam(low, high)
146
+ }
147
+
148
+ val dateParam =
149
+ this.searchParameterResolver.getSearchParameterDefinition(
150
+ dataType,
151
+ datePath,
152
+ RestSearchParameterTypeEnum.DATE,
153
+ )
154
+
155
+ if (dateParam == null) {
156
+ throw UnsupportedOperationException(
157
+ "Could not resolve a search parameter with date type for $dataType.$datePath "
158
+ )
159
+ }
160
+
161
+ return Pair.of<String, DateRangeParam>(dateParam.name, rangeParam)
162
+ }
163
+
164
+ protected fun getContextParam(
165
+ dataType: String?,
166
+ context: String?,
167
+ contextPath: String?,
168
+ contextValue: String?,
169
+ ): Pair<String, IQueryParameterType>? {
170
+ if (
171
+ context != null && context == "Patient" && contextValue != null && contextPath != null
172
+ ) {
173
+ return this.searchParameterResolver.createSearchParameter(
174
+ context,
175
+ dataType,
176
+ contextPath,
177
+ contextValue,
178
+ )
179
+ }
180
+
181
+ return null
182
+ }
183
+
184
+ protected fun getCodeParams(
185
+ dataType: String?,
186
+ codePath: String?,
187
+ codes: Iterable<Code?>?,
188
+ valueSet: String?,
189
+ ): Pair<String, MutableList<TokenOrListParam>>? {
190
+ var valueSet = valueSet
191
+ if (valueSet != null && valueSet.startsWith("urn:oid:")) {
192
+ valueSet = valueSet.replace("urn:oid:", "")
193
+ }
194
+
195
+ require(!(codePath == null && (codes != null || valueSet != null))) {
196
+ "A code path must be provided when filtering on codes or a valueset."
197
+ }
198
+
199
+ if (codePath == null || codePath.isEmpty()) {
200
+ return null
201
+ }
202
+
203
+ // TODO: This assumes the code path will always be a token param.
204
+ val codeParamLists = this.getCodeParams(codes, valueSet)
205
+ if (codeParamLists.isEmpty()) {
206
+ return null
207
+ }
208
+
209
+ val codeParam =
210
+ this.searchParameterResolver.getSearchParameterDefinition(
211
+ dataType,
212
+ codePath,
213
+ RestSearchParameterTypeEnum.TOKEN,
214
+ )
215
+
216
+ if (codeParam == null) {
217
+ return null
218
+ }
219
+
220
+ return Pair.of<String, MutableList<TokenOrListParam>>(codeParam.name, codeParamLists)
221
+ }
222
+
223
+ // The code params will be either the literal set of codes in the event the data server doesn't
224
+ // have the referenced
225
+ // ValueSet (or doesn't support pulling and caching a ValueSet). If the target server DOES
226
+ // support that then it's
227
+ // "dataType.codePath in ValueSet"
228
+ protected fun getCodeParams(
229
+ codes: Iterable<Code?>?,
230
+ valueSet: String?,
231
+ ): MutableList<TokenOrListParam> {
232
+ var codes = codes
233
+ if (valueSet != null) {
234
+ if (!this.isExpandValueSets) {
235
+ return mutableListOf(
236
+ TokenOrListParam()
237
+ .addOr(TokenParam(valueSet).setModifier(TokenParamModifier.IN))
238
+ )
239
+ } else {
240
+ requireNotNull(terminologyProvider) {
241
+ "Expand value sets cannot be used without a terminology provider and no terminology provider is set."
242
+ }
243
+ val valueSetInfo = ValueSetInfo().withId(valueSet)
244
+ codes = terminologyProvider!!.expand(valueSetInfo)
245
+ }
246
+ }
247
+
248
+ if (codes == null) {
249
+ return mutableListOf()
250
+ }
251
+
252
+ // If the number of queries generated as a result of the code list size and maxCodesPerQuery
253
+ // constraint would
254
+ // result in a number of queries that is greater than the queryBatchThreshold value, then
255
+ // codeParams will
256
+ // be omitted altogether.
257
+ if (this.maxCodesPerQuery != null && this.queryBatchThreshold != null) {
258
+ if (
259
+ (getIterableSize(codes) / this.maxCodesPerQuery!!.toFloat()) >
260
+ this.queryBatchThreshold!!
261
+ ) {
262
+ return mutableListOf()
263
+ }
264
+ }
265
+
266
+ val codeParamsList: MutableList<TokenOrListParam> = mutableListOf()
267
+ var codeParams: TokenOrListParam? = null
268
+ var codeCount = 0
269
+ for (code in codes) {
270
+ if (this.maxCodesPerQuery == null) {
271
+ if (codeCount == 0 && codeParams == null) {
272
+ codeParams = TokenOrListParam()
273
+ }
274
+ } else if (codeCount % this.maxCodesPerQuery!! == 0) {
275
+ if (codeParams != null) {
276
+ codeParamsList.add(codeParams)
277
+ }
278
+
279
+ codeParams = TokenOrListParam()
280
+ }
281
+
282
+ codeCount++
283
+ if (code != null) {
284
+ codeParams!!.addOr(TokenParam(code.system, code.code))
285
+ }
286
+ }
287
+
288
+ if (codeParams != null) {
289
+ codeParamsList.add(codeParams)
290
+ }
291
+
292
+ return codeParamsList
293
+ }
294
+
295
+ protected fun setupQueries(
296
+ context: String?,
297
+ contextPath: String?,
298
+ contextValue: String?,
299
+ dataType: String?,
300
+ templateId: String?,
301
+ codeFilters: MutableList<CodeFilter>?,
302
+ dateFilters: MutableList<DateFilter>?,
303
+ ): MutableList<SearchParameterMap> {
304
+ val templateParam = this.getTemplateParam(dataType, templateId)
305
+
306
+ val contextParam = this.getContextParam(dataType, context, contextPath, contextValue)
307
+
308
+ val dateRangeParams: MutableList<Pair<String, DateRangeParam>> = mutableListOf()
309
+ if (dateFilters != null) {
310
+ for (df in dateFilters) {
311
+ val dateRangeParam =
312
+ this.getDateRangeParam(
313
+ dataType,
314
+ df.datePath,
315
+ df.dateLowPath,
316
+ df.dateHighPath,
317
+ df.dateRange,
318
+ )
319
+ if (dateRangeParam != null) {
320
+ dateRangeParams.add(dateRangeParam)
321
+ }
322
+ }
323
+ }
324
+
325
+ val codeParamList: MutableList<Pair<String, MutableList<TokenOrListParam>>> =
326
+ ArrayList<Pair<String, MutableList<TokenOrListParam>>>()
327
+ if (codeFilters != null) {
328
+ for (cf in codeFilters) {
329
+ val codeParams = this.getCodeParams(dataType, cf.codePath, cf.codes, cf.valueSet)
330
+
331
+ if (codeParams != null) {
332
+ codeParamList.add(codeParams)
333
+ }
334
+ }
335
+ }
336
+
337
+ return this.innerSetupQueries(templateParam, contextParam, dateRangeParams, codeParamList)
338
+ }
339
+
340
+ fun setupQueries(
341
+ context: String?,
342
+ contextPath: String?,
343
+ contextValue: String?,
344
+ dataType: String?,
345
+ templateId: String?,
346
+ codePath: String?,
347
+ codes: Iterable<Code?>?,
348
+ valueSet: String?,
349
+ datePath: String?,
350
+ dateLowPath: String?,
351
+ dateHighPath: String?,
352
+ dateRange: Interval?,
353
+ ): MutableList<SearchParameterMap> {
354
+ return setupQueries(
355
+ context,
356
+ contextPath,
357
+ contextValue,
358
+ dataType,
359
+ templateId,
360
+ if (codePath != null) mutableListOf(CodeFilter(codePath, codes, valueSet)) else null,
361
+ if (datePath != null || dateLowPath != null || dateHighPath != null)
362
+ mutableListOf(DateFilter(datePath, dateLowPath, dateHighPath, dateRange))
363
+ else null,
364
+ )
365
+ }
366
+
367
+ protected fun innerSetupQueries(
368
+ templateParam: Pair<String, IQueryParameterType>?,
369
+ contextParam: Pair<String, IQueryParameterType>?,
370
+ dateRangeParams: MutableList<Pair<String, DateRangeParam>>?,
371
+ codeParams: MutableList<Pair<String, MutableList<TokenOrListParam>>>?,
372
+ ): MutableList<SearchParameterMap> {
373
+ if (codeParams == null || codeParams.isEmpty()) {
374
+ return mutableListOf<SearchParameterMap>(
375
+ this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams)
376
+ )
377
+ }
378
+
379
+ var chunkedCodeParam: Pair<String, MutableList<TokenOrListParam>>? = null
380
+ for (cp in codeParams) {
381
+ if (cp.value != null && cp.value!!.size > 1) {
382
+ require(chunkedCodeParam == null) {
383
+ "Cannot evaluate multiple chunked code filters on ${chunkedCodeParam!!.key} and ${cp.key}"
384
+ }
385
+ chunkedCodeParam = cp
386
+ }
387
+ }
388
+
389
+ if (chunkedCodeParam == null) {
390
+ return mutableListOf(
391
+ this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams)
392
+ )
393
+ }
394
+
395
+ val maps: MutableList<SearchParameterMap> = mutableListOf()
396
+ for (t in chunkedCodeParam.value!!) {
397
+ val base = this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams)
398
+ base.add(chunkedCodeParam.key!!, t)
399
+ maps.add(base)
400
+ }
401
+
402
+ return maps
403
+ }
404
+
405
+ fun getBaseMap(
406
+ templateParam: Pair<String, IQueryParameterType>?,
407
+ contextParam: Pair<String, IQueryParameterType>?,
408
+ dateRangeParams: MutableList<Pair<String, DateRangeParam>>?,
409
+ codeParams: MutableList<Pair<String, MutableList<TokenOrListParam>>>?,
410
+ ): SearchParameterMap {
411
+ val baseMap = SearchParameterMap()
412
+ baseMap.lastUpdated = DateRangeParam()
413
+
414
+ if (this.pageSize != null) {
415
+ baseMap.count = pageSize
416
+ }
417
+
418
+ if (templateParam != null) {
419
+ baseMap.add(templateParam.key!!, templateParam.value)
420
+ }
421
+
422
+ if (dateRangeParams != null) {
423
+ for (drp in dateRangeParams) {
424
+ baseMap.add(drp.key!!, drp.value)
425
+ }
426
+ }
427
+
428
+ if (codeParams != null) {
429
+ for (cp in codeParams) {
430
+ if (cp.value == null || cp.value!!.isEmpty() || cp.value!!.size > 1) {
431
+ // NOTE: Ignores "chunked" code parameters so they don't have to be removed
432
+ continue
433
+ }
434
+ baseMap.add(cp.key!!, cp.value!![0])
435
+ }
436
+ }
437
+
438
+ if (contextParam != null) {
439
+ baseMap.add(contextParam.key!!, contextParam.value)
440
+ }
441
+
442
+ return baseMap
443
+ }
444
+
445
+ companion object {
446
+ protected const val DEFAULT_SHOULD_EXPAND_VALUESETS: Boolean = false
447
+
448
+ private fun getIterableSize(iterable: Iterable<*>): Int {
449
+ if (iterable is MutableCollection<*>) {
450
+ return iterable.size
451
+ }
452
+
453
+ var counter = 0
454
+ for (i in iterable) {
455
+ counter++
456
+ }
457
+ return counter
458
+ }
459
+ }
460
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/CodeFilter.kt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import org.opencds.cqf.cql.engine.runtime.Code
4
+
5
+ class CodeFilter(
6
+ @JvmField val codePath: String?,
7
+ @JvmField val codes: Iterable<Code?>?,
8
+ @JvmField val valueSet: String?,
9
+ )
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/DateFilter.kt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import org.opencds.cqf.cql.engine.runtime.Interval
4
+
5
+ class DateFilter(
6
+ @JvmField val datePath: String?,
7
+ @JvmField val dateLowPath: String?,
8
+ @JvmField val dateHighPath: String?,
9
+ @JvmField val dateRange: Interval?,
10
+ )
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/Dstu3FhirQueryGenerator.kt ADDED
@@ -0,0 +1,215 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+ import java.net.URLDecoder
5
+ import java.time.OffsetDateTime
6
+ import org.hl7.fhir.dstu3.model.CapabilityStatement
7
+ import org.hl7.fhir.dstu3.model.DataRequirement
8
+ import org.hl7.fhir.dstu3.model.DateTimeType
9
+ import org.hl7.fhir.dstu3.model.Duration
10
+ import org.hl7.fhir.dstu3.model.Period
11
+ import org.hl7.fhir.dstu3.model.Reference
12
+ import org.hl7.fhir.instance.model.api.IBaseConformance
13
+ import org.hl7.fhir.instance.model.api.ICompositeType
14
+ import org.opencds.cqf.cql.engine.elm.executing.SubtractEvaluator
15
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
16
+ import org.opencds.cqf.cql.engine.model.ModelResolver
17
+ import org.opencds.cqf.cql.engine.runtime.Code
18
+ import org.opencds.cqf.cql.engine.runtime.Date
19
+ import org.opencds.cqf.cql.engine.runtime.DateTime
20
+ import org.opencds.cqf.cql.engine.runtime.Interval
21
+ import org.opencds.cqf.cql.engine.runtime.Quantity
22
+ import org.opencds.cqf.cql.engine.runtime.Value
23
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
24
+
25
+ class Dstu3FhirQueryGenerator(
26
+ searchParameterResolver: SearchParameterResolver,
27
+ terminologyProvider: TerminologyProvider?,
28
+ modelResolver: ModelResolver,
29
+ ) :
30
+ BaseFhirQueryGenerator(
31
+ searchParameterResolver,
32
+ terminologyProvider,
33
+ modelResolver,
34
+ searchParameterResolver.fhirContext,
35
+ ) {
36
+ override val fhirVersion = FhirVersionEnum.DSTU3
37
+
38
+ override fun generateFhirQueries(
39
+ dataRequirement: ICompositeType?,
40
+ evaluationDateTime: DateTime?,
41
+ contextValues: MutableMap<String, String?>?,
42
+ parameters: MutableMap<String, Value?>?,
43
+ capabilityStatement: IBaseConformance?,
44
+ ): MutableList<String> {
45
+ require(dataRequirement is DataRequirement) {
46
+ "dataRequirement argument must be a DataRequirement"
47
+ }
48
+ require(!(capabilityStatement != null && capabilityStatement !is CapabilityStatement)) {
49
+ "capabilityStatement argument must be a CapabilityStatement"
50
+ }
51
+
52
+ val queries: MutableList<String> = ArrayList()
53
+
54
+ val codeFilters: MutableList<CodeFilter> = ArrayList()
55
+
56
+ if (dataRequirement.hasCodeFilter()) {
57
+ for (codeFilterComponent in dataRequirement.getCodeFilter()) {
58
+ if (!codeFilterComponent.hasPath()) {
59
+ continue
60
+ }
61
+ var codes: MutableList<Code>? = null
62
+ var valueSet: String? = null
63
+
64
+ val codePath = codeFilterComponent.getPath()
65
+
66
+ // TODO: What to do if/when System is not provided...
67
+ if (codeFilterComponent.hasValueCode()) {
68
+ codes = ArrayList()
69
+ val codeFilterValueCode = codeFilterComponent.getValueCode()
70
+ for (codeType in codeFilterValueCode) {
71
+ val code = Code()
72
+ code.code = codeType.asStringValue()
73
+ codes.add(code)
74
+ }
75
+ }
76
+ if (codeFilterComponent.hasValueCoding()) {
77
+ codes = ArrayList()
78
+
79
+ val codeFilterValueCodings = codeFilterComponent.getValueCoding()
80
+ for (coding in codeFilterValueCodings) {
81
+ if (coding.hasCode()) {
82
+ val code = Code()
83
+ code.system = coding.getSystem()
84
+ code.code = coding.getCode()
85
+ codes.add(code)
86
+ }
87
+ }
88
+ }
89
+ if (codeFilterComponent.hasValueCodeableConcept()) {
90
+ val codeFilterValueCodeableConcepts =
91
+ codeFilterComponent.getValueCodeableConcept()
92
+ for (codeableConcept in codeFilterValueCodeableConcepts) {
93
+ val codeFilterValueCodeableConceptCodings = codeableConcept.getCoding()
94
+ for (coding in codeFilterValueCodeableConceptCodings) {
95
+ if (coding.hasCode()) {
96
+ val code = Code()
97
+ code.system = coding.getSystem()
98
+ code.code = coding.getCode()
99
+ codes!!.add(code)
100
+ }
101
+ }
102
+ }
103
+ }
104
+ if (codeFilterComponent.hasValueSet()) {
105
+ if (codeFilterComponent.valueSetReference.getReference() is String) {
106
+ valueSet = (codeFilterComponent.getValueSet() as Reference).getReference()
107
+ } else if (codeFilterComponent.valueSetReference is Reference) {
108
+ valueSet = codeFilterComponent.valueSetReference.getReference()
109
+ }
110
+ }
111
+
112
+ codeFilters.add(CodeFilter(codePath, codes, valueSet))
113
+ }
114
+ }
115
+
116
+ val dateFilters: MutableList<DateFilter> = ArrayList()
117
+
118
+ if (dataRequirement.hasDateFilter()) {
119
+ for (dateFilterComponent in dataRequirement.getDateFilter()) {
120
+ if (!dateFilterComponent.hasPath()) {
121
+ throw UnsupportedOperationException("A path must be provided")
122
+ }
123
+ var dateLowPath: String? = null
124
+ var dateHighPath: String? = null
125
+ var dateRange: Interval? = null
126
+
127
+ val datePath = dateFilterComponent.getPath()
128
+
129
+ // TODO: Deal with the case that the value is expressed as an expression extension
130
+ if (dateFilterComponent.hasValue()) {
131
+ when (val dateFilterValue = dateFilterComponent.getValue()) {
132
+ is DateTimeType if dateFilterValue.hasPrimitiveValue() -> {
133
+ dateLowPath = "valueDateTime"
134
+ dateHighPath = "valueDateTime"
135
+ val offsetDateTimeString = dateFilterValue.valueAsString
136
+ val dateTime = DateTime(OffsetDateTime.parse(offsetDateTimeString))
137
+
138
+ dateRange = Interval(dateTime, true, dateTime, true)
139
+ }
140
+
141
+ is Duration if dateFilterValue.hasValue() -> {
142
+ // If a Duration is specified, the filter will return only those data
143
+ // items that fall within
144
+ // Duration before now.
145
+ val dateFilterAsDuration = dateFilterValue
146
+
147
+ val dateFilterDurationAsCQLQuantity =
148
+ Quantity()
149
+ .withValue(dateFilterAsDuration.getValue())
150
+ .withUnit(dateFilterAsDuration.getUnit())
151
+
152
+ // Passing null as the state argument to the subtract method is fine
153
+ // here since that method only uses the state when it has to convert
154
+ // Quantities with different units which cannot happen here.
155
+ val diff =
156
+ (SubtractEvaluator.subtract(
157
+ evaluationDateTime,
158
+ dateFilterDurationAsCQLQuantity,
159
+ null,
160
+ ) as DateTime?)
161
+
162
+ dateRange = Interval(diff, true, evaluationDateTime, true)
163
+ }
164
+
165
+ is Period if dateFilterValue.hasStart() && dateFilterValue.hasEnd() -> {
166
+ dateLowPath = "valueDateTime"
167
+ dateHighPath = "valueDateTime"
168
+ dateRange =
169
+ Interval(
170
+ Date.fromJavaDate(dateFilterValue.getStart()),
171
+ true,
172
+ Date.fromJavaDate(dateFilterValue.getEnd()),
173
+ true,
174
+ )
175
+ }
176
+ }
177
+
178
+ dateFilters.add(DateFilter(datePath, dateLowPath, dateHighPath, dateRange))
179
+ }
180
+ }
181
+ }
182
+
183
+ // STU3 only supported Patient context
184
+ val contextType = "Patient"
185
+ val contextPath = modelResolver.getContextPath(contextType, dataRequirement.getType())
186
+ val contextValue = contextValues?.get(contextType)
187
+ val templateId =
188
+ if (dataRequirement.getProfile() != null && !dataRequirement.getProfile().isEmpty())
189
+ dataRequirement.getProfile()[0].value
190
+ else null
191
+
192
+ val maps =
193
+ setupQueries(
194
+ contextType,
195
+ contextPath,
196
+ contextValue,
197
+ dataRequirement.getType(),
198
+ templateId,
199
+ codeFilters,
200
+ dateFilters,
201
+ )
202
+
203
+ for (map in maps) {
204
+ val query =
205
+ try {
206
+ URLDecoder.decode(map.toNormalizedQueryString(fhirContext), "UTF-8")
207
+ } catch (ex: Exception) {
208
+ map.toNormalizedQueryString(fhirContext)
209
+ }
210
+ queries.add(dataRequirement.getType() + query)
211
+ }
212
+
213
+ return queries
214
+ }
215
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirBundleCursor.kt ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.rest.client.api.IGenericClient
4
+ import ca.uhn.fhir.util.BundleUtil
5
+ import org.hl7.fhir.instance.model.api.IBaseBundle
6
+ import org.hl7.fhir.instance.model.api.IBaseResource
7
+ import org.opencds.cqf.cql.engine.fhir.exception.UnknownElement
8
+
9
+ class FhirBundleCursor // This constructor filters the bundle based on dataType
10
+ // If templateId is provided, this is a trusted cursor, meaning that it will only return results
11
+ // for resources that declare they conform to the given profile
12
+ @JvmOverloads
13
+ constructor(
14
+ private val fhirClient: IGenericClient,
15
+ private val results: IBaseBundle?,
16
+ private val dataType: String? = null,
17
+ private val templateId: String? = null,
18
+ ) : Iterable<Any?> {
19
+ /**
20
+ * Returns an iterator over elements of type `T`.
21
+ *
22
+ * @return an Iterator.
23
+ */
24
+ override fun iterator(): Iterator<Any?> {
25
+ return FhirBundleIterator(fhirClient, results, dataType, templateId)
26
+ }
27
+
28
+ private inner class FhirBundleIterator(
29
+ private var fhirClient: IGenericClient,
30
+ private var results: IBaseBundle?,
31
+ private var dataType: String?,
32
+ private var templateId: String?,
33
+ ) : Iterator<Any?> {
34
+ private var current: Int
35
+ private var dataTypeClass: Class<out IBaseResource>? = null
36
+ private var currentEntry: MutableList<out IBaseResource>
37
+
38
+ init {
39
+ this.current = -1
40
+
41
+ // Do not test templateId for base resource "profiles"
42
+ if (
43
+ this.templateId != null &&
44
+ this.templateId!!.startsWith(
45
+ "http://hl7.org/fhir/StructureDefinition/$dataType"
46
+ )
47
+ ) {
48
+ this.templateId = null
49
+ }
50
+
51
+ if (dataType != null) {
52
+ this.dataTypeClass =
53
+ this.fhirClient.fhirContext
54
+ .getResourceDefinition(this.dataType)
55
+ .implementingClass
56
+ }
57
+
58
+ this.currentEntry = this.entry
59
+ }
60
+
61
+ /**
62
+ * Returns `true` if the iteration has more elements. (In other words, returns `true` if
63
+ * [.next] would return an element rather than throwing an exception.)
64
+ *
65
+ * @return `true` if the iteration has more elements
66
+ */
67
+ override fun hasNext(): Boolean {
68
+ return current < this.currentEntry.size - 1 || this.link != null
69
+ }
70
+
71
+ val entry: MutableList<out IBaseResource>
72
+ get() {
73
+ return if (this.dataTypeClass != null) {
74
+ val entries: MutableList<out IBaseResource> =
75
+ BundleUtil.toListOfResourcesOfType(
76
+ this.fhirClient.fhirContext,
77
+ this.results,
78
+ this.dataTypeClass,
79
+ )
80
+ if (templateId != null) {
81
+ getTrustedEntries(entries, templateId)
82
+ } else {
83
+ entries
84
+ }
85
+ } else {
86
+ BundleUtil.toListOfResources(this.fhirClient.fhirContext, this.results)
87
+ }
88
+ }
89
+
90
+ fun getTrustedEntries(
91
+ entries: MutableList<out IBaseResource>,
92
+ templateId: String?,
93
+ ): MutableList<out IBaseResource> {
94
+ val trustedEntries: MutableList<IBaseResource> = ArrayList()
95
+ for (entry in entries) {
96
+ if (entry.meta != null && entry.meta.profile != null) {
97
+ for (profile in entry.meta.profile) {
98
+ if (profile.hasValue() && profile.valueAsString == templateId) {
99
+ trustedEntries.add(entry)
100
+ }
101
+ }
102
+ }
103
+ }
104
+ return trustedEntries
105
+ }
106
+
107
+ val link: String?
108
+ get() =
109
+ BundleUtil.getLinkUrlOfType(
110
+ this.fhirClient.fhirContext,
111
+ this.results,
112
+ IBaseBundle.LINK_NEXT,
113
+ )
114
+
115
+ /**
116
+ * Returns the next element in the iteration.
117
+ *
118
+ * @return the next element in the iteration
119
+ * @throws UnknownElement if the iteration has no more elements
120
+ */
121
+ override fun next(): Any {
122
+ current++
123
+ if (current < this.currentEntry.size) {
124
+ return this.currentEntry[current]
125
+ } else {
126
+ this.results = fhirClient.loadPage().next<IBaseBundle?>(results).execute()
127
+ this.currentEntry = this.entry
128
+ current = 0
129
+ if (this.currentEntry.isNotEmpty()) {
130
+ return this.currentEntry[current]
131
+ }
132
+ }
133
+
134
+ // TODO: It would be possible to get here if the next link was present, but the returned
135
+ // page had 0
136
+ // entries...
137
+ // NOTE: This is especially true if the page has only data that is not conformant to the
138
+ // given profile
139
+ throw UnknownElement("The iteration has no more elements.")
140
+ }
141
+ }
142
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirQueryGeneratorFactory.kt ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+ import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException
5
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
6
+ import org.opencds.cqf.cql.engine.model.ModelResolver
7
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
8
+
9
+ object FhirQueryGeneratorFactory {
10
+ /**
11
+ * Creates a FHIR version-specific FhirQueryGenerator
12
+ *
13
+ * @param modelResolver is the model resolver for specific fhir version
14
+ * @param searchParameterResolver the SearchParameterResolver instance the Generator should use
15
+ * @param terminologyProvider the TerminologyProvider instance the Generator should use
16
+ * @return a BaseFhirQueryGenerator
17
+ * @throws IllegalArgumentException if the FHIR version specified is not supported
18
+ */
19
+ @Throws(FhirVersionMisMatchException::class)
20
+ fun create(
21
+ modelResolver: ModelResolver,
22
+ searchParameterResolver: SearchParameterResolver,
23
+ terminologyProvider: TerminologyProvider?,
24
+ ): BaseFhirQueryGenerator {
25
+ return when (val fhirVersionEnum = searchParameterResolver.fhirContext.version.version) {
26
+ FhirVersionEnum.DSTU3 -> {
27
+ Dstu3FhirQueryGenerator(searchParameterResolver, terminologyProvider, modelResolver)
28
+ }
29
+ FhirVersionEnum.R4 -> {
30
+ R4FhirQueryGenerator(searchParameterResolver, terminologyProvider, modelResolver)
31
+ }
32
+ else -> {
33
+ throw IllegalArgumentException(
34
+ "Unsupported FHIR version for FHIR Query Generation: $fhirVersionEnum"
35
+ )
36
+ }
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Creates a FHIR version-specific FhirQueryGenerator
42
+ *
43
+ * @param modelResolver is the model resolver for specific fhir version
44
+ * @param searchParameterResolver the SearchParameterResolver instance the Generator should use
45
+ * @param terminologyProvider the TerminologyProvider instance the Generator should use
46
+ * @param shouldExpandValueSets configuration indicating whether or not ValueSets should be
47
+ * expanded for querying via list of codes as opposed to using the :in modifier.
48
+ * @param maxCodesPerQuery configuration indicating how many codes, at most, should be included
49
+ * on a query string
50
+ * @param pageSize configuration indicating what the _count should be on the query
51
+ * @return a BaseFhirQueryGenerator
52
+ * @throws IllegalArgumentException if the FHIR version specified is not supported
53
+ */
54
+ @Throws(FhirVersionMisMatchException::class)
55
+ fun create(
56
+ modelResolver: ModelResolver,
57
+ searchParameterResolver: SearchParameterResolver,
58
+ terminologyProvider: TerminologyProvider?,
59
+ shouldExpandValueSets: Boolean?,
60
+ maxCodesPerQuery: Int?,
61
+ pageSize: Int?,
62
+ queryBatchThreshold: Int?,
63
+ ): BaseFhirQueryGenerator {
64
+ val baseFhirQueryGenerator =
65
+ create(modelResolver, searchParameterResolver, terminologyProvider)
66
+ if (shouldExpandValueSets != null) {
67
+ baseFhirQueryGenerator.isExpandValueSets = shouldExpandValueSets
68
+ }
69
+ if (maxCodesPerQuery != null) {
70
+ baseFhirQueryGenerator.maxCodesPerQuery = maxCodesPerQuery
71
+ }
72
+ if (queryBatchThreshold != null) {
73
+ baseFhirQueryGenerator.queryBatchThreshold = queryBatchThreshold
74
+ }
75
+ if (pageSize != null) {
76
+ baseFhirQueryGenerator.pageSize = pageSize
77
+ }
78
+
79
+ return baseFhirQueryGenerator
80
+ }
81
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirVersionIntegrityChecker.kt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+ import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException
5
+
6
+ interface FhirVersionIntegrityChecker {
7
+ @Throws(FhirVersionMisMatchException::class)
8
+ fun validateFhirVersionIntegrity(fhirVersion: FhirVersionEnum)
9
+
10
+ val fhirVersion: FhirVersionEnum
11
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/R4FhirQueryGenerator.kt ADDED
@@ -0,0 +1,212 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+ import java.net.URLDecoder
5
+ import java.time.OffsetDateTime
6
+ import org.hl7.fhir.instance.model.api.IBaseConformance
7
+ import org.hl7.fhir.instance.model.api.ICompositeType
8
+ import org.hl7.fhir.r4.model.CapabilityStatement
9
+ import org.hl7.fhir.r4.model.Coding
10
+ import org.hl7.fhir.r4.model.DataRequirement
11
+ import org.hl7.fhir.r4.model.DateTimeType
12
+ import org.hl7.fhir.r4.model.Duration
13
+ import org.hl7.fhir.r4.model.Period
14
+ import org.opencds.cqf.cql.engine.elm.executing.SubtractEvaluator
15
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
16
+ import org.opencds.cqf.cql.engine.model.ModelResolver
17
+ import org.opencds.cqf.cql.engine.runtime.Code
18
+ import org.opencds.cqf.cql.engine.runtime.Date
19
+ import org.opencds.cqf.cql.engine.runtime.DateTime
20
+ import org.opencds.cqf.cql.engine.runtime.Interval
21
+ import org.opencds.cqf.cql.engine.runtime.Quantity
22
+ import org.opencds.cqf.cql.engine.runtime.Value
23
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
24
+
25
+ class R4FhirQueryGenerator(
26
+ searchParameterResolver: SearchParameterResolver,
27
+ terminologyProvider: TerminologyProvider?,
28
+ modelResolver: ModelResolver,
29
+ ) :
30
+ BaseFhirQueryGenerator(
31
+ searchParameterResolver,
32
+ terminologyProvider,
33
+ modelResolver,
34
+ searchParameterResolver.fhirContext,
35
+ ) {
36
+
37
+ override val fhirVersion = FhirVersionEnum.R4
38
+
39
+ override fun generateFhirQueries(
40
+ dataRequirement: ICompositeType?,
41
+ evaluationDateTime: DateTime?,
42
+ contextValues: MutableMap<String, String?>?,
43
+ parameters: MutableMap<String, Value?>?,
44
+ capabilityStatement: IBaseConformance?,
45
+ ): MutableList<String> {
46
+ require(dataRequirement is DataRequirement) {
47
+ "dataRequirement argument must be a DataRequirement"
48
+ }
49
+ require(!(capabilityStatement != null && capabilityStatement !is CapabilityStatement)) {
50
+ "capabilityStatement argument must be a CapabilityStatement"
51
+ }
52
+
53
+ val queries: MutableList<String> = ArrayList()
54
+
55
+ val codeFilters: MutableList<CodeFilter> = ArrayList()
56
+ if (dataRequirement.hasCodeFilter()) {
57
+ for (codeFilterComponent in dataRequirement.getCodeFilter()) {
58
+ if (!codeFilterComponent.hasPath()) continue
59
+ var codes: MutableList<Code>? = null
60
+ var valueSet: String? = null
61
+
62
+ val codePath = codeFilterComponent.getPath()
63
+
64
+ if (codeFilterComponent.hasValueSetElement()) {
65
+ valueSet = codeFilterComponent.getValueSet()
66
+ }
67
+
68
+ if (codeFilterComponent.hasCode()) {
69
+ codes = ArrayList()
70
+
71
+ val codeFilterValueCodings = codeFilterComponent.getCode()
72
+ for (coding in codeFilterValueCodings) {
73
+ if (coding.hasCode()) {
74
+ val code = Code()
75
+ code.system = coding.getSystem()
76
+ code.code = coding.getCode()
77
+ codes.add(code)
78
+ }
79
+ }
80
+ }
81
+
82
+ codeFilters.add(CodeFilter(codePath, codes, valueSet))
83
+ }
84
+ }
85
+
86
+ val dateFilters: MutableList<DateFilter> = ArrayList()
87
+
88
+ if (dataRequirement.hasDateFilter()) {
89
+ for (dateFilterComponent in dataRequirement.getDateFilter()) {
90
+ var datePath: String? = null
91
+ var dateLowPath: String? = null
92
+ var dateHighPath: String? = null
93
+ var dateRange: Interval? = null
94
+
95
+ if (dateFilterComponent.hasPath() && dateFilterComponent.hasSearchParam()) {
96
+ throw UnsupportedOperationException(
97
+ "Either a path or a searchParam must be provided, but not both"
98
+ )
99
+ }
100
+
101
+ if (dateFilterComponent.hasPath()) {
102
+ datePath = dateFilterComponent.getPath()
103
+ } else if (dateFilterComponent.hasSearchParam()) {
104
+ datePath = dateFilterComponent.getSearchParam()
105
+ }
106
+
107
+ // TODO: Deal with the case that the value is expressed as an expression extension
108
+ if (dateFilterComponent.hasValue()) {
109
+ when (val dateFilterValue = dateFilterComponent.getValue()) {
110
+ is DateTimeType if dateFilterValue.hasPrimitiveValue() -> {
111
+ dateLowPath = "valueDateTime"
112
+ dateHighPath = "valueDateTime"
113
+ val offsetDateTimeString = dateFilterValue.valueAsString
114
+ val dateTime = DateTime(OffsetDateTime.parse(offsetDateTimeString))
115
+
116
+ dateRange = Interval(dateTime, true, dateTime, true)
117
+ }
118
+
119
+ is Duration if dateFilterValue.hasValue() -> {
120
+ // If a Duration is specified, the filter will return only those data
121
+ // items that fall within
122
+ // Duration before now.
123
+ val dateFilterAsDuration = dateFilterValue
124
+
125
+ val dateFilterDurationAsCQLQuantity =
126
+ Quantity()
127
+ .withValue(dateFilterAsDuration.getValue())
128
+ .withUnit(dateFilterAsDuration.getUnit())
129
+
130
+ // Passing null as the state argument to the subtract method is fine
131
+ // here since that method only uses the state when it has to convert
132
+ // Quantities with different units which cannot happen here.
133
+ val diff =
134
+ (SubtractEvaluator.subtract(
135
+ evaluationDateTime,
136
+ dateFilterDurationAsCQLQuantity,
137
+ null,
138
+ ) as DateTime?)
139
+
140
+ dateRange = Interval(diff, true, evaluationDateTime, true)
141
+ }
142
+
143
+ is Period if dateFilterValue.hasStart() && dateFilterValue.hasEnd() -> {
144
+ dateLowPath = "valueDateTime"
145
+ dateHighPath = "valueDateTime"
146
+ dateRange =
147
+ Interval(
148
+ Date.fromJavaDate(dateFilterValue.getStart()),
149
+ true,
150
+ Date.fromJavaDate(dateFilterValue.getEnd()),
151
+ true,
152
+ )
153
+ }
154
+ }
155
+
156
+ dateFilters.add(DateFilter(datePath, dateLowPath, dateHighPath, dateRange))
157
+ }
158
+ }
159
+ }
160
+
161
+ // Patient is the default context if one is not specified
162
+ var contextType: String? = "Patient"
163
+
164
+ require(!dataRequirement.hasSubjectReference()) {
165
+ "Cannot process data requirements with subjects specified as references"
166
+ }
167
+
168
+ if (dataRequirement.hasSubjectCodeableConcept()) {
169
+ var c: Coding? = null
170
+ for (coding in dataRequirement.subjectCodeableConcept.getCoding()) {
171
+ if ("http://hl7.org/fhir/resource-types" == coding.getSystem()) {
172
+ c = coding
173
+ break
174
+ }
175
+ }
176
+ requireNotNull(c) {
177
+ "Cannot process data requirements with subjects not specified using a code from http://hl7.org/fhir/resource-types"
178
+ }
179
+ contextType = c.getCode()
180
+ }
181
+
182
+ val contextPath = modelResolver.getContextPath(contextType, dataRequirement.getType())
183
+ val contextValue = contextValues?.get(contextType)
184
+ val templateId =
185
+ if (dataRequirement.getProfile() != null && !dataRequirement.getProfile().isEmpty())
186
+ dataRequirement.getProfile()[0].value
187
+ else null
188
+
189
+ val maps =
190
+ setupQueries(
191
+ contextType,
192
+ contextPath,
193
+ contextValue,
194
+ dataRequirement.getType(),
195
+ templateId,
196
+ codeFilters,
197
+ dateFilters,
198
+ )
199
+
200
+ for (map in maps) {
201
+ val query =
202
+ try {
203
+ URLDecoder.decode(map.toNormalizedQueryString(fhirContext), "UTF-8")
204
+ } catch (ex: Exception) {
205
+ map.toNormalizedQueryString(fhirContext)
206
+ }
207
+ queries.add(dataRequirement.getType() + query)
208
+ }
209
+
210
+ return queries
211
+ }
212
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/RestFhirRetrieveProvider.kt ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirVersionEnum
4
+ import ca.uhn.fhir.model.api.IQueryParameterType
5
+ import ca.uhn.fhir.rest.api.SearchStyleEnum
6
+ import ca.uhn.fhir.rest.client.api.IGenericClient
7
+ import ca.uhn.fhir.rest.gclient.TokenClientParam
8
+ import ca.uhn.fhir.rest.param.TokenParam
9
+ import java.util.function.BiFunction
10
+ import java.util.function.Consumer
11
+ import org.hl7.fhir.dstu3.model.Coding
12
+ import org.hl7.fhir.instance.model.api.IBaseBundle
13
+ import org.hl7.fhir.instance.model.api.IBaseCoding
14
+ import org.hl7.fhir.instance.model.api.IBaseResource
15
+ import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver
16
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap
17
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
18
+
19
+ class RestFhirRetrieveProvider(
20
+ searchParameterResolver: SearchParameterResolver,
21
+ modelResolver: FhirModelResolver<*, *, *, *, *, *, *, *>,
22
+ private val fhirClient: IGenericClient,
23
+ ) : SearchParamFhirRetrieveProvider(searchParameterResolver, modelResolver) {
24
+ var searchStyle: SearchStyleEnum = DEFAULT_SEARCH_STYLE
25
+
26
+ override fun executeQueries(
27
+ dataType: String?,
28
+ queries: MutableList<SearchParameterMap>,
29
+ ): Iterable<Any?> {
30
+ if (queries.isEmpty()) {
31
+ return mutableListOf()
32
+ }
33
+
34
+ val objects: MutableList<Any?> = ArrayList()
35
+ val bundles: MutableList<IBaseBundle?> = ArrayList()
36
+ for (map in queries) {
37
+ val result = this.executeQuery(dataType, map)
38
+ if (result is IBaseBundle) {
39
+ bundles.add(result)
40
+ } else {
41
+ objects.add(result)
42
+ }
43
+ }
44
+
45
+ // TODO: evaluate this lazily in case the engine only needs the first element
46
+ for (b in bundles) {
47
+ val cursor = FhirBundleCursor(fhirClient, b, dataType)
48
+ cursor.forEach(Consumer { e: Any? -> objects.add(e) })
49
+ }
50
+
51
+ return objects
52
+ }
53
+
54
+ private fun executeQuery(dataType: String?, map: SearchParameterMap): IBaseResource? {
55
+ if (map.containsKey("_id")) {
56
+ return this.queryById(dataType, map)
57
+ } else {
58
+ var search = this.fhirClient.search<IBaseBundle?>().forResource(dataType)
59
+
60
+ val flattenedMap: MutableMap<String, MutableList<IQueryParameterType>> = mutableMapOf()
61
+ for (entry in map.entrySet()) {
62
+ val name: String = entry.key
63
+
64
+ val value: MutableList<MutableList<IQueryParameterType>> = entry.value
65
+ if (value.isEmpty()) {
66
+ continue
67
+ }
68
+
69
+ val flattened: MutableList<IQueryParameterType> = ArrayList()
70
+
71
+ for (subList in value) {
72
+ if (subList.isEmpty()) {
73
+ continue
74
+ }
75
+
76
+ if (subList.size == 1) {
77
+ flattened.add(subList[0])
78
+ continue
79
+ }
80
+
81
+ // Sublists are logical "Ors"
82
+ // The only "Or" supported from the engine are tokens at the moment.
83
+ // So this is a hack to add them to a "criterion", which is the
84
+ // only way the HAPI POST api supports passing them.
85
+ val first = subList[0]
86
+ if (first is TokenParam) {
87
+ val tcp = TokenClientParam(name)
88
+
89
+ val codings = this.toCodings(subList)
90
+
91
+ val criterion = tcp.exactly().codings(*codings)
92
+
93
+ search = search.where(criterion)
94
+ } else {
95
+ flattened.addAll(subList)
96
+ }
97
+ }
98
+
99
+ flattenedMap[name] = flattened
100
+ }
101
+
102
+ if (pageSize != null) {
103
+ search.count(pageSize!!)
104
+ }
105
+
106
+ return search.where(flattenedMap).usingStyle(this.searchStyle).execute()
107
+ }
108
+ }
109
+
110
+ private fun queryById(dataType: String?, map: SearchParameterMap): IBaseResource? {
111
+ require(map.entrySet().size <= 1) {
112
+ "Error querying $dataType. Queries by id must not have any other search criteria."
113
+ }
114
+
115
+ val tokenList: MutableList<IQueryParameterType> = map.get("_id")!![0]
116
+ require(!tokenList.isEmpty()) {
117
+ "Error querying $dataType. Attempted query by id but no id was specified."
118
+ }
119
+
120
+ require(tokenList.size <= 1) {
121
+ "Error querying $dataType. Attempted query by id but multiple ids were specified."
122
+ }
123
+
124
+ val param = tokenList[0]
125
+ require(param is TokenParam) {
126
+ "Error querying $dataType. Attempted query by id but a non-token parameter was given."
127
+ }
128
+
129
+ val id = param.value
130
+
131
+ requireNotNull(id) { "Error querying $dataType. Attempted query by id but id was null." }
132
+
133
+ return queryById(dataType, id)
134
+ }
135
+
136
+ private fun queryById(dataType: String?, id: String?): IBaseResource? {
137
+ return this.fhirClient.read().resource(dataType).withId(id).execute()
138
+ }
139
+
140
+ private fun toCodings(codingList: MutableList<IQueryParameterType>): Array<IBaseCoding> {
141
+ val codings: MutableList<IBaseCoding> = ArrayList()
142
+
143
+ val codingConverter =
144
+ when (this.fhirClient.fhirContext.version.version) {
145
+ FhirVersionEnum.DSTU3 ->
146
+ BiFunction { system: String?, code: String? -> Coding(system, code, null) }
147
+ FhirVersionEnum.R4 ->
148
+ BiFunction { system: String?, code: String? ->
149
+ org.hl7.fhir.r4.model.Coding(system, code, null)
150
+ }
151
+ else -> throw IllegalArgumentException("Unhandled FHIR version")
152
+ }
153
+
154
+ for (param in codingList) {
155
+ val token = param as TokenParam
156
+
157
+ val coding = codingConverter.apply(token.system, token.value)
158
+
159
+ codings.add(coding)
160
+ }
161
+
162
+ return codings.toTypedArray()
163
+ }
164
+
165
+ companion object {
166
+ private val DEFAULT_SEARCH_STYLE = SearchStyleEnum.GET
167
+ }
168
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/SearchParamFhirRetrieveProvider.kt ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.retrieve
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException
6
+ import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver
7
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap
8
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
9
+ import org.opencds.cqf.cql.engine.retrieve.TerminologyAwareRetrieveProvider
10
+ import org.opencds.cqf.cql.engine.runtime.Code
11
+ import org.opencds.cqf.cql.engine.runtime.Interval
12
+ import org.opencds.cqf.cql.engine.runtime.Value
13
+
14
+ abstract class SearchParamFhirRetrieveProvider
15
+ protected constructor(
16
+ val searchParameterResolver: SearchParameterResolver,
17
+ val modelResolver: FhirModelResolver<*, *, *, *, *, *, *, *>,
18
+ ) : TerminologyAwareRetrieveProvider() {
19
+ protected val fhirContext: FhirContext
20
+ get() = searchParameterResolver.fhirContext
21
+
22
+ var fhirQueryGenerator: BaseFhirQueryGenerator? = null
23
+
24
+ var pageSize: Int? = null
25
+ set(value) {
26
+ require(value == null || value > 0) { "value must be a non-null integer > 0" }
27
+ field = value
28
+ }
29
+
30
+ var maxCodesPerQuery: Int? = null
31
+ set(value) {
32
+ require(value != null && value >= 1) { "value must be a non-null integer > 0" }
33
+ field = value
34
+ }
35
+
36
+ var queryBatchThreshold: Int? = null
37
+ set(value) {
38
+ require(value != null && value >= 1) { "value must be a non-null integer > 0" }
39
+ field = value
40
+ }
41
+
42
+ protected abstract fun executeQueries(
43
+ dataType: String?,
44
+ queries: MutableList<SearchParameterMap>,
45
+ ): Iterable<Any?>?
46
+
47
+ override fun retrieve(
48
+ context: String?,
49
+ contextPath: String?,
50
+ contextValue: String?,
51
+ dataType: String,
52
+ templateId: String?,
53
+ codePath: String?,
54
+ codes: Iterable<Code>?,
55
+ valueSet: String?,
56
+ datePath: String?,
57
+ dateLowPath: String?,
58
+ dateHighPath: String?,
59
+ dateRange: Interval?,
60
+ ): Iterable<Value?>? {
61
+
62
+ try {
63
+ if (this.fhirContext.version.version == FhirVersionEnum.DSTU3) {
64
+ fhirQueryGenerator =
65
+ Dstu3FhirQueryGenerator(
66
+ searchParameterResolver,
67
+ terminologyProvider,
68
+ this.modelResolver,
69
+ )
70
+ } else if (this.fhirContext.version.version == FhirVersionEnum.R4) {
71
+ fhirQueryGenerator =
72
+ R4FhirQueryGenerator(
73
+ searchParameterResolver,
74
+ terminologyProvider,
75
+ this.modelResolver,
76
+ )
77
+ }
78
+ } catch (exception: FhirVersionMisMatchException) {
79
+ throw RuntimeException(exception.message)
80
+ }
81
+ fhirQueryGenerator!!.isExpandValueSets = isExpandValueSets
82
+
83
+ if (maxCodesPerQuery != null) {
84
+ fhirQueryGenerator!!.maxCodesPerQuery = maxCodesPerQuery
85
+ }
86
+ if (queryBatchThreshold != null) {
87
+ fhirQueryGenerator!!.queryBatchThreshold = queryBatchThreshold
88
+ }
89
+ if (pageSize != null) {
90
+ fhirQueryGenerator!!.pageSize = pageSize
91
+ }
92
+
93
+ val queries =
94
+ fhirQueryGenerator!!.setupQueries(
95
+ context,
96
+ contextPath,
97
+ contextValue,
98
+ dataType,
99
+ templateId,
100
+ codePath,
101
+ codes,
102
+ valueSet,
103
+ datePath,
104
+ dateLowPath,
105
+ dateHighPath,
106
+ dateRange,
107
+ )
108
+
109
+ return this.executeQueries(dataType, queries)?.map { modelResolver.toCqlValue(it) }
110
+ }
111
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterMap.kt ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.searchparam
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.model.api.IQueryParameterAnd
5
+ import ca.uhn.fhir.model.api.IQueryParameterOr
6
+ import ca.uhn.fhir.model.api.IQueryParameterType
7
+ import ca.uhn.fhir.model.api.Include
8
+ import ca.uhn.fhir.rest.api.Constants
9
+ import ca.uhn.fhir.rest.api.SearchTotalModeEnum
10
+ import ca.uhn.fhir.rest.api.SortOrderEnum
11
+ import ca.uhn.fhir.rest.api.SortSpec
12
+ import ca.uhn.fhir.rest.api.SummaryEnum
13
+ import ca.uhn.fhir.rest.param.DateParam
14
+ import ca.uhn.fhir.rest.param.DateRangeParam
15
+ import ca.uhn.fhir.rest.param.QuantityParam
16
+ import ca.uhn.fhir.util.UrlUtil
17
+ import java.io.Serializable
18
+ import org.apache.commons.lang3.StringUtils
19
+ import org.apache.commons.lang3.Validate
20
+ import org.apache.commons.lang3.builder.ToStringBuilder
21
+ import org.apache.commons.lang3.builder.ToStringStyle
22
+ import org.slf4j.Logger
23
+ import org.slf4j.LoggerFactory
24
+
25
+ // This class was copied from package ca.uhn.fhir.jpa.searchparam.SearchParameterMap
26
+ // It included many unnecessary HAPI FHIR server dependencies.
27
+ // Justification for these suppressions: this is a copy of hapi-fhir code.
28
+ class SearchParameterMap : Serializable {
29
+ private val mySearchParameterMap:
30
+ MutableMap<String, MutableList<MutableList<IQueryParameterType>>> =
31
+ mutableMapOf()
32
+
33
+ var count: Int? = null
34
+ var everythingMode: EverythingModeEnum? = null
35
+ private var myIncludes: MutableSet<Include>? = null
36
+ private var myLastUpdated: DateRangeParam? = null
37
+ var isLoadSynchronous: Boolean = false
38
+ private set
39
+
40
+ var loadSynchronousUpTo: Int? = null
41
+ private set
42
+
43
+ private var myRevIncludes: MutableSet<Include>? = null
44
+ var sort: SortSpec? = null
45
+ var summaryMode: SummaryEnum? = null
46
+ var searchTotalMode: SearchTotalModeEnum? = null
47
+
48
+ constructor() : super()
49
+
50
+ constructor(theName: String, theParam: IQueryParameterType?) {
51
+ add(theName, theParam)
52
+ }
53
+
54
+ fun add(theName: String, theDateParam: DateParam?): SearchParameterMap {
55
+ add(theName, theDateParam as IQueryParameterOr<*>?)
56
+ return this
57
+ }
58
+
59
+ fun add(theName: String, theAnd: IQueryParameterAnd<*>?) {
60
+ if (theAnd == null) {
61
+ return
62
+ }
63
+ if (!containsKey(theName)) {
64
+ put(theName, mutableListOf())
65
+ }
66
+
67
+ for (next in theAnd.getValuesAsQueryTokens()) {
68
+ if (next == null) {
69
+ continue
70
+ }
71
+
72
+ get(theName)!!.add((next.getValuesAsQueryTokens() as MutableList<IQueryParameterType>))
73
+ }
74
+ }
75
+
76
+ fun add(theName: String, theOr: IQueryParameterOr<*>?) {
77
+ if (theOr == null) {
78
+ return
79
+ }
80
+ if (!containsKey(theName)) {
81
+ put(theName, mutableListOf())
82
+ }
83
+
84
+ get(theName)!!.add((theOr.getValuesAsQueryTokens() as MutableList<IQueryParameterType>))
85
+ }
86
+
87
+ fun values(): Collection<MutableList<MutableList<IQueryParameterType>>> {
88
+ return mySearchParameterMap.values
89
+ }
90
+
91
+ fun add(theName: String, theParam: IQueryParameterType?): SearchParameterMap {
92
+ assert(
93
+ Constants.PARAM_LASTUPDATED != theName // this has it's own field in the map
94
+ )
95
+
96
+ if (theParam == null) {
97
+ return this
98
+ }
99
+ if (!containsKey(theName)) {
100
+ put(theName, mutableListOf())
101
+ }
102
+ val list = ArrayList<IQueryParameterType>()
103
+ list.add(theParam)
104
+ get(theName)!!.add(list)
105
+
106
+ return this
107
+ }
108
+
109
+ fun addInclude(theInclude: Include) {
110
+ this.includes.add(theInclude)
111
+ }
112
+
113
+ private fun addLastUpdateParam(b: StringBuilder, date: DateParam?) {
114
+ if (date != null && StringUtils.isNotBlank(date.valueAsString)) {
115
+ addUrlParamSeparator(b)
116
+ b.append(Constants.PARAM_LASTUPDATED)
117
+ b.append('=')
118
+ b.append(date.valueAsString)
119
+ }
120
+ }
121
+
122
+ fun addRevInclude(theInclude: Include) {
123
+ this.revIncludes.add(theInclude)
124
+ }
125
+
126
+ private fun addUrlIncludeParams(
127
+ b: StringBuilder,
128
+ paramName: String?,
129
+ theList: MutableSet<Include>,
130
+ ) {
131
+ val list = theList.toMutableList()
132
+
133
+ list.sortWith(IncludeComparator())
134
+ for (nextInclude in list) {
135
+ addUrlParamSeparator(b)
136
+ b.append(paramName)
137
+ b.append('=')
138
+ b.append(UrlUtil.escapeUrlParam(nextInclude.paramType))
139
+ b.append(':')
140
+ b.append(UrlUtil.escapeUrlParam(nextInclude.paramName))
141
+ if (StringUtils.isNotBlank(nextInclude.paramTargetType)) {
142
+ b.append(':')
143
+ b.append(nextInclude.paramTargetType)
144
+ }
145
+ }
146
+ }
147
+
148
+ private fun addUrlParamSeparator(theB: StringBuilder) {
149
+ if (theB.isEmpty()) {
150
+ theB.append('?')
151
+ } else {
152
+ theB.append('&')
153
+ }
154
+ }
155
+
156
+ var includes: MutableSet<Include>
157
+ get() {
158
+ if (myIncludes == null) {
159
+ myIncludes = mutableSetOf()
160
+ }
161
+ return myIncludes!!
162
+ }
163
+ set(theIncludes) {
164
+ myIncludes = theIncludes
165
+ }
166
+
167
+ var lastUpdated: DateRangeParam?
168
+ get() {
169
+ if (myLastUpdated != null) {
170
+ if (myLastUpdated!!.isEmpty) {
171
+ myLastUpdated = null
172
+ }
173
+ }
174
+ return myLastUpdated
175
+ }
176
+ set(theLastUpdated) {
177
+ myLastUpdated = theLastUpdated
178
+ }
179
+
180
+ fun setLoadSynchronousUpTo(theLoadSynchronousUpTo: Int?): SearchParameterMap {
181
+ this.loadSynchronousUpTo = theLoadSynchronousUpTo
182
+ if (this.loadSynchronousUpTo != null) {
183
+ setLoadSynchronous(true)
184
+ }
185
+ return this
186
+ }
187
+
188
+ var revIncludes: MutableSet<Include>
189
+ get() {
190
+ if (myRevIncludes == null) {
191
+ myRevIncludes = mutableSetOf()
192
+ }
193
+ return myRevIncludes!!
194
+ }
195
+ set(theRevIncludes) {
196
+ myRevIncludes = theRevIncludes
197
+ }
198
+
199
+ val isAllParametersHaveNoModifier: Boolean
200
+ get() {
201
+ for (nextParamName in values()) {
202
+ for (nextAnd in nextParamName) {
203
+ for (nextOr in nextAnd) {
204
+ if (StringUtils.isNotBlank(nextOr.queryParameterQualifier)) {
205
+ return false
206
+ }
207
+ }
208
+ }
209
+ }
210
+ return true
211
+ }
212
+
213
+ fun setLoadSynchronous(theLoadSynchronous: Boolean): SearchParameterMap {
214
+ this.isLoadSynchronous = theLoadSynchronous
215
+ return this
216
+ }
217
+
218
+ fun toNormalizedQueryString(theCtx: FhirContext): String {
219
+ val b = StringBuilder()
220
+
221
+ val keys = keySet().sorted()
222
+ for (nextKey in keys) {
223
+ val nextValuesAndsIn = get(nextKey)!!
224
+ val nextValuesAndsOut: MutableList<MutableList<IQueryParameterType>> = mutableListOf()
225
+ for (nextValuesAndIn in nextValuesAndsIn) {
226
+ val nextValuesOrsOut: MutableList<IQueryParameterType> = mutableListOf()
227
+ for (nextValueOrIn in nextValuesAndIn) {
228
+ if (
229
+ nextValueOrIn.missing != null ||
230
+ StringUtils.isNotBlank(nextValueOrIn.getValueAsQueryToken(theCtx))
231
+ ) {
232
+ nextValuesOrsOut.add(nextValueOrIn)
233
+ }
234
+ }
235
+
236
+ nextValuesOrsOut.sortWith(QueryParameterTypeComparator(theCtx))
237
+
238
+ if (nextValuesOrsOut.isNotEmpty()) {
239
+ nextValuesAndsOut.add(nextValuesOrsOut)
240
+ }
241
+ } // for AND
242
+
243
+ nextValuesAndsOut.sortWith(QueryParameterOrComparator(theCtx))
244
+
245
+ for (nextValuesAnd in nextValuesAndsOut) {
246
+ addUrlParamSeparator(b)
247
+ val firstValue: IQueryParameterType = nextValuesAnd[0]
248
+ b.append(UrlUtil.escapeUrlParam(nextKey))
249
+
250
+ if (nextKey == Constants.PARAM_HAS) {
251
+ b.append(':')
252
+ }
253
+
254
+ if (firstValue.missing != null) {
255
+ b.append(Constants.PARAMQUALIFIER_MISSING)
256
+ b.append('=')
257
+ if (firstValue.missing) {
258
+ b.append(Constants.PARAMQUALIFIER_MISSING_TRUE)
259
+ } else {
260
+ b.append(Constants.PARAMQUALIFIER_MISSING_FALSE)
261
+ }
262
+ continue
263
+ }
264
+
265
+ if (StringUtils.isNotBlank(firstValue.queryParameterQualifier)) {
266
+ b.append(firstValue.queryParameterQualifier)
267
+ }
268
+
269
+ b.append('=')
270
+
271
+ for (i in nextValuesAnd.indices) {
272
+ val nextValueOr: IQueryParameterType = nextValuesAnd[i]
273
+ if (i > 0) {
274
+ b.append(',')
275
+ }
276
+ val valueAsQueryToken = nextValueOr.getValueAsQueryToken(theCtx)
277
+ b.append(UrlUtil.escapeUrlParam(valueAsQueryToken))
278
+ }
279
+ }
280
+ } // for keys
281
+
282
+ var sort = this.sort
283
+ var first = true
284
+ while (sort != null) {
285
+ if (StringUtils.isNotBlank(sort.paramName)) {
286
+ if (first) {
287
+ addUrlParamSeparator(b)
288
+ b.append(Constants.PARAM_SORT)
289
+ b.append('=')
290
+ first = false
291
+ } else {
292
+ b.append(',')
293
+ }
294
+ if (sort.order == SortOrderEnum.DESC) {
295
+ b.append('-')
296
+ }
297
+ b.append(sort.paramName)
298
+ }
299
+
300
+ Validate.isTrue(sort !== sort.chain) // just in case, shouldn't happen
301
+ sort = sort.chain
302
+ }
303
+
304
+ addUrlIncludeParams(b, Constants.PARAM_INCLUDE, this.includes)
305
+ addUrlIncludeParams(b, Constants.PARAM_REVINCLUDE, this.revIncludes)
306
+
307
+ if (this.lastUpdated != null) {
308
+ val lb = this.lastUpdated!!.lowerBound
309
+ addLastUpdateParam(b, lb)
310
+ val ub = this.lastUpdated!!.upperBound
311
+ addLastUpdateParam(b, ub)
312
+ }
313
+
314
+ if (this.count != null) {
315
+ addUrlParamSeparator(b)
316
+ b.append(Constants.PARAM_COUNT)
317
+ b.append('=')
318
+ b.append(this.count)
319
+ }
320
+
321
+ // Summary mode (_summary)
322
+ if (this.summaryMode != null) {
323
+ addUrlParamSeparator(b)
324
+ b.append(Constants.PARAM_SUMMARY)
325
+ b.append('=')
326
+ b.append(this.summaryMode!!.code)
327
+ }
328
+
329
+ // Search count mode (_total)
330
+ if (this.searchTotalMode != null) {
331
+ addUrlParamSeparator(b)
332
+ b.append(Constants.PARAM_SEARCH_TOTAL_MODE)
333
+ b.append('=')
334
+ b.append(this.searchTotalMode!!.code)
335
+ }
336
+
337
+ if (b.isEmpty()) {
338
+ b.append('?')
339
+ }
340
+
341
+ return b.toString()
342
+ }
343
+
344
+ override fun toString(): String {
345
+ val b = ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE)
346
+ if (!this.isEmpty) {
347
+ b.append("params", mySearchParameterMap)
348
+ }
349
+ if (!this.includes.isEmpty()) {
350
+ b.append("includes", this.includes)
351
+ }
352
+ return b.toString()
353
+ }
354
+
355
+ fun clean() {
356
+ for (nextParamEntry in this.entrySet()) {
357
+ val nextParamName = nextParamEntry.key
358
+ val andOrParams: MutableList<MutableList<IQueryParameterType>> = nextParamEntry.value
359
+ clean(nextParamName, andOrParams)
360
+ }
361
+ }
362
+
363
+ private fun clean(
364
+ theParamName: String?,
365
+ theAndOrParams: MutableList<MutableList<IQueryParameterType>>,
366
+ ) {
367
+ var andListIdx = 0
368
+ while (andListIdx < theAndOrParams.size) {
369
+ val nextOrList: MutableList<out IQueryParameterType> = theAndOrParams[andListIdx]
370
+
371
+ var orListIdx = 0
372
+ while (orListIdx < nextOrList.size) {
373
+ val nextOr: IQueryParameterType = nextOrList[orListIdx]
374
+ var hasNoValue = false
375
+ if (nextOr.missing != null) {
376
+ orListIdx++
377
+ continue
378
+ }
379
+ if (nextOr is QuantityParam) {
380
+ if (StringUtils.isBlank(nextOr.valueAsString)) {
381
+ hasNoValue = true
382
+ }
383
+ }
384
+
385
+ if (hasNoValue) {
386
+ ourLog.debug("Ignoring empty parameter: {}", theParamName)
387
+ nextOrList.removeAt(orListIdx)
388
+ orListIdx--
389
+ }
390
+ orListIdx++
391
+ }
392
+
393
+ if (nextOrList.isEmpty()) {
394
+ theAndOrParams.removeAt(andListIdx)
395
+ andListIdx--
396
+ }
397
+ andListIdx++
398
+ }
399
+ }
400
+
401
+ enum class EverythingModeEnum(
402
+ thePatient: Boolean,
403
+ theEncounter: Boolean,
404
+ theInstance: Boolean,
405
+ ) {
406
+ ENCOUNTER_INSTANCE(false, true, true),
407
+ ENCOUNTER_TYPE(false, true, false),
408
+ PATIENT_INSTANCE(true, false, true),
409
+ PATIENT_TYPE(true, false, false);
410
+
411
+ val isEncounter: Boolean
412
+
413
+ val isInstance: Boolean
414
+
415
+ val isPatient: Boolean
416
+
417
+ init {
418
+ assert(thePatient xor theEncounter)
419
+ this.isPatient = thePatient
420
+ this.isEncounter = theEncounter
421
+ this.isInstance = theInstance
422
+ }
423
+ }
424
+
425
+ class IncludeComparator : Comparator<Include> {
426
+ override fun compare(theO1: Include, theO2: Include): Int {
427
+ var retVal = StringUtils.compare(theO1.paramType, theO2.paramType)
428
+ if (retVal == 0) {
429
+ retVal = StringUtils.compare(theO1.paramName, theO2.paramName)
430
+ }
431
+ if (retVal == 0) {
432
+ retVal = StringUtils.compare(theO1.paramTargetType, theO2.paramTargetType)
433
+ }
434
+ return retVal
435
+ }
436
+ }
437
+
438
+ class QueryParameterOrComparator internal constructor(private val myCtx: FhirContext) :
439
+ Comparator<MutableList<IQueryParameterType>> {
440
+ override fun compare(
441
+ theO1: MutableList<IQueryParameterType>,
442
+ theO2: MutableList<IQueryParameterType>,
443
+ ): Int {
444
+ // These lists will never be empty
445
+ return compare(myCtx, theO1[0], theO2[0])
446
+ }
447
+ }
448
+
449
+ class QueryParameterTypeComparator internal constructor(private val myCtx: FhirContext) :
450
+ Comparator<IQueryParameterType> {
451
+ override fun compare(theO1: IQueryParameterType, theO2: IQueryParameterType): Int {
452
+ return compare(myCtx, theO1, theO2)
453
+ }
454
+ }
455
+
456
+ // Wrapper methods
457
+ fun get(theName: String): MutableList<MutableList<IQueryParameterType>>? {
458
+ return mySearchParameterMap[theName]
459
+ }
460
+
461
+ private fun put(theName: String, theParams: MutableList<MutableList<IQueryParameterType>>) {
462
+ mySearchParameterMap[theName] = theParams
463
+ }
464
+
465
+ fun containsKey(theName: String?): Boolean {
466
+ return mySearchParameterMap.containsKey(theName)
467
+ }
468
+
469
+ fun keySet(): Set<String> {
470
+ return mySearchParameterMap.keys
471
+ }
472
+
473
+ val isEmpty: Boolean
474
+ get() = mySearchParameterMap.isEmpty()
475
+
476
+ fun entrySet(): Set<Map.Entry<String, MutableList<MutableList<IQueryParameterType>>>> {
477
+ return mySearchParameterMap.entries
478
+ }
479
+
480
+ fun remove(theName: String): MutableList<MutableList<IQueryParameterType>>? {
481
+ return mySearchParameterMap.remove(theName)
482
+ }
483
+
484
+ companion object {
485
+ private val ourLog: Logger = LoggerFactory.getLogger(SearchParameterMap::class.java)
486
+
487
+ private const val serialVersionUID = 1L
488
+
489
+ private fun compare(
490
+ theCtx: FhirContext?,
491
+ theO1: IQueryParameterType,
492
+ theO2: IQueryParameterType,
493
+ ): Int {
494
+ var retVal: Int
495
+ retVal =
496
+ if (theO1.missing == null && theO2.missing == null) {
497
+ 0
498
+ } else if (theO1.missing == null) {
499
+ -1
500
+ } else if (theO2.missing == null) {
501
+ 1
502
+ } else if (theO1.missing == theO2.missing) {
503
+ 0
504
+ } else {
505
+ if (theO1.missing) {
506
+ 1
507
+ } else {
508
+ -1
509
+ }
510
+ }
511
+
512
+ if (retVal == 0) {
513
+ val q1 = theO1.queryParameterQualifier
514
+ val q2 = theO2.queryParameterQualifier
515
+ retVal = StringUtils.compare(q1, q2)
516
+ }
517
+
518
+ if (retVal == 0) {
519
+ val v1 = theO1.getValueAsQueryToken(theCtx)
520
+ val v2 = theO2.getValueAsQueryToken(theCtx)
521
+ retVal = StringUtils.compare(v1, v2)
522
+ }
523
+ return retVal
524
+ }
525
+ }
526
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterResolver.kt ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.searchparam
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.RuntimeSearchParam
5
+ import ca.uhn.fhir.model.api.IQueryParameterType
6
+ import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum
7
+ import ca.uhn.fhir.rest.param.NumberParam
8
+ import ca.uhn.fhir.rest.param.QuantityParam
9
+ import ca.uhn.fhir.rest.param.ReferenceParam
10
+ import ca.uhn.fhir.rest.param.StringParam
11
+ import ca.uhn.fhir.rest.param.TokenParam
12
+ import ca.uhn.fhir.rest.param.UriParam
13
+ import org.apache.commons.lang3.tuple.Pair
14
+
15
+ class SearchParameterResolver(val fhirContext: FhirContext) {
16
+ fun getSearchParameterDefinition(dataType: String?, path: String?): RuntimeSearchParam? {
17
+ return this.getSearchParameterDefinition(
18
+ dataType,
19
+ path,
20
+ null as RestSearchParameterTypeEnum?,
21
+ )
22
+ }
23
+
24
+ fun getSearchParameterDefinition(
25
+ dataType: String?,
26
+ path: String?,
27
+ paramType: RestSearchParameterTypeEnum?,
28
+ ): RuntimeSearchParam? {
29
+ var path = path
30
+ if (dataType == null || path == null) {
31
+ return null
32
+ }
33
+
34
+ // Special case for system params. They need to be resolved by name.
35
+ // TODO: All the others like "_language"
36
+ var name: String? = null
37
+ if (path == "id") {
38
+ name = "_id"
39
+ path = ""
40
+ }
41
+
42
+ val params = this.fhirContext.getResourceDefinition(dataType).searchParams
43
+
44
+ for (param in params) {
45
+ // If name matches, it's the one we want.
46
+ if (name != null && param.name == name) {
47
+ return param
48
+ }
49
+
50
+ // Filter out parameters that don't match our requested type.
51
+ if (paramType != null && param.paramType != paramType) {
52
+ continue
53
+ }
54
+
55
+ val normalizedPath = normalizePath(param.path)
56
+ if (path == normalizedPath || path.equals(param.name, ignoreCase = true)) {
57
+ return param
58
+ }
59
+ }
60
+
61
+ return null
62
+ }
63
+
64
+ fun createSearchParameter(
65
+ context: String?,
66
+ dataType: String?,
67
+ path: String?,
68
+ value: String?,
69
+ ): Pair<String, IQueryParameterType>? {
70
+ val searchParam = this.getSearchParameterDefinition(dataType, path) ?: return null
71
+
72
+ val name = searchParam.name
73
+
74
+ when (searchParam.paramType) {
75
+ RestSearchParameterTypeEnum.TOKEN ->
76
+ return Pair.of<String, IQueryParameterType>(name, TokenParam(value))
77
+ RestSearchParameterTypeEnum.REFERENCE ->
78
+ return Pair.of<String, IQueryParameterType>(
79
+ name,
80
+ ReferenceParam(context, null, value),
81
+ )
82
+
83
+ RestSearchParameterTypeEnum.QUANTITY ->
84
+ return Pair.of<String, IQueryParameterType>(name, QuantityParam(value))
85
+
86
+ RestSearchParameterTypeEnum.STRING ->
87
+ return Pair.of<String, IQueryParameterType>(name, StringParam(value))
88
+
89
+ RestSearchParameterTypeEnum.NUMBER ->
90
+ return Pair.of<String, IQueryParameterType>(name, NumberParam(value))
91
+
92
+ RestSearchParameterTypeEnum.URI ->
93
+ return Pair.of<String, IQueryParameterType>(name, UriParam(value))
94
+
95
+ RestSearchParameterTypeEnum.DATE,
96
+ RestSearchParameterTypeEnum.HAS,
97
+ RestSearchParameterTypeEnum.COMPOSITE,
98
+ RestSearchParameterTypeEnum.SPECIAL -> {}
99
+ }
100
+
101
+ return null
102
+ }
103
+
104
+ // This is actually a lot of processing. We should cache search parameter resolutions.
105
+ private fun normalizePath(path: String): String? {
106
+ // TODO: What we really need is FhirPath parsing to just get the path
107
+ // MedicationAdministration.medication.as(CodeableConcept)
108
+ // MedicationAdministration.medication.as(Reference)
109
+ // (MedicationAdministration.medication as CodeableConcept)
110
+ // (MedicationAdministration.medication as Reference)
111
+ // Condition.onset.as(Age) | Condition.onset.as(Range)
112
+ // Observation.code | Observation.component.code
113
+
114
+ // Trim off outer parens
115
+
116
+ var path = path
117
+ if (path == "(") {
118
+ path = path.substring(1, path.length - 1)
119
+ }
120
+
121
+ val normalizedParts = mutableSetOf<String>()
122
+ val orParts = path.split("|")
123
+ for (part in orParts) {
124
+ path = part.trim { it <= ' ' }
125
+
126
+ // Trim off DataType
127
+ path = path.substring(path.indexOf(".") + 1, path.length)
128
+
129
+ // Split into components
130
+ val pathSplit = path.split(".")
131
+ val newPathParts = mutableListOf<String>()
132
+
133
+ for (p in pathSplit) {
134
+ // Skip the "as(X)" part.
135
+ if (p.startsWith("as(")) {
136
+ continue
137
+ }
138
+
139
+ // Skip the "[x]" part.
140
+ if (p.startsWith("[x]")) {
141
+ continue
142
+ }
143
+
144
+ // Filter out spaces and everything after "medication as Reference"
145
+ val ps = p.split(" ")
146
+ if (ps.isNotEmpty()) {
147
+ newPathParts.add(ps[0])
148
+ }
149
+ }
150
+
151
+ path = newPathParts.joinToString(".")
152
+ normalizedParts.add(path)
153
+ }
154
+
155
+ // This handles cases such as /Condition?onset-age and /Condition?onset-date
156
+ // where there are multiple underlying representations of the same property
157
+ // (e.g. Condition.onset.as(Age) | Condition.onset.as(Range)), but
158
+ // will punt on something like /Observation?combo-code where the underlying
159
+ // representation maps to multiple places in a nested hierarchy (e.g.
160
+ // Observation.code | Observation.component.code ).
161
+ return if (normalizedParts.size == 1) {
162
+ normalizedParts.iterator().next()
163
+ } else {
164
+ null
165
+ }
166
+ }
167
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/Dstu3FhirTerminologyProvider.kt ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.terminology
2
+
3
+ import ca.uhn.fhir.rest.client.api.IGenericClient
4
+ import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException
5
+ import org.hl7.fhir.dstu3.model.BooleanType
6
+ import org.hl7.fhir.dstu3.model.Bundle
7
+ import org.hl7.fhir.dstu3.model.CodeSystem
8
+ import org.hl7.fhir.dstu3.model.CodeType
9
+ import org.hl7.fhir.dstu3.model.IdType
10
+ import org.hl7.fhir.dstu3.model.Parameters
11
+ import org.hl7.fhir.dstu3.model.StringType
12
+ import org.hl7.fhir.dstu3.model.UriType
13
+ import org.hl7.fhir.dstu3.model.ValueSet
14
+ import org.hl7.fhir.instance.model.api.IBaseBundle
15
+ import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator
16
+ import org.opencds.cqf.cql.engine.exception.TerminologyProviderException
17
+ import org.opencds.cqf.cql.engine.runtime.Code
18
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
19
+ import org.opencds.cqf.cql.engine.terminology.CodeSystemInfo
20
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
21
+ import org.opencds.cqf.cql.engine.terminology.ValueSetInfo
22
+
23
+ class Dstu3FhirTerminologyProvider(private val fhirClient: IGenericClient) : TerminologyProvider {
24
+ override fun `in`(code: Code, valueSet: ValueSetInfo): Boolean {
25
+ if (code.system == null) {
26
+ // If the system is not provided and the resolved value set contains codes from multiple
27
+ // code systems, a run-time error is thrown because the operation is ambiguous
28
+ val codes = expand(valueSet)
29
+ if (codes.distinctBy { it.system }.size > 1) {
30
+ throw TerminologyProviderException(
31
+ @Suppress("MaxLineLength")
32
+ "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}; the operation is ambiguous because the code system is not provided and the resolved value set contains codes from multiple code systems"
33
+ )
34
+ }
35
+ return codes.any {
36
+ EquivalentEvaluator.equivalent(code.code?.toCqlString(), it.code?.toCqlString()) ==
37
+ org.opencds.cqf.cql.engine.runtime.Boolean.TRUE
38
+ }
39
+ }
40
+ try {
41
+ val id = resolveValueSetId(valueSet)
42
+ val respParam =
43
+ fhirClient
44
+ .operation()
45
+ .onInstance(IdType(VALUE_SET, id)) // .onType(ValueSet.class)
46
+ .named("validate-code")
47
+ .withParameter(Parameters::class.java, "code", StringType(code.code))
48
+ .andParameter("system", StringType(code.system))
49
+ .useHttpGet()
50
+ .execute()
51
+ return (respParam.getParameter()[0].getValue() as BooleanType).booleanValue()
52
+ } catch (e: Exception) {
53
+ throw TerminologyProviderException(
54
+ "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}",
55
+ e,
56
+ )
57
+ }
58
+ }
59
+
60
+ override fun expand(valueSet: ValueSetInfo): Iterable<Code> {
61
+ try {
62
+ val id = resolveValueSetId(valueSet)
63
+ val respParam =
64
+ fhirClient
65
+ .operation()
66
+ .onInstance(IdType(VALUE_SET, id))
67
+ .named("expand")
68
+ .withNoParameters(Parameters::class.java)
69
+ .useHttpGet()
70
+ .execute()
71
+
72
+ val expanded = respParam.getParameter()[0].getResource() as ValueSet
73
+ val codes = mutableListOf<Code>()
74
+ for (codeInfo in expanded.getExpansion().getContains()) {
75
+ val nextCode =
76
+ Code()
77
+ .withCode(codeInfo.getCode())
78
+ .withSystem(codeInfo.getSystem())
79
+ .withVersion(codeInfo.getVersion())
80
+ .withDisplay(codeInfo.getDisplay())
81
+ codes.add(nextCode)
82
+ }
83
+ return codes
84
+ } catch (e: Exception) {
85
+ throw TerminologyProviderException(
86
+ "Error performing expansion of ValueSet: ${valueSet.id}",
87
+ e,
88
+ )
89
+ }
90
+ }
91
+
92
+ override fun lookup(code: Code, codeSystem: CodeSystemInfo): Code {
93
+ try {
94
+ val respParam =
95
+ fhirClient
96
+ .operation()
97
+ .onType(CodeSystem::class.java)
98
+ .named("lookup")
99
+ .withParameter(Parameters::class.java, "code", CodeType(code.code))
100
+ .andParameter("system", UriType(codeSystem.id))
101
+ .execute()
102
+
103
+ val display =
104
+ respParam
105
+ .getParameter()
106
+ .stream()
107
+ .filter { x: Parameters.ParametersParameterComponent? ->
108
+ x!!.getName() == "display"
109
+ }
110
+ .findFirst()
111
+ if (display.isPresent) {
112
+ code.withDisplay(display.get().getValue().toString())
113
+ }
114
+
115
+ return code.withSystem(codeSystem.id)
116
+ } catch (e: Exception) {
117
+ throw TerminologyProviderException(
118
+ "Error performing lookup of Code: $code in CodeSystem: ${codeSystem.id}",
119
+ e,
120
+ )
121
+ }
122
+ }
123
+
124
+ private fun searchByUrl(url: String?): Bundle {
125
+ return fhirClient
126
+ .search<IBaseBundle?>()
127
+ .forResource(ValueSet::class.java)
128
+ .where(ValueSet.URL.matches().value(url))
129
+ .returnBundle(Bundle::class.java)
130
+ .execute()
131
+ }
132
+
133
+ private fun searchByIdentifier(identifier: String?): Bundle {
134
+ return fhirClient
135
+ .search<IBaseBundle?>()
136
+ .forResource(ValueSet::class.java)
137
+ .where(ValueSet.IDENTIFIER.exactly().code(identifier))
138
+ .returnBundle(Bundle::class.java)
139
+ .execute()
140
+ }
141
+
142
+ private fun searchById(id: String): Bundle {
143
+ var id = id
144
+ if (id.startsWith(URN_OID)) {
145
+ id = id.replace(URN_OID, "")
146
+ } else if (id.startsWith(URN_UUID)) {
147
+ id = id.replace(URN_UUID, "")
148
+ }
149
+ val searchResults = Bundle()
150
+ // If we reached this point, and it looks like it might
151
+ // be a FHIR resource ID, we will try to read it.
152
+ // See https://www.hl7.org/fhir/datatypes.html#id
153
+ if (id.matches("[A-Za-z0-9\\-\\.]{1,64}".toRegex())) {
154
+ try {
155
+ val vs = fhirClient.read().resource(ValueSet::class.java).withId(id).execute()
156
+ searchResults.addEntry().setResource(vs)
157
+ } catch (rnfe: ResourceNotFoundException) {
158
+ // intentionally empty
159
+ }
160
+ }
161
+
162
+ return searchResults
163
+ }
164
+
165
+ fun resolveValueSetId(valueSet: ValueSetInfo): String? {
166
+ if (
167
+ valueSet.version != null ||
168
+ (valueSet.codeSystems != null && !valueSet.codeSystems!!.isEmpty())
169
+ ) {
170
+ throw UnsupportedOperationException(
171
+ "Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time."
172
+ )
173
+ }
174
+
175
+ // https://github.com/DBCG/cql_engine/pull/462 - Use a search path of URL,
176
+ // identifier, and then resource id
177
+ var searchResults = searchByUrl(valueSet.id)
178
+ if (!searchResults.hasEntry()) {
179
+ searchResults = searchByIdentifier(valueSet.id)
180
+ }
181
+
182
+ if (!searchResults.hasEntry()) {
183
+ searchResults = searchById(valueSet.id!!)
184
+ }
185
+
186
+ require(!(!searchResults.hasEntry() || searchResults.getEntry().isEmpty())) {
187
+ "Could not resolve value set ${valueSet.id}."
188
+ }
189
+ require(searchResults.getEntry().size <= 1) {
190
+ "Found more than 1 ValueSet with url: " + valueSet.id
191
+ }
192
+ return searchResults.entryFirstRep.getResource().idElement.idPart
193
+ }
194
+
195
+ companion object {
196
+ private const val URN_UUID = "urn:uuid:"
197
+ private const val URN_OID = "urn:oid:"
198
+ private const val VALUE_SET = "ValueSet"
199
+ }
200
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/HeaderInjectionInterceptor.kt ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ *
3
+ * This code is derived from work done by Barry Cassidy from Motive Medical Intelligence
4
+ * Thank you!
5
+ *
6
+ * */
7
+ package org.opencds.cqf.cql.engine.fhir.terminology
8
+
9
+ import ca.uhn.fhir.rest.client.api.IClientInterceptor
10
+ import ca.uhn.fhir.rest.client.api.IHttpRequest
11
+ import ca.uhn.fhir.rest.client.api.IHttpResponse
12
+ import java.io.IOException
13
+
14
+ class HeaderInjectionInterceptor(private val headers: Map<String, String> = mapOf()) :
15
+ IClientInterceptor {
16
+ /**
17
+ * Instantiates a new header injection interception.
18
+ *
19
+ * @param headerKey the header key
20
+ * @param headerValue the header value
21
+ */
22
+ constructor(headerKey: String, headerValue: String) : this(mapOf(headerKey to headerValue))
23
+
24
+ override fun interceptRequest(request: IHttpRequest) {
25
+ for (entry in this.headers.entries) {
26
+ request.addHeader(entry.key, entry.value)
27
+ }
28
+ }
29
+
30
+ @Throws(IOException::class)
31
+ override fun interceptResponse(response: IHttpResponse?) {
32
+ // nothing
33
+ }
34
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/R4FhirTerminologyProvider.kt ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.terminology
2
+
3
+ import ca.uhn.fhir.rest.client.api.IGenericClient
4
+ import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException
5
+ import org.hl7.fhir.instance.model.api.IBaseBundle
6
+ import org.hl7.fhir.r4.model.BooleanType
7
+ import org.hl7.fhir.r4.model.Bundle
8
+ import org.hl7.fhir.r4.model.CodeSystem
9
+ import org.hl7.fhir.r4.model.CodeType
10
+ import org.hl7.fhir.r4.model.IdType
11
+ import org.hl7.fhir.r4.model.Parameters
12
+ import org.hl7.fhir.r4.model.StringType
13
+ import org.hl7.fhir.r4.model.UriType
14
+ import org.hl7.fhir.r4.model.ValueSet
15
+ import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator
16
+ import org.opencds.cqf.cql.engine.exception.TerminologyProviderException
17
+ import org.opencds.cqf.cql.engine.runtime.Code
18
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
19
+ import org.opencds.cqf.cql.engine.terminology.CodeSystemInfo
20
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
21
+ import org.opencds.cqf.cql.engine.terminology.ValueSetInfo
22
+
23
+ /**
24
+ * @param fhirClient - an IGenericClient that has endpoint and authentication already defined and
25
+ * set.
26
+ */
27
+ class R4FhirTerminologyProvider(val fhirClient: IGenericClient) : TerminologyProvider {
28
+ override fun `in`(code: Code, valueSet: ValueSetInfo): Boolean {
29
+ if (code.system == null) {
30
+ // If the system is not provided and the resolved value set contains codes from multiple
31
+ // code systems, a run-time error is thrown because the operation is ambiguous
32
+ val codes = expand(valueSet)
33
+ if (codes.distinctBy { it.system }.size > 1) {
34
+ throw TerminologyProviderException(
35
+ @Suppress("MaxLineLength")
36
+ "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}; the operation is ambiguous because the code system is not provided and the resolved value set contains codes from multiple code systems"
37
+ )
38
+ }
39
+ return codes.any {
40
+ EquivalentEvaluator.equivalent(code.code?.toCqlString(), it.code?.toCqlString()) ==
41
+ org.opencds.cqf.cql.engine.runtime.Boolean.TRUE
42
+ }
43
+ }
44
+ try {
45
+ val id = resolveValueSetId(valueSet)
46
+ val respParam =
47
+ fhirClient
48
+ .operation()
49
+ .onInstance(IdType(VALUE_SET, id)) // .onType(ValueSet.class)
50
+ .named("validate-code")
51
+ .withParameter(Parameters::class.java, "code", StringType(code.code))
52
+ .andParameter("system", StringType(code.system))
53
+ .useHttpGet()
54
+ .execute()
55
+ return (respParam.getParameter()[0].getValue() as BooleanType).booleanValue()
56
+ } catch (e: Exception) {
57
+ throw TerminologyProviderException(
58
+ "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}",
59
+ e,
60
+ )
61
+ }
62
+ }
63
+
64
+ override fun expand(valueSet: ValueSetInfo): Iterable<Code> {
65
+ try {
66
+ val id = resolveValueSetId(valueSet)
67
+ val respParam =
68
+ fhirClient
69
+ .operation()
70
+ .onInstance(IdType(VALUE_SET, id))
71
+ .named("expand")
72
+ .withNoParameters(Parameters::class.java)
73
+ .useHttpGet()
74
+ .execute()
75
+
76
+ val expanded = respParam.getParameter()[0].getResource() as ValueSet
77
+ val codes = mutableListOf<Code>()
78
+ for (codeInfo in expanded.getExpansion().getContains()) {
79
+ val nextCode =
80
+ Code()
81
+ .withCode(codeInfo.getCode())
82
+ .withSystem(codeInfo.getSystem())
83
+ .withVersion(codeInfo.getVersion())
84
+ .withDisplay(codeInfo.getDisplay())
85
+ codes.add(nextCode)
86
+ }
87
+ return codes
88
+ } catch (e: Exception) {
89
+ throw TerminologyProviderException(
90
+ "Error performing expansion of ValueSet: ${valueSet.id}",
91
+ e,
92
+ )
93
+ }
94
+ }
95
+
96
+ override fun lookup(code: Code, codeSystem: CodeSystemInfo): Code {
97
+ try {
98
+ val respParam =
99
+ fhirClient
100
+ .operation()
101
+ .onType(CodeSystem::class.java)
102
+ .named("lookup")
103
+ .withParameter(Parameters::class.java, "code", CodeType(code.code))
104
+ .andParameter("system", UriType(codeSystem.id))
105
+ .execute()
106
+
107
+ val display = respParam.getParameter("display").getValue() as StringType?
108
+ if (display != null) {
109
+ code.withDisplay(display.value)
110
+ }
111
+
112
+ return code.withSystem(codeSystem.id)
113
+ } catch (e: Exception) {
114
+ throw TerminologyProviderException(
115
+ "Error performing lookup of Code: $code in CodeSystem: ${codeSystem.id}",
116
+ e,
117
+ )
118
+ }
119
+ }
120
+
121
+ private fun searchByUrl(url: String?): Bundle {
122
+ return fhirClient
123
+ .search<IBaseBundle?>()
124
+ .forResource(ValueSet::class.java)
125
+ .where(ValueSet.URL.matches().value(url))
126
+ .returnBundle(Bundle::class.java)
127
+ .execute()
128
+ }
129
+
130
+ private fun searchByIdentifier(identifier: String?): Bundle {
131
+ return fhirClient
132
+ .search<IBaseBundle?>()
133
+ .forResource(ValueSet::class.java)
134
+ .where(ValueSet.IDENTIFIER.exactly().code(identifier))
135
+ .returnBundle(Bundle::class.java)
136
+ .execute()
137
+ }
138
+
139
+ private fun searchById(id: String): Bundle {
140
+ var id = id
141
+ if (id.startsWith(URN_OID)) {
142
+ id = id.replace(URN_OID, "")
143
+ } else if (id.startsWith(URN_UUID)) {
144
+ id = id.replace(URN_UUID, "")
145
+ }
146
+ val searchResults = Bundle()
147
+ // If we reached this point and it looks like it might
148
+ // be a FHIR resource ID, we will try to read it.
149
+ // See https://www.hl7.org/fhir/datatypes.html#id
150
+ if (id.matches("[A-Za-z0-9\\-\\.]{1,64}".toRegex())) {
151
+ try {
152
+ val vs = fhirClient.read().resource(ValueSet::class.java).withId(id).execute()
153
+ searchResults.addEntry().setResource(vs)
154
+ } catch (rnfe: ResourceNotFoundException) {
155
+ // intentionally empty
156
+ }
157
+ }
158
+
159
+ return searchResults
160
+ }
161
+
162
+ fun resolveValueSetId(valueSet: ValueSetInfo): String? {
163
+ if (
164
+ valueSet.version != null ||
165
+ (valueSet.codeSystems != null && !valueSet.codeSystems!!.isEmpty())
166
+ ) {
167
+ throw UnsupportedOperationException(
168
+ "Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time."
169
+ )
170
+ }
171
+
172
+ // https://github.com/DBCG/cql_engine/pull/462 - Use a search path of URL,
173
+ // identifier, and then resource id
174
+ var searchResults = searchByUrl(valueSet.id)
175
+ if (!searchResults.hasEntry()) {
176
+ searchResults = searchByIdentifier(valueSet.id)
177
+ }
178
+
179
+ if (!searchResults.hasEntry()) {
180
+ searchResults = searchById(valueSet.id!!)
181
+ }
182
+
183
+ require(!(!searchResults.hasEntry() || searchResults.getEntry().isEmpty())) {
184
+ "Could not resolve value set ${valueSet.id}."
185
+ }
186
+ require(searchResults.getEntry().size <= 1) {
187
+ "Found more than 1 ValueSet with url: " + valueSet.id
188
+ }
189
+ return searchResults.entryFirstRep.getResource().idElement.idPart
190
+ }
191
+
192
+ companion object {
193
+ private const val URN_UUID = "urn:uuid:"
194
+ private const val URN_OID = "urn:oid:"
195
+ private const val VALUE_SET = "ValueSet"
196
+ }
197
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsDstu3Test.kt ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import com.google.common.collect.Sets
6
+ import org.hl7.fhirpath.tests.Group
7
+ import org.hl7.fhirpath.tests.Test
8
+ import org.junit.jupiter.api.Assumptions
9
+ import org.junit.jupiter.params.ParameterizedTest
10
+ import org.junit.jupiter.params.provider.MethodSource
11
+ import org.opencds.cqf.cql.engine.data.CompositeDataProvider
12
+ import org.opencds.cqf.cql.engine.fhir.model.CachedDstu3FhirModelResolver
13
+ import org.opencds.cqf.cql.engine.fhir.model.Dstu3FhirModelResolver
14
+ import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider
15
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
16
+
17
+ class CQLOperationsDstu3Test : TestFhirPath() {
18
+ @ParameterizedTest(name = "{0}")
19
+ @MethodSource("dataMethod")
20
+ fun test(name: String, test: Test) {
21
+ Assumptions.assumeFalse(SKIP.contains(name), "Skipping $name")
22
+ runTest(test, "stu3/input/", fhirContext, provider, fhirModelResolver)
23
+ runTest(test, "stu3/input/", fhirContext, provider, fhirModelResolver)
24
+ }
25
+
26
+ companion object {
27
+ private val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.DSTU3)
28
+ private val fhirModelResolver: Dstu3FhirModelResolver = CachedDstu3FhirModelResolver()
29
+ private val retrieveProvider =
30
+ RestFhirRetrieveProvider(
31
+ SearchParameterResolver(fhirContext),
32
+ fhirModelResolver,
33
+ fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"),
34
+ )
35
+ private val provider = CompositeDataProvider(fhirModelResolver, retrieveProvider)
36
+
37
+ @JvmStatic
38
+ fun dataMethod(): Array<Array<Any>> {
39
+ val listOfFiles = arrayOf("stu3/tests-fhir-r3.xml")
40
+
41
+ val testsToRun: MutableList<Array<Any>> = ArrayList()
42
+ for (file in listOfFiles) {
43
+ for (group in loadTestsFile(file)!!.getGroup()) {
44
+ for (test in group.getTest()) {
45
+ if ("2.1.0" != test.getVersion()) { // unsupported version
46
+ val name: String = getTestName(file, group, test)
47
+ testsToRun.add(arrayOf(name, test))
48
+ }
49
+ }
50
+ }
51
+ }
52
+ return testsToRun.toTypedArray()
53
+ }
54
+
55
+ var SKIP: MutableSet<String> =
56
+ Sets.newHashSet<String>(
57
+ "stu3/tests-fhir-r3/Dollar/testDollarOrderNotAllowed(Patient.children().skip(1))",
58
+ $$"stu3/tests-fhir-r3/Dollar/testDollarThis1(Patient.name.given.where(substring($this.length()-3) = 'out'))",
59
+ $$"stu3/tests-fhir-r3/Dollar/testDollarThis2(Patient.name.given.where(substring($this.length()-3) = 'ter'))",
60
+ "stu3/tests-fhir-r3/Literals/testLiteralDate((0).not() = false)",
61
+ "stu3/tests-fhir-r3/Literals/testLiteralDate((1).not() = false)",
62
+ "stu3/tests-fhir-r3/Literals/testLiteralDate((1|2).not() = false)",
63
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00)",
64
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00+10:00)",
65
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00-10:00)",
66
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00Z)",
67
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @T12:14)",
68
+ "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @T12:14:15)",
69
+ "stu3/tests-fhir-r3/Literals/testLiteralDecimal(Observation.value.value < 190)",
70
+ "stu3/tests-fhir-r3/Literals/testLiteralDecimal(Observation.value.value > 0)",
71
+ "stu3/tests-fhir-r3/Literals/testLiteralString(Patient.name.given.first() = 'Peter')",
72
+ "stu3/tests-fhir-r3/Literals/testLiteralUnicode(Patient.name.given.first() = 'P\\u0065ter')",
73
+ "stu3/tests-fhir-r3/testAll(Patient.name.select(family.exists()).all())",
74
+ "stu3/tests-fhir-r3/testAll(Patient.name.select(given.exists()).all())",
75
+ "stu3/tests-fhir-r3/testBooleanImplies((true implies {}) = {})",
76
+ "stu3/tests-fhir-r3/testBooleanImplies(({} implies false) = true)",
77
+ "stu3/tests-fhir-r3/testBooleanImplies(({} implies {}) = true)",
78
+ "stu3/tests-fhir-r3/testBooleanLogicAnd((true and {}) = {})",
79
+ "stu3/tests-fhir-r3/testBooleanLogicAnd(({} and true) = {})",
80
+ "stu3/tests-fhir-r3/testBooleanLogicAnd(({} and {}) = {})",
81
+ "stu3/tests-fhir-r3/testBooleanLogicOr((false or {}) = {})",
82
+ "stu3/tests-fhir-r3/testBooleanLogicOr(({} or false) = {})",
83
+ "stu3/tests-fhir-r3/testBooleanLogicOr(({} or {}) = {})",
84
+ "stu3/tests-fhir-r3/testBooleanLogicXOr((false xor {}) = {})",
85
+ "stu3/tests-fhir-r3/testBooleanLogicXOr((true xor {}) = {})",
86
+ "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor false) = {})",
87
+ "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor true) = {})",
88
+ "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor {}) = {})",
89
+ "stu3/tests-fhir-r3/testConcatenate((1 | 2 | 3) & 'b' = '1,2,3b')",
90
+ "stu3/tests-fhir-r3/testConcatenate(1 & 'a' = '1a')",
91
+ "stu3/tests-fhir-r3/testConcatenate(1 & 1 = '11')",
92
+ "stu3/tests-fhir-r3/testContainsString('12345'.contains('') = false)",
93
+ "stu3/tests-fhir-r3/testDistinct((1 | 2 | 3).isDistinct())",
94
+ "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.distinct())",
95
+ "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.isDistinct())",
96
+ "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).distinct())",
97
+ "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).isDistinct().not())",
98
+ "stu3/tests-fhir-r3/testDivide(1.2 / 1.8 = 0.67)",
99
+ "stu3/tests-fhir-r3/testEndsWith('12345'.endsWith('') = false)",
100
+ "stu3/tests-fhir-r3/testEquality(0.0 = 0)",
101
+ "stu3/tests-fhir-r3/testEquality(1.10 = 1.1)",
102
+ "stu3/tests-fhir-r3/testEquality(name = name.first() | name.last())",
103
+ "stu3/tests-fhir-r3/testEquality(name = name.last() | name.first())",
104
+ "stu3/tests-fhir-r3/testEquivalent(@2012-04-15 ~ @2012-04-15T10:00:00)",
105
+ "stu3/tests-fhir-r3/testEquivalent(name.given ~ name.first().given | name.last().given)",
106
+ "stu3/tests-fhir-r3/testEquivalent(name.given ~ name.last().given | name.first().given)",
107
+ "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension(%\"ext-patient-birthTime\").exists())",
108
+ "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').exists())",
109
+ "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime1').empty())",
110
+ "stu3/tests-fhir-r3/testFirstLast(Patient.name.first().given = 'Peter' | 'James')",
111
+ "stu3/tests-fhir-r3/testFirstLast(Patient.name.last().given = 'Jim')",
112
+ "stu3/tests-fhir-r3/testIif(iif(Patient.name.empty(), 'unnamed', 'named') = 'named')",
113
+ "stu3/tests-fhir-r3/testIif(iif(Patient.name.exists(), 'named', 'unnamed') = 'named')",
114
+ "stu3/tests-fhir-r3/testIndexer(Patient.name[0].given = 'Peter' | 'James')",
115
+ "stu3/tests-fhir-r3/testIndexer(Patient.name[1].given = 'Jim')",
116
+ "stu3/tests-fhir-r3/testNEquality(0.0 != 0)",
117
+ "stu3/tests-fhir-r3/testNEquality(1.10 != 1.1)",
118
+ "stu3/tests-fhir-r3/testNEquality(name != name.first() | name.last())",
119
+ "stu3/tests-fhir-r3/testNEquality(name != name.last() | name.first())",
120
+ "stu3/tests-fhir-r3/testNotEquivalent(@2012-04-15 !~ @2012-04-15T10:00:00)",
121
+ "stu3/tests-fhir-r3/testNotEquivalent(name.given !~ name.first().given | name.last().given)",
122
+ "stu3/tests-fhir-r3/testNotEquivalent(name.given !~ name.last().given | name.first().given)",
123
+ "stu3/tests-fhir-r3/testNow(now().toString().length() > 10)",
124
+ "stu3/tests-fhir-r3/testNow(Patient.birthDate < now())",
125
+ "stu3/tests-fhir-r3/testRepeat(Questionnaire.children().concept.count() = 2)",
126
+ "stu3/tests-fhir-r3/testRepeat(Questionnaire.descendants().concept.count() = 10)",
127
+ "stu3/tests-fhir-r3/testRepeat(Questionnaire.repeat(item).concept.count() = 10)",
128
+ "stu3/tests-fhir-r3/testRepeat(ValueSet.expansion.repeat(contains).count() = 10)",
129
+ "stu3/tests-fhir-r3/testSelect(Patient.name.select(given) = 'Peter' | 'James' | 'Jim')",
130
+ "stu3/tests-fhir-r3/testSelect(Patient.name.select(given | family) = 'Peter' | 'James' | 'Chalmers' | 'Jim')",
131
+ "stu3/tests-fhir-r3/testSkip((0 | 1 | 2).skip(1) = 1 | 2)",
132
+ "stu3/tests-fhir-r3/testSkip(Patient.name.skip(1).given = 'Jim')",
133
+ "stu3/tests-fhir-r3/testStartsWith('12345'.startsWith('') = false)",
134
+ $$"stu3/tests-fhir-r3/testSubSetOf(Patient.name.first().subsetOf($this.name))",
135
+ $$"stu3/tests-fhir-r3/testSubSetOf(Patient.name.subsetOf($this.name.first()).not())",
136
+ $$"stu3/tests-fhir-r3/testSuperSetOf(Patient.name.first().supersetOf($this.name).not())",
137
+ $$"stu3/tests-fhir-r3/testSuperSetOf(Patient.name.supersetOf($this.name.first()))",
138
+ "stu3/tests-fhir-r3/testTail((0 | 1 | 2).tail() = 1 | 2)",
139
+ "stu3/tests-fhir-r3/testTail(Patient.name.tail().given = 'Jim')",
140
+ "stu3/tests-fhir-r3/testTake((0 | 1 | 2).take(2) = 0 | 1)",
141
+ "stu3/tests-fhir-r3/testTake(Patient.name.take(1).given = 'Peter' | 'James')",
142
+ "stu3/tests-fhir-r3/testTake(Patient.name.take(2).given = 'Peter' | 'James' | 'Jim')",
143
+ "stu3/tests-fhir-r3/testTake(Patient.name.take(3).given = 'Peter' | 'James' | 'Jim')",
144
+ "stu3/tests-fhir-r3/testToday(Patient.birthDate < today())",
145
+ "stu3/tests-fhir-r3/testToday(today().toString().length() = 10)",
146
+ "stu3/tests-fhir-r3/testToInteger('0.0'.toInteger().empty())",
147
+ "stu3/tests-fhir-r3/testVariables(%\"vs-administrative-gender\" = 'http://hl7.org/fhir/ValueSet/administrative-gender')",
148
+ "stu3/tests-fhir-r3/testVariables(%loinc = 'http://loinc.org')",
149
+ "stu3/tests-fhir-r3/testVariables(%sct = 'http://snomed.info/sct')",
150
+ "stu3/tests-fhir-r3/testVariables(%ucum = 'http://unitsofmeasure.org')",
151
+ $$"stu3/tests-fhir-r3/testWhere(Patient.name.where($this.given = 'Jim').count() = 1)",
152
+ "stu3/tests-fhir-r3/testWhere(Patient.name.where(given = 'Jim').count() = 1)",
153
+ "stu3/tests-fhir-r3/testWhere(Patient.name.where(given = 'X').count() = 0)",
154
+ )
155
+
156
+ fun getTestName(file: String, group: Group, test: Test): String {
157
+ return (file.replace(".xml", "") +
158
+ "/" +
159
+ group.getName() +
160
+ (if (test.getName() != null) "/" + test.getName() else "") +
161
+ "(" +
162
+ test.getExpression().getValue() +
163
+ ")")
164
+ }
165
+ }
166
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsR4Test.kt ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import com.google.common.collect.Sets
6
+ import org.hl7.fhirpath.tests.Group
7
+ import org.hl7.fhirpath.tests.Test
8
+ import org.junit.jupiter.api.Assumptions
9
+ import org.junit.jupiter.params.ParameterizedTest
10
+ import org.junit.jupiter.params.provider.MethodSource
11
+ import org.opencds.cqf.cql.engine.data.CompositeDataProvider
12
+ import org.opencds.cqf.cql.engine.fhir.model.CachedR4FhirModelResolver
13
+ import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver
14
+ import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider
15
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
16
+
17
+ class CQLOperationsR4Test : TestFhirPath() {
18
+ @ParameterizedTest(name = "{0}")
19
+ @MethodSource("dataMethod")
20
+ fun test(name: String, test: Test) {
21
+ Assumptions.assumeFalse(SKIP.contains(name), "Skipping $name")
22
+ runTest(test, "r4/input/", fhirContext, provider, fhirModelResolver)
23
+ }
24
+
25
+ companion object {
26
+ private val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.R4)
27
+ private val fhirModelResolver: R4FhirModelResolver = CachedR4FhirModelResolver()
28
+ private val retrieveProvider =
29
+ RestFhirRetrieveProvider(
30
+ SearchParameterResolver(fhirContext),
31
+ fhirModelResolver,
32
+ fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseR4"),
33
+ )
34
+ private val provider = CompositeDataProvider(fhirModelResolver, retrieveProvider)
35
+
36
+ @JvmStatic
37
+ fun dataMethod(): Array<Array<Any>> {
38
+ val listOfFiles =
39
+ arrayOf(
40
+ "r4/tests-fhir-r4.xml",
41
+ "cql/CqlAggregateFunctionsTest.xml",
42
+ "cql/CqlAggregateTest.xml",
43
+ "cql/CqlArithmeticFunctionsTest.xml",
44
+ "cql/CqlComparisonOperatorsTest.xml",
45
+ "cql/CqlConditionalOperatorsTest.xml",
46
+ "cql/CqlDateTimeOperatorsTest.xml",
47
+ "cql/CqlErrorsAndMessagingOperatorsTest.xml",
48
+ "cql/CqlIntervalOperatorsTest.xml",
49
+ "cql/CqlListOperatorsTest.xml",
50
+ "cql/CqlLogicalOperatorsTest.xml",
51
+ "cql/CqlNullologicalOperatorsTest.xml",
52
+ "cql/CqlStringOperatorsTest.xml",
53
+ "cql/CqlTypeOperatorsTest.xml",
54
+ "cql/CqlTypesTest.xml",
55
+ "cql/ValueLiteralsAndSelectors.xml",
56
+ )
57
+
58
+ val testsToRun: MutableList<Array<Any>> = ArrayList()
59
+ for (file in listOfFiles) {
60
+ for (group in loadTestsFile(file)!!.getGroup()) {
61
+ for (test in group.getTest()) {
62
+ if ("2.1.0" != test.getVersion()) { // unsupported version
63
+ val name: String = getTestName(file, group, test)
64
+ testsToRun.add(arrayOf(name, test))
65
+ }
66
+ }
67
+ }
68
+ }
69
+ return testsToRun.toTypedArray()
70
+ }
71
+
72
+ var SKIP: MutableSet<String> =
73
+ Sets.newHashSet(
74
+ "cql/CqlAggregateTest/AggregateTests/RolledOutIntervals",
75
+ "cql/CqlArithmeticFunctionsTest/Ln/Ln1000D",
76
+ "cql/CqlArithmeticFunctionsTest/Ln/Ln1000",
77
+ "cql/CqlDateTimeOperatorsTest/Duration/DateTimeDurationBetweenYear",
78
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainAdd",
79
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainInterval",
80
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainInterval2",
81
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainMultiply",
82
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainSubtract",
83
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DurationInDaysA",
84
+ "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DurationInDaysAA",
85
+ "cql/CqlIntervalOperatorsTest/Intersect/TestIntersectNull",
86
+ "cql/CqlIntervalOperatorsTest/Expand/ExpandPer0D1",
87
+ "cql/CqlIntervalOperatorsTest/Expand/ExpandPer0D1IntervalOverload",
88
+ "cql/CqlListOperatorsTest/Equal/EqualABCAnd123",
89
+ "cql/CqlListOperatorsTest/Equal/Equal123AndABC",
90
+ "cql/CqlListOperatorsTest/Equal/Equal123AndString123",
91
+ "cql/CqlListOperatorsTest/Equivalent/Equivalent123AndABC",
92
+ "cql/CqlListOperatorsTest/Equivalent/Equivalent123AndString123",
93
+ "cql/CqlListOperatorsTest/Equivalent/EquivalentABCAnd123",
94
+ "cql/CqlListOperatorsTest/NotEqual/NotEqual123AndABC",
95
+ "cql/CqlListOperatorsTest/NotEqual/NotEqual123AndString123",
96
+ "cql/CqlListOperatorsTest/NotEqual/NotEqualABCAnd123",
97
+ "cql/CqlListOperatorsTest/ProperlyIncludedIn/ProperlyIncludedInNulRight",
98
+ "cql/CqlListOperatorsTest/ProperlyIncludes/ProperlyIncludesNullLeft",
99
+ "cql/CqlListOperatorsTest/Union/UnionListNullAndListNull",
100
+ "cql/CqlStringOperatorsTest/toString tests/DateTimeToString3",
101
+ "cql/CqlTypeOperatorsTest/As/AsQuantity",
102
+ "cql/CqlTypeOperatorsTest/As/CastAsQuantity",
103
+ "cql/CqlTypeOperatorsTest/ToTime/ToTime2",
104
+ "cql/CqlTypeOperatorsTest/ToTime/ToTime3",
105
+ "cql/CqlTypeOperatorsTest/ToTime/ToTime4",
106
+ "cql/CqlTypesTest/DateTime/DateTimeUncertain",
107
+ "cql/CqlTypesTest/Time/TimeUpperBoundMillis",
108
+ "cql/ValueLiteralsAndSelectors/Decimal/Decimal10Pow20",
109
+ "cql/ValueLiteralsAndSelectors/Decimal/DecimalNeg10Pow20",
110
+ "cql/ValueLiteralsAndSelectors/Decimal/DecimalNegTenthStep",
111
+ "cql/ValueLiteralsAndSelectors/Decimal/DecimalPos10Pow20",
112
+ "cql/ValueLiteralsAndSelectors/Decimal/DecimalPosTenthStep",
113
+ "cql/ValueLiteralsAndSelectors/Decimal/DecimalTenthStep",
114
+ "r4/tests-fhir-r4/from-Zulip/(true and 'foo').empty()",
115
+ "r4/tests-fhir-r4/from-Zulip/(true | 'foo').allTrue()",
116
+ "r4/tests-fhir-r4/testAggregate/testAggregate1",
117
+ "r4/tests-fhir-r4/testAggregate/testAggregate2",
118
+ "r4/tests-fhir-r4/testAggregate/testAggregate3",
119
+ "r4/tests-fhir-r4/testAggregate/testAggregate4",
120
+ "r4/tests-fhir-r4/testAll/testAllTrue4",
121
+ "r4/tests-fhir-r4/testBasics/testIdentifierContext",
122
+ "r4/tests-fhir-r4/testBasics/testIdentifierContextIsNotResource",
123
+ "r4/tests-fhir-r4/testBasics/testContainerAccess",
124
+ "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean2",
125
+ "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean3",
126
+ "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean4",
127
+ "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean5",
128
+ "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean6",
129
+ "r4/tests-fhir-r4/testConformsTo/testConformsTo1",
130
+ "r4/tests-fhir-r4/testConformsTo/testConformsTo2",
131
+ "r4/tests-fhir-r4/testDistinct/testDistinct1",
132
+ "r4/tests-fhir-r4/testDistinct/testDistinct2",
133
+ "r4/tests-fhir-r4/testDistinct/testDistinct3",
134
+ "r4/tests-fhir-r4/testDistinct/testDistinct5",
135
+ "r4/tests-fhir-r4/testDistinct/testDistinct6",
136
+ "r4/tests-fhir-r4/testDollar/testDollarOrderNotAllowed",
137
+ "r4/tests-fhir-r4/testEquality/testEquality19",
138
+ "r4/tests-fhir-r4/testEquality/testEquality21",
139
+ "r4/tests-fhir-r4/testEquality/testEquality22",
140
+ "r4/tests-fhir-r4/testEquality/testEquality23",
141
+ "r4/tests-fhir-r4/testEquivalent/testEquivalent11",
142
+ "r4/tests-fhir-r4/testEquivalent/testEquivalent17",
143
+ "r4/tests-fhir-r4/testEquivalent/testEquivalent21",
144
+ "r4/tests-fhir-r4/testExclude/testExclude4",
145
+ "r4/tests-fhir-r4/testExtension/testExtension1",
146
+ "r4/tests-fhir-r4/testExtension/testExtension2",
147
+ "r4/tests-fhir-r4/testExtension/testExtension3",
148
+ "r4/tests-fhir-r4/testGreaterThan/testGreaterThan26",
149
+ "r4/tests-fhir-r4/testGreaterThan/testGreaterThan27",
150
+ "r4/tests-fhir-r4/testGreatorOrEqual/testGreatorOrEqual26",
151
+ "r4/tests-fhir-r4/testGreatorOrEqual/testGreatorOrEqual27",
152
+ "r4/tests-fhir-r4/testIif/testIif1",
153
+ "r4/tests-fhir-r4/testIif/testIif2",
154
+ "r4/tests-fhir-r4/testIif/testIif3",
155
+ "r4/tests-fhir-r4/testIif/testIif4",
156
+ "r4/tests-fhir-r4/testInvariants/extension('http://hl7.org/fhir/us/cqfmeasures/StructureDefinition/cqfm-scoring').exists() and extension('http://hl7.org/fhir/us/cqfmeasures/StructureDefinition/cqfm-scoring').value = 'ratio' implies group.population.where(code.coding.where(system = 'http://terminology.hl7.org/CodeSystem/measure-population').code = 'initial-population').count() in (1 | 2)",
157
+ "r4/tests-fhir-r4/testLessOrEqual/testLessOrEqual26",
158
+ "r4/tests-fhir-r4/testLessOrEqual/testLessOrEqual27",
159
+ "r4/tests-fhir-r4/testLessThan/testLessThan26",
160
+ "r4/tests-fhir-r4/testLessThan/testLessThan27",
161
+ "r4/tests-fhir-r4/testLiterals/testDateGreaterThanDate",
162
+ "r4/tests-fhir-r4/testLiterals/testDateNotEqual",
163
+ "r4/tests-fhir-r4/testLiterals/testDateNotEqualTimeMinute",
164
+ "r4/tests-fhir-r4/testLiterals/testDateNotEqualTimeSecond",
165
+ "r4/tests-fhir-r4/testLiterals/testDateNotEqualToday",
166
+ "r4/tests-fhir-r4/testLiterals/testDateTimeGreaterThanDate1",
167
+ "r4/tests-fhir-r4/testLiterals/testDateTimeGreaterThanDate2",
168
+ "r4/tests-fhir-r4/testLiterals/testLiteralDateTimeTZGreater",
169
+ "r4/tests-fhir-r4/testLiterals/testLiteralDateTimeTZLess",
170
+ "r4/tests-fhir-r4/testLiterals/testLiteralDecimalGreaterThanIntegerTrue",
171
+ "r4/tests-fhir-r4/testLiterals/testLiteralDecimalLessThanInteger",
172
+ "r4/tests-fhir-r4/testLiterals/testLiteralDecimalLessThanInvalid",
173
+ "r4/tests-fhir-r4/testMatches/testMatchesSingleLineMode1",
174
+ "r4/tests-fhir-r4/testMatches/testMatchesWithinUrl1",
175
+ "r4/tests-fhir-r4/testNEquality/testNEquality13",
176
+ "r4/tests-fhir-r4/testNEquality/testNEquality15",
177
+ "r4/tests-fhir-r4/testNEquality/testNEquality16",
178
+ "r4/tests-fhir-r4/testNEquality/testNEquality17",
179
+ "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent13",
180
+ "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent17",
181
+ "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent21",
182
+ "r4/tests-fhir-r4/testObservations/testPolymorphismIsA3", // The engine returns
183
+ // false but the test
184
+ // expects null.
185
+ "r4/tests-fhir-r4/testPower/testPower3",
186
+ "r4/tests-fhir-r4/testPrecedence/testPrecedence3",
187
+ "r4/tests-fhir-r4/testPrecedence/testPrecedence4",
188
+ "r4/tests-fhir-r4/testQuantity/testQuantity5",
189
+ "r4/tests-fhir-r4/testQuantity/testQuantity6",
190
+ "r4/tests-fhir-r4/testQuantity/testQuantity7",
191
+ "r4/tests-fhir-r4/testQuantity/testQuantity8",
192
+ "r4/tests-fhir-r4/testRepeat/testRepeat1",
193
+ "r4/tests-fhir-r4/testRepeat/testRepeat2",
194
+ "r4/tests-fhir-r4/testRepeat/testRepeat3",
195
+ "r4/tests-fhir-r4/testRepeat/testRepeat4",
196
+ "r4/tests-fhir-r4/testSelect/testSelect1",
197
+ "r4/tests-fhir-r4/testSingle/testSingle2",
198
+ "r4/tests-fhir-r4/testSqrt/testSqrt2",
199
+ "r4/tests-fhir-r4/testSubSetOf/testSubSetOf1",
200
+ "r4/tests-fhir-r4/testSubSetOf/testSubSetOf2",
201
+ "r4/tests-fhir-r4/testSuperSetOf/testSuperSetOf1",
202
+ "r4/tests-fhir-r4/testSuperSetOf/testSuperSetOf2",
203
+ "r4/tests-fhir-r4/testTimeOfDay/testTimeOfDay1",
204
+ "r4/tests-fhir-r4/testToChars/testToChars1",
205
+ "r4/tests-fhir-r4/testToInteger/testToInteger4",
206
+ "r4/tests-fhir-r4/testTrace/testTrace2",
207
+ "r4/tests-fhir-r4/testType/testType1",
208
+ "r4/tests-fhir-r4/testType/testType2",
209
+ "r4/tests-fhir-r4/testType/testType3",
210
+ "r4/tests-fhir-r4/testType/testType4",
211
+ "r4/tests-fhir-r4/testType/testType6",
212
+ "r4/tests-fhir-r4/testType/testType9",
213
+ "r4/tests-fhir-r4/testType/testType10",
214
+ "r4/tests-fhir-r4/testType/testType13",
215
+ "r4/tests-fhir-r4/testType/testType14",
216
+ "r4/tests-fhir-r4/testType/testType15",
217
+ "r4/tests-fhir-r4/testType/testType16",
218
+ "r4/tests-fhir-r4/testType/testType18",
219
+ "r4/tests-fhir-r4/testType/testType19",
220
+ "r4/tests-fhir-r4/testType/testType20",
221
+ "r4/tests-fhir-r4/testType/testType21",
222
+ "r4/tests-fhir-r4/testType/testType22",
223
+ "r4/tests-fhir-r4/testType/testType23",
224
+ "r4/tests-fhir-r4/testTypes/testBooleanLiteralConvertsToQuantity",
225
+ "r4/tests-fhir-r4/testTypes/testBooleanLiteralIsNotSystemQuantity",
226
+ "r4/tests-fhir-r4/testTypes/testDecimalLiteralIsNotQuantity",
227
+ "r4/tests-fhir-r4/testTypes/testDecimalLiteralToDecimal",
228
+ "r4/tests-fhir-r4/testTypes/testDecimalLiteralToIntegerIsEmpty",
229
+ "r4/tests-fhir-r4/testTypes/testIntegerLiteralIsSystemInteger",
230
+ "r4/tests-fhir-r4/testTypes/testIntegerLiteralToInteger",
231
+ "r4/tests-fhir-r4/testTypes/testQuantityLiteralWeekToString",
232
+ "r4/tests-fhir-r4/testTypes/testStringDecimalLiteralIsNotSystemQuantity",
233
+ "r4/tests-fhir-r4/testTypes/testStringIntegerLiteralIsNotQuantity",
234
+ "r4/tests-fhir-r4/testTypes/testStringLiteralToString",
235
+ "r4/tests-fhir-r4/testTypes/testStringQuantityWeekConvertsToQuantityFalse",
236
+ "r4/tests-fhir-r4/testVariables/testVariables1",
237
+ "r4/tests-fhir-r4/testVariables/testVariables2",
238
+ "r4/tests-fhir-r4/testVariables/testVariables3",
239
+ "r4/tests-fhir-r4/testVariables/testVariables4",
240
+ "r4/tests-fhir-r4/testWhere/testWhere2",
241
+ "r4/tests-fhir-r4/testWhere/testWhere3",
242
+ "r4/tests-fhir-r4/testWhere/testWhere4",
243
+ )
244
+
245
+ fun getTestName(file: String, group: Group, test: Test): String {
246
+ return (file.replace(".xml", "") +
247
+ "/" +
248
+ group.getName() +
249
+ "/" +
250
+ (if (test.getName() != null) test.getName() else test.getExpression().getValue()))
251
+ }
252
+ }
253
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/DateTypeTest.kt ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import java.util.*
4
+ import org.hamcrest.MatcherAssert
5
+ import org.hamcrest.Matchers
6
+ import org.hl7.fhir.r4.model.DateType
7
+ import org.junit.jupiter.api.Test
8
+
9
+ internal class DateTypeTest {
10
+ @Test
11
+ fun dateType() {
12
+ // DateType Month is zero-based (11 == December)
13
+ val birthDate = DateType(1974, 11, 25)
14
+ MatcherAssert.assertThat(birthDate.year, Matchers.`is`(1974))
15
+ MatcherAssert.assertThat(birthDate.month, Matchers.`is`(11))
16
+ MatcherAssert.assertThat(birthDate.day, Matchers.`is`(25))
17
+ }
18
+
19
+ @Test
20
+ fun date() {
21
+ // NOTE: DateType uses default GMT
22
+ val birthDate = DateType(1974, 11, 25).value
23
+ val calendar = GregorianCalendar(TimeZone.getTimeZone("GMT"))
24
+ calendar.setTime(birthDate)
25
+ MatcherAssert.assertThat(calendar.get(Calendar.YEAR), Matchers.`is`(1974))
26
+ MatcherAssert.assertThat(calendar.get(Calendar.MONTH), Matchers.`is`(11))
27
+ MatcherAssert.assertThat(calendar.get(Calendar.DAY_OF_MONTH), Matchers.`is`(25))
28
+ }
29
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu2Test.kt ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import java.io.BufferedReader
6
+ import java.io.IOException
7
+ import java.io.InputStreamReader
8
+ import org.fhir.ucum.UcumException
9
+ import org.opencds.cqf.cql.engine.data.CompositeDataProvider
10
+ import org.opencds.cqf.cql.engine.fhir.model.Dstu2FhirModelResolver
11
+ import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider
12
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
13
+
14
+ class FhirHelpersDstu2Test {
15
+ private fun getStringFromResourceStream(resourceName: String): String? {
16
+ val input = TestFhirPath::class.java.getResourceAsStream(resourceName)
17
+ try {
18
+ BufferedReader(InputStreamReader(input)).use { stringReader ->
19
+ var line: String? = null
20
+ val source = StringBuilder()
21
+ while ((stringReader.readLine().also { line = it }) != null) {
22
+ source.append(line)
23
+ source.append("\n")
24
+ }
25
+ return source.toString()
26
+ }
27
+ } catch (e: IOException) {
28
+ e.printStackTrace()
29
+ }
30
+
31
+ return null
32
+ }
33
+
34
+ // @Test
35
+ @Throws(UcumException::class)
36
+ fun testFhirHelpersDstu2() {
37
+ val cql = getStringFromResourceStream("Dstu2/TestFHIRHelpersDstu2.cql")
38
+ val env = TranslatorHelper.environment
39
+ TranslatorHelper.translate(cql, env.libraryManager!!)
40
+ val engine = TranslatorHelper.getEngine(env)
41
+
42
+ val libraryId = TranslatorHelper.toElmIdentifier("TestFHIRHelpersDstu2", "0.1.0")
43
+
44
+ val modelResolver = Dstu2FhirModelResolver()
45
+ val retrieveProvider =
46
+ RestFhirRetrieveProvider(
47
+ SearchParameterResolver(modelResolver.fhirContext),
48
+ modelResolver,
49
+ FhirContext.forCached(FhirVersionEnum.DSTU2).newRestfulGenericClient(""),
50
+ )
51
+ val provider = CompositeDataProvider(modelResolver, retrieveProvider)
52
+ // BaseFhirDataProvider provider = new FhirDataProviderDstu2();
53
+ engine.environment.registerDataProvider("http://hl7.org/fhir", provider)
54
+ val results = engine.evaluate { library(libraryId) }.onlyResultOrThrow
55
+
56
+ // TODO - millis shouldn't be populated - issue with DateTime.fromJavaDate(Date date)
57
+ var value = results["TestPeriodToInterval"]!!.value
58
+ // Assertions.assertEquals(((DateTime)((Interval) value).getStart()).getPartial(),
59
+ // new
60
+ // Partial(DateTime.getFields(7), new int[] {2017, 5, 6, 18, 8, 0, 0}));
61
+ // Assertions.assertEquals(((DateTime)((Interval) value).getEnd()).getPartial(), new
62
+ // Partial(DateTime.getFields(7), new int[] {2017, 5, 6, 19, 8, 0, 0}));
63
+ value = results["TestToQuantity"]!!.value
64
+ value = results["TestRangeToInterval"]!!.value
65
+ value = results["TestToCode"]!!.value
66
+ value = results["TestToConcept"]!!.value
67
+ value = results["TestToString"]!!.value
68
+ value = results["TestRequestStatusToString"]!!.value
69
+ value = results["TestToDateTime"]!!.value
70
+ value = results["TestToTime"]!!.value
71
+ value = results["TestToInteger"]!!.value
72
+ value = results["TestToDecimal"]!!.value
73
+ value = results["TestToBoolean"]!!.value
74
+ }
75
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu3Test.kt ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import java.io.BufferedReader
4
+ import java.io.IOException
5
+ import java.io.InputStreamReader
6
+ import org.fhir.ucum.UcumException
7
+ import org.opencds.cqf.cql.engine.data.CompositeDataProvider
8
+ import org.opencds.cqf.cql.engine.fhir.model.Dstu3FhirModelResolver
9
+ import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider
10
+ import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver
11
+
12
+ class FhirHelpersDstu3Test {
13
+ private fun getStringFromResourceStream(resourceName: String): String? {
14
+ val input = TestFhirPath::class.java.getResourceAsStream(resourceName)
15
+ try {
16
+ BufferedReader(InputStreamReader(input)).use { stringReader ->
17
+ var line: String? = null
18
+ val source = StringBuilder()
19
+ while ((stringReader.readLine().also { line = it }) != null) {
20
+ source.append(line)
21
+ source.append("\n")
22
+ }
23
+ return source.toString()
24
+ }
25
+ } catch (e: IOException) {
26
+ e.printStackTrace()
27
+ }
28
+
29
+ return null
30
+ }
31
+
32
+ // @Test
33
+ // TODO: Resolve Error: Could not load model information for model FHIR, version
34
+ // 3.0.0 because version 1.0.2 is already loaded
35
+ // @Test
36
+ @Throws(UcumException::class)
37
+ fun testFhirHelpersStu3() {
38
+ val cql = getStringFromResourceStream("stu3/TestFHIRHelpers.cql")
39
+ val env = TranslatorHelper.environment
40
+ TranslatorHelper.translate(cql, env.libraryManager!!)
41
+
42
+ val engine = TranslatorHelper.getEngine(env)
43
+
44
+ val libraryId = TranslatorHelper.toElmIdentifier("TestFHIRHelpers", "0.1.0")
45
+
46
+ val modelResolver = Dstu3FhirModelResolver()
47
+ val fhirContext = modelResolver.fhirContext
48
+ val retrieveProvider =
49
+ RestFhirRetrieveProvider(
50
+ SearchParameterResolver(fhirContext),
51
+ modelResolver,
52
+ fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"),
53
+ )
54
+ val provider = CompositeDataProvider(modelResolver, retrieveProvider)
55
+ // BaseFhirDataProvider provider = new
56
+ // FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
57
+ engine.environment.registerDataProvider("http://hl7.org/fhir", provider)
58
+ val results = engine.evaluate { library(libraryId) }.onlyResultOrThrow
59
+
60
+ // TODO - fix
61
+ var value = results["TestPeriodToInterval"]!!.value
62
+ // Assertions.assertEquals(((DateTime)((Interval) value).getStart()).getPartial(),
63
+ // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 18, 8, 0}));
64
+ // Assertions.assertEquals(((DateTime)((Interval) value).getEnd()).getPartial(),
65
+ // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 19, 8, 0}));
66
+ value = results["TestToQuantity"]!!.value
67
+ // TODO: ModelInfo bug. Not aware of SimpleQuantity
68
+ value = results["TestRangeToInterval"]!!.value
69
+ value = results["TestToCode"]!!.value
70
+ value = results["TestToConcept"]!!.value
71
+ value = results["TestToString"]!!.value
72
+ value = results["TestRequestStatusToString"]!!.value
73
+ value = results["TestToDateTime"]!!.value
74
+ value = results["TestToTime"]!!.value
75
+ value = results["TestToInteger"]!!.value
76
+ value = results["TestToDecimal"]!!.value
77
+ value = results["TestToBoolean"]!!.value
78
+ }
79
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestFhirPath.kt ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import jakarta.xml.bind.JAXB
5
+ import java.io.InputStreamReader
6
+ import java.math.BigDecimal
7
+ import java.time.Instant
8
+ import java.time.ZoneOffset
9
+ import java.util.*
10
+ import java.util.function.Function
11
+ import org.cqframework.cql.cql2elm.CqlCompilerException
12
+ import org.hl7.fhir.instance.model.api.IBaseResource
13
+ import org.hl7.fhir.instance.model.api.IPrimitiveType
14
+ import org.hl7.fhirpath.TranslatorHelper.toElmIdentifier
15
+ import org.hl7.fhirpath.tests.InvalidType
16
+ import org.hl7.fhirpath.tests.Output
17
+ import org.hl7.fhirpath.tests.OutputType
18
+ import org.hl7.fhirpath.tests.Test
19
+ import org.hl7.fhirpath.tests.Tests
20
+ import org.opencds.cqf.cql.engine.data.CompositeDataProvider
21
+ import org.opencds.cqf.cql.engine.elm.executing.EqualEvaluator
22
+ import org.opencds.cqf.cql.engine.elm.executing.ToQuantityEvaluator
23
+ import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator
24
+ import org.opencds.cqf.cql.engine.exception.CqlException
25
+ import org.opencds.cqf.cql.engine.execution.EvaluationResult
26
+ import org.opencds.cqf.cql.engine.execution.State
27
+ import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri
28
+ import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver
29
+ import org.opencds.cqf.cql.engine.runtime.ClassInstance
30
+ import org.opencds.cqf.cql.engine.runtime.Date
31
+ import org.opencds.cqf.cql.engine.runtime.DateTime
32
+ import org.opencds.cqf.cql.engine.runtime.List
33
+ import org.opencds.cqf.cql.engine.runtime.Time
34
+ import org.opencds.cqf.cql.engine.runtime.Value
35
+ import org.opencds.cqf.cql.engine.runtime.toCqlBoolean
36
+ import org.opencds.cqf.cql.engine.runtime.toCqlDecimal
37
+ import org.opencds.cqf.cql.engine.runtime.toCqlInteger
38
+ import org.opencds.cqf.cql.engine.runtime.toCqlList
39
+ import org.opencds.cqf.cql.engine.runtime.toCqlString
40
+ import org.slf4j.Logger
41
+ import org.slf4j.LoggerFactory
42
+
43
+ abstract class TestFhirPath {
44
+ open class TestCase(val name: String?, val cql: String?)
45
+
46
+ class Error(name: String?, cql: String?) : TestCase(name, cql) // Compile time (Semantic) error
47
+
48
+ class Invalid(name: String?, cql: String?) : TestCase(name, cql) // Runtime (Invalid) error
49
+
50
+ class Pass(
51
+ name: String?,
52
+ cql: String?,
53
+ val resource: IBaseResource?,
54
+ val results: MutableList<Value?>?,
55
+ ) : TestCase(name, cql) // Successful execution
56
+
57
+ private val libraryId = toElmIdentifier("TestFHIRPath")
58
+ private val header =
59
+ """
60
+ library TestFHIRPath
61
+ using FHIR version '4.0.1'
62
+ include FHIRHelpers version '4.0.1' called FHIRHelpers
63
+
64
+
65
+
66
+ """
67
+ .trimIndent()
68
+
69
+ private val parametersTemplate =
70
+ """
71
+ parameter %s %s
72
+ parameter "%%context" %s
73
+ parameter "%%resource" %s
74
+ parameter "%%rootResource" %s context %s
75
+
76
+
77
+
78
+ """
79
+ .trimIndent()
80
+
81
+ private val definesTemplate =
82
+ """
83
+ define Test: %s
84
+
85
+ """
86
+ .trimIndent()
87
+
88
+ fun compareResults(
89
+ expectedResult: Value?,
90
+ actualResult: Value?,
91
+ state: State?,
92
+ resolver: FhirModelResolver<*, *, *, *, *, *, *, *>,
93
+ ): Boolean? {
94
+ // Perform FHIR system-defined type conversions
95
+ var actualResult = actualResult
96
+
97
+ if (
98
+ actualResult is ClassInstance && actualResult.type.namespaceURI == fhirModelNamespaceUri
99
+ ) {
100
+ val actualResultClass = resolver.resolveType(actualResult.type.localPart)!!
101
+ if (
102
+ actualResultClass.isEnum ||
103
+ IPrimitiveType::class.java.isAssignableFrom(actualResultClass)
104
+ ) {
105
+ actualResult = actualResult.elements["value"]
106
+ }
107
+ }
108
+
109
+ return EqualEvaluator.equal(expectedResult, actualResult, state)?.value
110
+ }
111
+
112
+ protected fun runTest(
113
+ test: Test,
114
+ basePathInput: String?,
115
+ fhirContext: FhirContext,
116
+ provider: CompositeDataProvider?,
117
+ resolver: FhirModelResolver<*, *, *, *, *, *, *, *>,
118
+ ) {
119
+ val testCase = buildTestCase(test, basePathInput, fhirContext)
120
+ val engine = TranslatorHelper.getEngine(testCase.cql!!)
121
+ engine.state.environment.registerDataProvider("http://hl7.org/fhir", provider)
122
+ if (testCase is Pass && testCase.resource != null) {
123
+ val resource = testCase.resource
124
+ val resourceAsCqlValue = resolver.toCqlValue(resource)
125
+ engine.state.setParameter(null, resource.fhirType(), resourceAsCqlValue)
126
+ engine.state.setParameter(null, "%context", resourceAsCqlValue)
127
+ engine.state.setParameter(null, "%resource", resourceAsCqlValue)
128
+ engine.state.setParameter(null, "%rootResource", resourceAsCqlValue)
129
+ }
130
+
131
+ var result: EvaluationResult?
132
+ try {
133
+ result =
134
+ engine
135
+ .evaluate {
136
+ library(libraryId)
137
+ parameters = engine.state.parameters
138
+ }
139
+ .onlyResultOrThrow
140
+ } catch (e: CqlException) {
141
+ if (testCase is Pass) {
142
+ throw failWithContext(
143
+ "Runtime error and was expecting a result",
144
+ testCase,
145
+ "N/A".toCqlString(),
146
+ e,
147
+ )
148
+ }
149
+
150
+ if (testCase is Error && e.cause is CqlCompilerException) {
151
+ return // Expected a compile time error.
152
+ }
153
+
154
+ if (testCase is Invalid) {
155
+ return // Expected a runtime error
156
+ }
157
+
158
+ log.warn(
159
+ "%s failed as expected, but unable to determine the cause of the failure. Possible bug in engine. Skipping."
160
+ .format(testCase.name)
161
+ )
162
+ return
163
+ }
164
+
165
+ if (testCase is Invalid) {
166
+ log.warn(
167
+ "%s was marked as Invalid, but it got a result. Possible bug in test suite. Skipping."
168
+ .format(testCase.name)
169
+ )
170
+ return
171
+ }
172
+
173
+ val testValue = result["Test"]!!.value
174
+ val actualList =
175
+ if (testValue == null) List.EMPTY_LIST
176
+ else if (testValue is List) testValue else listOf(testValue).toCqlList()
177
+
178
+ // Catch-all to prevent ClassCastException
179
+ if (testCase !is Pass) {
180
+ throw failWithContext(
181
+ "expected a non-Pass test case for %s, but got %s"
182
+ .format(testCase.name, testCase.javaClass.getSimpleName()),
183
+ testCase,
184
+ actualList,
185
+ null,
186
+ )
187
+ }
188
+
189
+ // Invalid and Semantic errors have been handled above, so we can assume Pass here
190
+ if (actualList.count() != testCase.results!!.size) {
191
+ throw failWithContext(
192
+ "Incorrect number of results. Expected %d, Actual %d"
193
+ .format(testCase.results.size, actualList.count()),
194
+ testCase,
195
+ actualList,
196
+ null,
197
+ )
198
+ }
199
+
200
+ for (i in actualList.toList().indices) {
201
+ val expected = testCase.results[i]
202
+ val actual = actualList.elementAt(i)
203
+ val comparison = compareResults(expected, actual, engine.state, resolver)
204
+ if (true != comparison) {
205
+ throw failWithContext(
206
+ "Result mismatch at index %d".format(i),
207
+ testCase,
208
+ actual,
209
+ null,
210
+ )
211
+ }
212
+ }
213
+ }
214
+
215
+ private fun buildTestCase(
216
+ test: Test,
217
+ basePathInput: String?,
218
+ fhirContext: FhirContext,
219
+ ): TestCase {
220
+ val resource =
221
+ Optional.ofNullable<String?>(test.getInputfile())
222
+ .map<IBaseResource>(
223
+ Function { inputFile: String? ->
224
+ loadResourceFile(basePathInput + inputFile, fhirContext)
225
+ }
226
+ )
227
+ .orElse(null)
228
+
229
+ val cql = buildCql(test, resource)
230
+ val invalid =
231
+ Optional.ofNullable<InvalidType>(test.getExpression().getInvalid())
232
+ .orElse(InvalidType.FALSE)
233
+ val expectedResults = loadExpectedResults(test)
234
+ return when (invalid) {
235
+ InvalidType.TRUE -> Invalid(test.getName(), cql)
236
+ InvalidType.SEMANTIC -> Error(test.getName(), cql)
237
+ InvalidType.FALSE -> Pass(test.getName(), cql, resource, expectedResults)
238
+ }
239
+ }
240
+
241
+ private fun buildCql(test: Test, resource: IBaseResource?): String {
242
+ val inputExpression = test.getExpression().getValue()
243
+ val predicate = Optional.ofNullable<kotlin.Boolean>(test.isPredicate).orElse(false)
244
+ val expressionOutput = test.getOutput().size == 1 && test.getOutput()[0].getType() == null
245
+
246
+ var testExpression = inputExpression
247
+ if (predicate) {
248
+ testExpression = "exists { %s }".format(inputExpression)
249
+ } else if (expressionOutput) {
250
+ val outputExpression = test.getOutput()[0].getValue()
251
+ testExpression =
252
+ if ("null" == outputExpression) {
253
+ "(%s) is %s".format(inputExpression, outputExpression)
254
+ } else if ("{ }" == outputExpression) {
255
+ "not exists (%s)".format(inputExpression)
256
+ } else if ("null" == inputExpression) {
257
+ "(%s) is %s".format(outputExpression, inputExpression)
258
+ } else {
259
+ "(%s) = (%s)".format(inputExpression, outputExpression)
260
+ }
261
+ }
262
+
263
+ // if have a resource, add the CQL parameters.
264
+ val params =
265
+ Optional.ofNullable<IBaseResource?>(resource)
266
+ .map(
267
+ Function { res: IBaseResource? ->
268
+ parametersTemplate.format(
269
+ *Collections.nCopies(6, res!!.fhirType()).toTypedArray()
270
+ )
271
+ }
272
+ )
273
+ .orElse("")
274
+
275
+ val defines: String = definesTemplate.format(testExpression)
276
+ return header + params + defines
277
+ }
278
+
279
+ private fun failWithContext(
280
+ message: String?,
281
+ test: TestCase,
282
+ actual: Value?,
283
+ e: Exception?,
284
+ ): RuntimeException {
285
+ val expectedString =
286
+ if (test is Pass) ToStringEvaluator.toString(test.results?.toCqlList()) else "N/A"
287
+ val actualString = ToStringEvaluator.toString(actual)
288
+ val error =
289
+ """
290
+ Failed Test: %s
291
+ - Message: %s
292
+ - Expected: %s
293
+ - Actual: %s
294
+ - CQL:%n%n%s
295
+
296
+ """
297
+ .trimIndent()
298
+ return RuntimeException(
299
+ error.format(test.name, message, expectedString, actualString, test.cql),
300
+ e,
301
+ )
302
+ }
303
+
304
+ private fun loadResourceFile(resourceFilePath: String, context: FhirContext): IBaseResource? {
305
+ return context
306
+ .newXmlParser()
307
+ .parseResource(
308
+ InputStreamReader(TestFhirPath::class.java.getResourceAsStream(resourceFilePath)!!)
309
+ )
310
+ }
311
+
312
+ private fun readOutput(output: Output): Value? {
313
+ if (output.getType() == null) {
314
+ return null
315
+ }
316
+
317
+ return when (output.getType()) {
318
+ OutputType.BOOLEAN -> output.getValue().toBoolean().toCqlBoolean()
319
+ OutputType.DECIMAL -> BigDecimal(output.getValue()).toCqlDecimal()
320
+ OutputType.DATE -> Date(output.getValue())
321
+ OutputType.DATE_TIME ->
322
+ DateTime(
323
+ output.getValue(),
324
+ ZoneOffset.systemDefault().rules.getOffset(Instant.now()),
325
+ )
326
+
327
+ OutputType.TIME -> Time(output.getValue())
328
+ OutputType.INTEGER -> output.getValue().toInt().toCqlInteger()
329
+ OutputType.STRING,
330
+ OutputType.CODE -> output.getValue().toCqlString()
331
+ OutputType.QUANTITY -> ToQuantityEvaluator.toQuantity(output.getValue())
332
+ else ->
333
+ throw IllegalArgumentException(
334
+ "Output type [ %s ] is not supported in tests"
335
+ .format(if (output.getType() == null) "null" else output.getType())
336
+ )
337
+ }
338
+ }
339
+
340
+ private fun loadExpectedResults(test: Test): MutableList<Value?> {
341
+ // Special case for tests are "expression output" tests, which have a single output with no
342
+ // type
343
+ if (test.getOutput().size == 1 && test.getOutput()[0].getType() == null) {
344
+ return mutableListOf(org.opencds.cqf.cql.engine.runtime.Boolean.TRUE)
345
+ }
346
+
347
+ return test.getOutput()!!.map { this.readOutput(it) }.toMutableList()
348
+ }
349
+
350
+ companion object {
351
+ private val log: Logger = LoggerFactory.getLogger(TestFhirPath::class.java)
352
+
353
+ @JvmStatic
354
+ protected fun loadTestsFile(testsFilePath: String): Tests? {
355
+ try {
356
+ val testsFileRaw = TestFhirPath::class.java.getResourceAsStream(testsFilePath)
357
+ return JAXB.unmarshal(testsFileRaw, Tests::class.java)
358
+ } catch (e: Exception) {
359
+ // e.printStackTrace();
360
+ throw IllegalArgumentException(
361
+ "Couldn't load tests file [ %s ]".format(testsFilePath),
362
+ e,
363
+ )
364
+ }
365
+ }
366
+ }
367
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestLibrarySourceProvider.kt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import kotlinx.io.Source
4
+ import kotlinx.io.asSource
5
+ import kotlinx.io.buffered
6
+ import org.cqframework.cql.cql2elm.LibraryContentType
7
+ import org.cqframework.cql.cql2elm.LibrarySourceProvider
8
+ import org.hl7.elm.r1.VersionedIdentifier
9
+
10
+ class TestLibrarySourceProvider : LibrarySourceProvider {
11
+ override fun getLibrarySource(libraryIdentifier: VersionedIdentifier): Source? {
12
+ val libraryFileName =
13
+ "stu3/${libraryIdentifier.id}${if (libraryIdentifier.version != null) "-${libraryIdentifier.version}" else ""}.cql"
14
+ val inputStream = TestLibrarySourceProvider::class.java.getResourceAsStream(libraryFileName)
15
+ return inputStream?.asSource()?.buffered()
16
+ }
17
+
18
+ override fun getLibraryContent(
19
+ libraryIdentifier: VersionedIdentifier,
20
+ type: LibraryContentType,
21
+ ): Source? {
22
+ if (LibraryContentType.CQL == type) {
23
+ return getLibrarySource(libraryIdentifier)
24
+ }
25
+
26
+ return null
27
+ }
28
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TranslatorHelper.kt ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.hl7.fhirpath
2
+
3
+ import org.cqframework.cql.cql2elm.CqlCompiler
4
+ import org.cqframework.cql.cql2elm.CqlCompilerException.ErrorSeverity
5
+ import org.cqframework.cql.cql2elm.CqlCompilerOptions
6
+ import org.cqframework.cql.cql2elm.CqlCompilerOptions.Companion.defaultOptions
7
+ import org.cqframework.cql.cql2elm.LibraryManager
8
+ import org.cqframework.cql.cql2elm.ModelManager
9
+ import org.cqframework.cql.cql2elm.StringLibrarySourceProvider
10
+ import org.cqframework.cql.cql2elm.quick.FhirLibrarySourceProvider
11
+ import org.fhir.ucum.UcumException
12
+ import org.hl7.elm.r1.Library
13
+ import org.hl7.elm.r1.VersionedIdentifier
14
+ import org.opencds.cqf.cql.engine.execution.CqlEngine
15
+ import org.opencds.cqf.cql.engine.execution.Environment
16
+ import org.opencds.cqf.cql.engine.terminology.TerminologyProvider
17
+
18
+ object TranslatorHelper {
19
+ // Shared model cache — thread-safe (ConcurrentHashMap)
20
+ private val globalModelCache =
21
+ org.cqframework.cql.cql2elm.utils.createConcurrentHashMap<
22
+ org.hl7.cql.model.ModelIdentifier,
23
+ org.cqframework.cql.cql2elm.model.Model,
24
+ >()
25
+
26
+ private fun defaultCompilerOptions(): CqlCompilerOptions {
27
+ val options = defaultOptions()
28
+ options.options.remove(CqlCompilerOptions.Options.DisableListDemotion)
29
+ options.options.remove(CqlCompilerOptions.Options.DisableListPromotion)
30
+ options.options.add(CqlCompilerOptions.Options.EnableDateRangeOptimization)
31
+ options.options.add(CqlCompilerOptions.Options.EnableResultTypes)
32
+ return options
33
+ }
34
+
35
+ // Pre-compile FHIRHelpers and other shared libraries once, then reuse the cache.
36
+ private val sharedLibraryCache:
37
+ Map<VersionedIdentifier, org.cqframework.cql.cql2elm.model.CompiledLibrary> by lazy {
38
+ val warmupManager = newLibraryManagerInternal(defaultCompilerOptions(), emptyMap())
39
+ warmupManager.librarySourceLoader.registerProvider(
40
+ StringLibrarySourceProvider(
41
+ listOf(
42
+ "library Warmup using FHIR version '4.0.1' include FHIRHelpers version '4.0.1' define X: 1"
43
+ )
44
+ )
45
+ )
46
+ val compiler = CqlCompiler(libraryManager = warmupManager)
47
+ compiler.run(
48
+ "library Warmup using FHIR version '4.0.1' include FHIRHelpers version '4.0.1' define X: 1"
49
+ )
50
+ // Return only the shared dependency libraries (not the warmup library itself)
51
+ warmupManager.compiledLibraries.filter { it.key.id != "Warmup" }
52
+ }
53
+
54
+ private fun newLibraryManagerInternal(
55
+ cqlCompilerOptions: CqlCompilerOptions,
56
+ precompiledLibraries:
57
+ Map<VersionedIdentifier, org.cqframework.cql.cql2elm.model.CompiledLibrary>,
58
+ ): LibraryManager {
59
+ val modelManager = ModelManager(globalCache = globalModelCache)
60
+ val libraryCache = HashMap(precompiledLibraries)
61
+ val libraryManager =
62
+ LibraryManager(modelManager, cqlCompilerOptions, libraryCache = libraryCache)
63
+ libraryManager.librarySourceLoader.clearProviders()
64
+ libraryManager.librarySourceLoader.registerProvider(TestLibrarySourceProvider())
65
+ libraryManager.librarySourceLoader.registerProvider(FhirLibrarySourceProvider())
66
+ return libraryManager
67
+ }
68
+
69
+ private fun newLibraryManager(): LibraryManager {
70
+ return newLibraryManagerInternal(defaultCompilerOptions(), sharedLibraryCache)
71
+ }
72
+
73
+ @JvmStatic
74
+ fun getEngine(cql: String): CqlEngine {
75
+ return getEngine(getEnvironment(cql))
76
+ }
77
+
78
+ fun getEnvironment(cql: String): Environment {
79
+ val env = getEnvironment(null as TerminologyProvider?)
80
+ env.libraryManager!!
81
+ .librarySourceLoader
82
+ .registerProvider(StringLibrarySourceProvider(listOf(cql)))
83
+ return env
84
+ }
85
+
86
+ val environment: Environment
87
+ get() = getEnvironment(null as TerminologyProvider?)
88
+
89
+ fun getEnvironment(terminologyProvider: TerminologyProvider?): Environment {
90
+ return Environment(newLibraryManager(), null, terminologyProvider)
91
+ }
92
+
93
+ fun getEngine(environment: Environment?): CqlEngine {
94
+ return CqlEngine(environment!!, mutableSetOf(CqlEngine.Options.EnableTypeChecking))
95
+ }
96
+
97
+ @JvmStatic
98
+ fun toElmIdentifier(name: String?): VersionedIdentifier {
99
+ return VersionedIdentifier().withId(name)
100
+ }
101
+
102
+ @JvmStatic
103
+ fun toElmIdentifier(name: String?, version: String?): VersionedIdentifier {
104
+ return VersionedIdentifier().withId(name).withVersion(version)
105
+ }
106
+
107
+ @Throws(UcumException::class)
108
+ fun translate(cql: String?, libraryManager: LibraryManager): Library {
109
+ val compiler = CqlCompiler(libraryManager = libraryManager)
110
+ val lib = compiler.run(cql!!)
111
+
112
+ libraryManager.compiledLibraries[lib.identifier!!] = compiler.compiledLibrary!!
113
+
114
+ val errors = compiler.exceptions.filter { it.severity == ErrorSeverity.Error }
115
+ if (errors.isNotEmpty()) {
116
+ val messages = mutableListOf<String>()
117
+ for (error in compiler.exceptions) {
118
+ val tb = error.locator
119
+ val lines =
120
+ if (tb == null) "[n/a]"
121
+ else
122
+ String.format(
123
+ "[%d:%d, %d:%d]",
124
+ tb.startLine,
125
+ tb.startChar,
126
+ tb.endLine,
127
+ tb.endChar,
128
+ )
129
+ messages.add(lines + error.message)
130
+ }
131
+ throw IllegalArgumentException(messages.toString())
132
+ }
133
+
134
+ return lib
135
+ }
136
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/Dstu3FhirTest.kt ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import ca.uhn.fhir.parser.IParser
6
+ import ca.uhn.fhir.rest.client.api.IGenericClient
7
+ import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor
8
+ import com.github.tomakehurst.wiremock.WireMockServer
9
+ import com.github.tomakehurst.wiremock.client.MappingBuilder
10
+ import com.github.tomakehurst.wiremock.client.WireMock
11
+ import java.net.ServerSocket
12
+ import org.hl7.fhir.dstu3.model.Bundle
13
+ import org.hl7.fhir.dstu3.model.CapabilityStatement
14
+ import org.hl7.fhir.dstu3.model.OperationOutcome
15
+ import org.hl7.fhir.dstu3.model.Resource
16
+ import org.junit.jupiter.api.AfterEach
17
+ import org.junit.jupiter.api.BeforeEach
18
+
19
+ open class Dstu3FhirTest {
20
+ var wireMockServer: WireMockServer? = null
21
+ var wireMock: WireMock? = null
22
+
23
+ @BeforeEach
24
+ fun start() {
25
+ wireMockServer = WireMockServer(httpPort)
26
+ wireMockServer!!.start()
27
+ WireMock.configureFor("localhost", httpPort)
28
+ wireMock = WireMock("localhost", httpPort)
29
+
30
+ mockFhirRead("/metadata", this.capabilityStatement)
31
+ }
32
+
33
+ @AfterEach
34
+ fun stop() {
35
+ wireMockServer!!.stop()
36
+ }
37
+
38
+ fun mockNotFound(resource: String?) {
39
+ val outcome = OperationOutcome()
40
+ outcome.getText().statusAsString = "generated"
41
+ outcome.issueFirstRep
42
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
43
+ .setCode(OperationOutcome.IssueType.PROCESSING)
44
+ .setDiagnostics(resource)
45
+
46
+ mockFhirRead(resource, outcome, 404)
47
+ }
48
+
49
+ fun mockFhirRead(resource: Resource) {
50
+ val resourcePath = "/" + resource.fhirType() + "/" + resource.getId()
51
+ mockFhirInteraction(resourcePath, resource)
52
+ }
53
+
54
+ @JvmOverloads
55
+ fun mockFhirRead(path: String?, resource: Resource?, statusCode: Int = 200) {
56
+ val builder = WireMock.get(WireMock.urlEqualTo(path))
57
+ mockFhirInteraction(builder, resource, statusCode)
58
+ }
59
+
60
+ fun mockFhirSearch(path: String?, vararg resources: Resource) {
61
+ val builder = WireMock.get(WireMock.urlEqualTo(path))
62
+ mockFhirInteraction(builder, makeBundle(*resources))
63
+ }
64
+
65
+ fun mockFhirPost(path: String?, resource: Resource?) {
66
+ mockFhirInteraction(WireMock.post(WireMock.urlEqualTo(path)), resource, 200)
67
+ }
68
+
69
+ fun mockFhirInteraction(path: String?, resource: Resource?) {
70
+ mockFhirRead(path, resource, 200)
71
+ }
72
+
73
+ @JvmOverloads
74
+ fun mockFhirInteraction(builder: MappingBuilder, resource: Resource?, statusCode: Int = 200) {
75
+ var body: String? = null
76
+ if (resource != null) {
77
+ body = fhirParser!!.encodeResourceToString(resource)
78
+ }
79
+
80
+ WireMock.stubFor(
81
+ builder.willReturn(
82
+ WireMock.aResponse()
83
+ .withStatus(statusCode)
84
+ .withHeader("Content-Type", "application/json")
85
+ .withBody(body)
86
+ )
87
+ )
88
+ }
89
+
90
+ val capabilityStatement: CapabilityStatement
91
+ get() {
92
+ val metadata = CapabilityStatement()
93
+ metadata.setFhirVersion("3.0.2")
94
+ return metadata
95
+ }
96
+
97
+ fun makeBundle(resources: MutableList<out Resource>): Bundle {
98
+ return makeBundle(*resources.toTypedArray())
99
+ }
100
+
101
+ fun makeBundle(vararg resources: Resource): Bundle {
102
+ val bundle = Bundle()
103
+ bundle.setType(Bundle.BundleType.SEARCHSET)
104
+ bundle.setTotal(resources.size)
105
+ for (l in resources) {
106
+ bundle.addEntry().setResource(l).setFullUrl("/" + l.fhirType() + "/" + l.getId())
107
+ }
108
+ return bundle
109
+ }
110
+
111
+ companion object {
112
+ val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.DSTU3)
113
+ val fhirParser: IParser? = fhirContext.newJsonParser().setPrettyPrint(true)
114
+ private var HTTP_PORT = 0
115
+
116
+ val httpPort: Int
117
+ get() {
118
+ if (HTTP_PORT == 0) {
119
+ try {
120
+ ServerSocket(0).use { socket -> HTTP_PORT = socket.getLocalPort() }
121
+ } catch (ex: Exception) {
122
+ throw RuntimeException(
123
+ "Failed to determine a port for the wiremock server",
124
+ ex,
125
+ )
126
+ }
127
+ }
128
+ return HTTP_PORT
129
+ }
130
+
131
+ fun newClient(): IGenericClient {
132
+ val client: IGenericClient =
133
+ fhirContext.newRestfulGenericClient("http://localhost:$httpPort/")
134
+
135
+ val logger = LoggingInterceptor()
136
+ logger.setLogRequestSummary(true)
137
+ logger.setLogResponseBody(true)
138
+ client.registerInterceptor(logger)
139
+
140
+ return client
141
+ }
142
+ }
143
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/R4FhirTest.kt ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir
2
+
3
+ import ca.uhn.fhir.context.FhirContext
4
+ import ca.uhn.fhir.context.FhirVersionEnum
5
+ import ca.uhn.fhir.parser.IParser
6
+ import ca.uhn.fhir.rest.client.api.IGenericClient
7
+ import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor
8
+ import com.github.tomakehurst.wiremock.WireMockServer
9
+ import com.github.tomakehurst.wiremock.client.MappingBuilder
10
+ import com.github.tomakehurst.wiremock.client.WireMock
11
+ import java.net.ServerSocket
12
+ import org.hl7.fhir.r4.model.Bundle
13
+ import org.hl7.fhir.r4.model.CapabilityStatement
14
+ import org.hl7.fhir.r4.model.Enumerations
15
+ import org.hl7.fhir.r4.model.OperationOutcome
16
+ import org.hl7.fhir.r4.model.Resource
17
+ import org.junit.jupiter.api.AfterEach
18
+ import org.junit.jupiter.api.BeforeEach
19
+
20
+ abstract class R4FhirTest {
21
+ var wireMockServer: WireMockServer? = null
22
+ var wireMock: WireMock? = null
23
+
24
+ @BeforeEach
25
+ fun start() {
26
+ wireMockServer = WireMockServer(httpPort)
27
+ wireMockServer!!.start()
28
+ WireMock.configureFor("localhost", httpPort)
29
+ wireMock = WireMock("localhost", httpPort)
30
+
31
+ mockFhirRead("/metadata", this.capabilityStatement)
32
+ }
33
+
34
+ @AfterEach
35
+ fun stop() {
36
+ wireMockServer!!.stop()
37
+ }
38
+
39
+ fun mockNotFound(resource: String?) {
40
+ val outcome = OperationOutcome()
41
+ outcome.getText().statusAsString = "generated"
42
+ outcome.issueFirstRep
43
+ .setSeverity(OperationOutcome.IssueSeverity.ERROR)
44
+ .setCode(OperationOutcome.IssueType.PROCESSING)
45
+ .setDiagnostics(resource)
46
+
47
+ mockFhirRead(resource, outcome, 404)
48
+ }
49
+
50
+ fun mockFhirRead(resource: Resource) {
51
+ val resourcePath = "/" + resource.fhirType() + "/" + resource.getId()
52
+ mockFhirInteraction(resourcePath, resource)
53
+ }
54
+
55
+ @JvmOverloads
56
+ fun mockFhirRead(path: String?, resource: Resource?, statusCode: Int = 200) {
57
+ val builder = WireMock.get(WireMock.urlEqualTo(path))
58
+ mockFhirInteraction(builder, resource, statusCode)
59
+ }
60
+
61
+ fun mockFhirSearch(path: String?, vararg resources: Resource) {
62
+ val builder = WireMock.get(WireMock.urlEqualTo(path))
63
+ mockFhirInteraction(builder, makeBundle(*resources))
64
+ }
65
+
66
+ fun mockFhirPost(path: String?, resource: Resource?) {
67
+ mockFhirInteraction(WireMock.post(WireMock.urlEqualTo(path)), resource, 200)
68
+ }
69
+
70
+ fun mockFhirInteraction(path: String?, resource: Resource?) {
71
+ mockFhirRead(path, resource, 200)
72
+ }
73
+
74
+ @JvmOverloads
75
+ fun mockFhirInteraction(builder: MappingBuilder, resource: Resource?, statusCode: Int = 200) {
76
+ var body: String? = null
77
+ if (resource != null) {
78
+ body = fhirParser.encodeResourceToString(resource)
79
+ }
80
+
81
+ WireMock.stubFor(
82
+ builder.willReturn(
83
+ WireMock.aResponse()
84
+ .withStatus(statusCode)
85
+ .withHeader("Content-Type", "application/json")
86
+ .withBody(body)
87
+ )
88
+ )
89
+ }
90
+
91
+ val capabilityStatement: CapabilityStatement
92
+ get() {
93
+ val metadata = CapabilityStatement()
94
+ metadata.setFhirVersion(Enumerations.FHIRVersion._4_0_1)
95
+ return metadata
96
+ }
97
+
98
+ fun makeBundle(resources: MutableList<out Resource>): Bundle {
99
+ return makeBundle(*resources.toTypedArray())
100
+ }
101
+
102
+ fun makeBundle(vararg resources: Resource): Bundle {
103
+ val bundle = Bundle()
104
+ bundle.setType(Bundle.BundleType.SEARCHSET)
105
+ bundle.setTotal(resources.size)
106
+ for (l in resources) {
107
+ bundle.addEntry().setResource(l).setFullUrl("/" + l.fhirType() + "/" + l.getId())
108
+ }
109
+ return bundle
110
+ }
111
+
112
+ companion object {
113
+ val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.R4)
114
+ val fhirParser: IParser = fhirContext.newJsonParser().setPrettyPrint(true)
115
+ private var HTTP_PORT = 0
116
+
117
+ val httpPort: Int
118
+ get() {
119
+ if (HTTP_PORT == 0) {
120
+ try {
121
+ ServerSocket(0).use { socket -> HTTP_PORT = socket.getLocalPort() }
122
+ } catch (ex: Exception) {
123
+ throw RuntimeException(
124
+ "Failed to determine a port for the wiremock server",
125
+ ex,
126
+ )
127
+ }
128
+ }
129
+ return HTTP_PORT
130
+ }
131
+
132
+ fun newClient(): IGenericClient {
133
+ val client: IGenericClient =
134
+ fhirContext.newRestfulGenericClient("http://localhost:$httpPort/")
135
+
136
+ val logger = LoggingInterceptor()
137
+ logger.setLogRequestSummary(true)
138
+ logger.setLogResponseBody(true)
139
+ client.registerInterceptor(logger)
140
+ return client
141
+ }
142
+ }
143
+ }
source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/ConverterTestUtils.kt ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ package org.opencds.cqf.cql.engine.fhir.converter
2
+
3
+ import java.time.LocalDateTime
4
+ import java.time.Month
5
+ import java.time.format.DateTimeFormatter
6
+
7
+ object ConverterTestUtils {
8
+ val DST_2022_11_01: LocalDateTime = LocalDateTime.of(2022, Month.NOVEMBER, 1, 0, 0, 0)
9
+ val DST_2023_11_01: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 1, 0, 0, 0)
10
+ val DST_2023_11_03: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 3, 0, 0, 0)
11
+ val NON_DST_2022_01_01: LocalDateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 0, 0, 0)
12
+ val NON_DST_2023_01_01: LocalDateTime = LocalDateTime.of(2023, Month.JANUARY, 1, 0, 0, 0)
13
+ val NON_DST_2022_11_10: LocalDateTime = LocalDateTime.of(2022, Month.NOVEMBER, 10, 0, 0, 0)
14
+ val NON_DST_2023_11_10: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 10, 0, 0, 0)
15
+ val NON_DST_2023_11_14: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 14, 0, 0, 0)
16
+ @JvmField val YYYY_MM_DD: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
17
+
18
+ @JvmStatic
19
+ fun dateTimes(): Array<Array<Any?>?> {
20
+ return arrayOf(
21
+ arrayOf(DST_2023_11_01, DST_2023_11_01, DST_2023_11_03),
22
+ arrayOf(NON_DST_2023_11_14, NON_DST_2023_11_10, NON_DST_2023_11_14),
23
+ arrayOf(NON_DST_2023_11_14, DST_2023_11_01, DST_2023_11_03),
24
+ arrayOf(DST_2023_11_01, NON_DST_2023_11_10, NON_DST_2023_11_14),
25
+ )
26
+ }
27
+
28
+ @JvmStatic
29
+ fun startAndEndTimes(): Array<Array<Any?>?> {
30
+ return arrayOf(
31
+ arrayOf(DST_2023_11_01, DST_2023_11_03),
32
+ arrayOf(NON_DST_2023_11_10, NON_DST_2023_11_14),
33
+ arrayOf(DST_2023_11_01, DST_2023_11_03),
34
+ arrayOf(NON_DST_2023_11_10, NON_DST_2023_11_14),
35
+ arrayOf(DST_2022_11_01, DST_2023_11_03),
36
+ arrayOf(NON_DST_2022_11_10, NON_DST_2023_11_10),
37
+ arrayOf(NON_DST_2022_01_01, NON_DST_2023_01_01),
38
+ )
39
+ }
40
+
41
+ @JvmStatic
42
+ fun startAndEndYears(): Array<Array<Any?>?> {
43
+ return arrayOf(
44
+ arrayOf(DST_2022_11_01, 2019, 2020),
45
+ arrayOf(NON_DST_2023_11_14, 2019, 2020),
46
+ arrayOf(DST_2022_11_01, 2018, 2022),
47
+ arrayOf(NON_DST_2023_11_14, 2018, 2022),
48
+ )
49
+ }
50
+
51
+ @JvmStatic
52
+ fun nowsAndEvaluationTimes(): Array<Array<Any?>?> {
53
+ return arrayOf(
54
+ arrayOf(NON_DST_2022_01_01, NON_DST_2023_01_01),
55
+ arrayOf(DST_2022_11_01, NON_DST_2023_01_01),
56
+ arrayOf(NON_DST_2022_11_10, NON_DST_2023_01_01),
57
+ )
58
+ }
59
+ }