diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/README.md b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3b21fd61e7602c464fd5275085a47edcdf13d61f --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/README.md @@ -0,0 +1,16 @@ +# engine-fhir + +This module contains the implementation of the FHIR model resolvers and retrieve providers for the CQL engine, based on the HAPI FHIR library. + + +## Converting from HAPI FHIR structures to engine value types + +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: + +- 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, +- checks max cardinality to determine if a CQL list or a singleton to use as the value, +- if the child FHIR element has no values, sets the element value to `null` in the tuple. + +In general, the least nested structure is chosen for the value of an element, e.g.: +- when the element is List-typed but has no values, `null` is chosen instead of an empty list +- 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 }` diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/build.gradle.kts b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/build.gradle.kts new file mode 100644 index 0000000000000000000000000000000000000000..a19e4e2b8159fe420094faf9ca121933d896e50d --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/build.gradle.kts @@ -0,0 +1,49 @@ +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl + +plugins { + id("cql.xjc-conventions") + id("cql.fhir-kotlin-multiplatform-conventions") +} + +val generateFhirPathTests = + tasks.register("generateFhirPathTests") { + outputDir.set( + project.layout.buildDirectory.dir("generated/sources/engine-fhir/jvmTest/java") + ) + schema.set("${projectDir}/src/jvmTest/resources/org/hl7/fhirpath/testSchema") + extraArgs.set(listOf("-npa", "-p", "org.hl7.fhirpath.tests")) + } + +kotlin { + js { outputModuleName = "engine-fhir" } + + @OptIn(ExperimentalWasmDsl::class) wasmJs { outputModuleName = "engine-fhir" } + + sourceSets { + commonMain { dependencies { api(project(":engine")) } } + + jvmMain { dependencies { api(project(":ucum")) } } + + jvmTest { + dependencies { + implementation(libs.wiremock) + implementation(project(":cql-to-elm")) + implementation(project(":quick")) + implementation(libs.hapi.fhir.client) + + // JAXB runtime deps needed for the classes generated by xjc + implementation(libs.jaxb2.commons.basics) + implementation(libs.jaxb2.commons.fluent.api) + implementation(libs.jakarta.xml.bind.api) + implementation(libs.jaxb.runtime) + implementation(libs.moxy) + } + } + } +} + +java { + sourceSets { named("jvmTest") { java { srcDir(generateFhirPathTests.map { it.outputDir }) } } } +} + +dependencies { kover(project(":engine")) } diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/detekt-baseline.xml b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/detekt-baseline.xml new file mode 100644 index 0000000000000000000000000000000000000000..9390aa82e26d5fc1d158c49496e621be8bfc7eee --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/detekt-baseline.xml @@ -0,0 +1,250 @@ + + + + + ComplexCondition:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$context != null && context == "Patient" && contextValue != null && contextPath != null + ComplexCondition:Parser.kt$jsonObject.containsKey(propertyKeyWithType) || (type is ClassType && isFhirPrimitiveType(type) && jsonObject.containsKey("_$propertyKeyWithType")) + ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.<no name provided>$PATIENT == dataType && PATIENT == context && ID == contextPath && _PATIENT_123 == contextValue + ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.<no name provided>$PATIENT == dataType && PRACTITIONER == context && GENERAL_PRACTITIONER == contextPath && equals + ComplexCondition:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.<no name provided>$PRACTITIONER == dataType && PATIENT == context && ID == codePath && codesEqual(codes, PRACTITIONER_SLASH + XYZ) + CyclomaticComplexMethod:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( codes: Iterable<Code?>?, valueSet: String?, ): MutableList<TokenOrListParam> + CyclomaticComplexMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toCqlType(value: Any?): Value? + CyclomaticComplexMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toFhirType(value: Value?): IBase? + CyclomaticComplexMethod:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + CyclomaticComplexMethod:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance? + CyclomaticComplexMethod:FhirModelResolver.kt$FhirModelResolver$private fun resolveTypeUncached(typeName: String?): Class<*>? + CyclomaticComplexMethod:FhirModelResolverTest.kt$private fun validateCqlValueAgainstModel( fhirVersion: FhirVersionEnum, expectedFhirTypeName: String, cqlValue: Any?, ) + CyclomaticComplexMethod:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value? + CyclomaticComplexMethod:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + CyclomaticComplexMethod:R5FhirModelResolver.kt$R5FhirModelResolver$override fun resolveType(typeName: String?): Class<*>? + CyclomaticComplexMethod:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String + CyclomaticComplexMethod:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, ) + CyclomaticComplexMethod:TestR4ModelResolver.kt$TestR4ModelResolver$@Test @Throws(Exception::class) fun modelInfo401Tests() + ForbiddenComment:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$// TODO: Think about how to best handle the decision to expand value sets... Should it be part + ForbiddenComment:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$// TODO: This assumes the code path will always be a token param. + ForbiddenComment:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id, + ForbiddenComment:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in HAPI. + ForbiddenComment:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$// TODO: Deal with the case that the value is expressed as an expression extension + ForbiddenComment:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$// TODO: What to do if/when System is not provided... + ForbiddenComment:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id, + ForbiddenComment:FhirBundleCursor.kt$FhirBundleCursor.FhirBundleIterator$// TODO: It would be possible to get here if the next link was present, but the returned + ForbiddenComment:FhirExecutionMultiLibTestBase.kt$FhirExecutionMultiLibTestBase.Companion$// TODO: LD: figure out how to compile the CQLs only once for the whole test class + ForbiddenComment:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$// TODO: ModelInfo bug. Not aware of SimpleQuantity + ForbiddenComment:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$// TODO: Resolve Error: Could not load model information for model FHIR, version + 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; } } */ + ForbiddenComment:FhirModelResolver.kt$FhirModelResolver$// TODO: Probably quite a bit of redundancy here. Probably only really need the BaseType and the + 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 ... + 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" + 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 + ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$// TODO: Add DSTU2 test + ForbiddenComment:FhirModelResolverTest.kt$FhirModelResolverTest$// TODO: enable this for DSTU2 and DSTU3 models which use FHIR.ResourceContainer for + ForbiddenComment:R4FhirModelResolver.kt$R4FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in HAPI. + ForbiddenComment:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$// TODO: Deal with the case that the value is expressed as an expression extension + ForbiddenComment:R4FhirTypeConverter.kt$R4FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system + ForbiddenComment:R5FhirModelResolver.kt$R5FhirModelResolver$// TODO: Might be able to patch some of these by registering custom types in + ForbiddenComment:R5FhirTypeConverter.kt$R5FhirTypeConverter$// TODO: This will construct DateTimeType values in FHIR with the system timezone id, + ForbiddenComment:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$// TODO: evaluate this lazily in case the engine only needs the first element + ForbiddenComment:SearchParameterResolver.kt$SearchParameterResolver$// TODO: All the others like "_language" + ForbiddenComment:SearchParameterResolver.kt$SearchParameterResolver$// TODO: What we really need is FhirPath parsing to just get the path + ForbiddenComment:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$// TODO: LD: Due to a type erasure and the CQL compiler historically being in separate + ForbiddenComment:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$// TODO: Consider making this an exception on the resolver because + ForbiddenComment:TestDstu3ModelResolver.kt$TestDstu3ModelResolver$// TODO: Consider making this an exception on the resolver because + ForbiddenComment:TestFhirExecution.kt$TestFhirExecution$// TODO: fix this... I think it requires a resource to be loaded - put in init bundle + ForbiddenComment:TestR4ModelResolver.kt$TestR4ModelResolver$// TODO: Consider making this an exception on the resolver because + ForbiddenComment:TestR4ModelResolver.kt$TestR4ModelResolver$// TODO: The cause of failure for this is unknown. + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// // TODO: HAPI Doesn't have a ResourceContainer type + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// // TODO: The cause of failure for this is unknown. + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Consider making this an exception on the resolver because + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Replace with 5.0.0 model info once that's available + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver$// TODO: Replace with R5 special cases once that's available + ForbiddenComment:TestR5ModelResolver.kt$TestR5ModelResolver.Companion.<no name provided>$// TODO: Add the remainder of the FHIR R5 enums. + FunctionParameterNaming:FhirModelResolver.kt$FhirModelResolver$`object`: Any + ImplicitDefaultLocale:TranslatorHelper.kt$TranslatorHelper$String.format( "[%d:%d, %d:%d]", tb.startLine, tb.startChar, tb.endLine, tb.endChar, ) + IteratorNotThrowingNoSuchElementException:FhirBundleCursor.kt$FhirBundleCursor$FhirBundleIterator : Iterator + LargeClass:Dstu2TypeConverterTests.kt$Dstu2TypeConverterTests + LargeClass:Dstu3TypeConverterTests.kt$Dstu3TypeConverterTests + LargeClass:R4TypeConverterTests.kt$R4TypeConverterTests + LargeClass:R5TypeConverterTests.kt$R5TypeConverterTests + LongMethod:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime + LongMethod:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibraryEvaluationParams(): Stream<Arguments?> + LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibrarySingleEvaluationAtATimeParams(): Stream<Arguments?> + LongMethod:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun singleLibraryEvaluationParams(): Stream<Arguments> + LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest$@ParameterizedTest @MethodSource("multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiledParams") fun multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiled(expressionCaching: Boolean) + LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibParams(): List<Arguments> + LongMethod:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun singleLibParams(): List<Arguments> + LongMethod:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance? + LongMethod:FhirModelResolver.kt$FhirModelResolver$protected fun toDateTime( value: BaseDateTimeType, calendarConstant: Int = this.getCalendarConstant(value), ): DateTime + LongMethod:FhirModelResolverTest.kt$FhirModelResolverTest$@Test fun toCqlValueFhirPrimitiveWithValueAndExtension() + LongMethod:FhirModelResolverTest.kt$fun validateCqlValueAgainstModelInner(cqlValue: Any?, modelType: DataType) + LongMethod:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value? + LongMethod:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + LongMethod:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String + LongMethod:TestFHIR2Helpers.kt$TestFHIR2Helpers$fun test() + LongMethod:TestFHIR3Helpers.kt$TestFHIR3Helpers$fun test() + LongMethod:TestFHIRHelpers.kt$TestFHIRHelpers$@Test fun testFhirHelpers() + LongMethod:TestFhirDataProviderDstu3.kt$TestFhirDataProviderDstu3$fun testContained() + LongMethod:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, ) + LongMethod:TestR4ModelResolver.kt$TestR4ModelResolver$@Test fun modelInfoSpecialCaseTests() + LongParameterList:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$( context: String?, contextPath: String?, contextValue: String?, dataType: String?, templateId: String?, codeFilters: MutableList<CodeFilter>?, dateFilters: MutableList<DateFilter>?, ) + LongParameterList:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$( context: String?, contextPath: String?, contextValue: String?, dataType: String?, templateId: String?, codePath: String?, codes: Iterable<Code?>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, ) + LongParameterList:FhirQueryGeneratorFactory.kt$FhirQueryGeneratorFactory$( modelResolver: ModelResolver, searchParameterResolver: SearchParameterResolver, terminologyProvider: TerminologyProvider?, shouldExpandValueSets: Boolean?, maxCodesPerQuery: Int?, pageSize: Int?, queryBatchThreshold: Int?, ) + LoopWithTooManyJumpStatements:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$for + LoopWithTooManyJumpStatements:SearchParameterResolver.kt$SearchParameterResolver$for + LoopWithTooManyJumpStatements:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$for + LoopWithTooManyJumpStatements:TestDstu3ModelResolver.kt$TestDstu3ModelResolver$for + LoopWithTooManyJumpStatements:TestR4ModelResolver.kt$TestR4ModelResolver$for + MaxLineLength:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$"Expand value sets cannot be used without a terminology provider and no terminology provider is set." + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).isDistinct().not())" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').exists())" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime1').empty())" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testSelect(Patient.name.select(given | family) = 'Peter' | 'James' | 'Chalmers' | 'Jim')" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$"stu3/tests-fhir-r3/testVariables(%\"vs-administrative-gender\" = 'http://hl7.org/fhir/ValueSet/administrative-gender')" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$$$"stu3/tests-fhir-r3/Dollar/testDollarThis1(Patient.name.given.where(substring($this.length()-3) = 'out'))" + MaxLineLength:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$$$"stu3/tests-fhir-r3/Dollar/testDollarThis2(Patient.name.given.where(substring($this.length()-3) = 'ter'))" + 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)" + MaxLineLength:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$"Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time." + MaxLineLength:FhirModelResolver.kt$FhirModelResolver$"Could not resolve type $typeName. Primary package(s) for this resolver are ${this.packageNames.joinToString(",")}" + MaxLineLength:FhirModelResolver.kt$FhirModelResolver$"Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase." + MaxLineLength:FhirModelResolver.kt$FhirModelResolver$/* * type-to-class and contextPath resolutions are potentially expensive and can be cached * for improved performance. * * 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"/> * for a decorator that adds caching logic for ModelResolvers. */ + MaxLineLength:FhirModelResolverTest.kt$FhirModelResolverTest$* + MaxLineLength:Parser.kt$"Expected FHIR model for parsing FHIR resource, but got model ${model.modelInfo.name} with URL ${model.modelInfo.url}" + MaxLineLength:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$"Cannot process data requirements with subjects not specified using a code from http://hl7.org/fhir/resource-types" + MaxLineLength:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$"Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time." + MaxLineLength:TestFhirDataProviderDstu2.kt$TestFhirDataProviderDstu2$// FhirDataProviderDstu2().withEndpoint("http://fhirtest.uhn.ca/baseDstu2").withPackageName("ca.uhn.fhir.model.dstu2.composite"); + MaxLineLength:TestFhirDataProviderDstu2.kt$TestFhirDataProviderDstu2$// FhirDataProviderDstu2().withEndpoint("http://fhirtest.uhn.ca/baseDstu2").withPackageName("ca.uhn.fhir.model.primitive"); + MaxLineLength:TestFhirPath.kt$TestFhirPath$"%s failed as expected, but unable to determine the cause of the failure. Possible bug in engine. Skipping." + MaxLineLength:TestLibrarySourceProvider.kt$TestLibrarySourceProvider$"stu3/${libraryIdentifier.id}${if (libraryIdentifier.version != null) "-${libraryIdentifier.version}" else ""}.cql" + 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 */ + 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&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?category=http://myterm.com/fhir/CodeSystem/MyValueSet|code20&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + 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&subject=Patient/{{context.patientId}}" + MaxLineLength:TestR4FhirQueryGenerator.kt$TestR4FhirQueryGenerator$"Observation?date=ge${simpleDateFormatter.format(expectedRangeStartDateTime)}&date=le${dateTimeFormatter.format(evaluationDateTimeAsLocal)}&subject=Patient/{{context.patientId}}" + MemberNameEqualsClassName:ParserTest.kt$ParserTest$@Test fun parserTest() + MemberNameEqualsClassName:TestFHIRHelpers.kt$TestFHIRHelpers$@Test fun testFhirHelpers() + NestedBlockDepth:CQLOperationsDstu3Test.kt$CQLOperationsDstu3Test.Companion$@JvmStatic fun dataMethod(): Array<Array<Any>> + NestedBlockDepth:CQLOperationsR4Test.kt$CQLOperationsR4Test.Companion$@JvmStatic fun dataMethod(): Array<Array<Any>> + NestedBlockDepth:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + NestedBlockDepth:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$fun setupCql( classToUse: Class<*>, librariesToPopulate: MutableList<Library?>, libraryManagerToUse: LibraryManager, ) + NestedBlockDepth:FhirBundleCursor.kt$FhirBundleCursor.FhirBundleIterator$fun getTrustedEntries( entries: MutableList<out IBaseResource>, templateId: String?, ): MutableList<out IBaseResource> + NestedBlockDepth:FhirExecutionTestBase.kt$FhirExecutionTestBase$@BeforeEach @Throws(IOException::class, UcumException::class) fun beforeEachTestMethod() + NestedBlockDepth:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance? + NestedBlockDepth:FhirModelResolver.kt$FhirModelResolver$private fun resolveChildren( children: List<BaseRuntimeChildDefinition>, childName: String, ): Class<*>? + NestedBlockDepth:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value? + NestedBlockDepth:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$override fun generateFhirQueries( dataRequirement: ICompositeType?, evaluationDateTime: DateTime?, contextValues: MutableMap<String, String?>?, parameters: MutableMap<String, Value?>?, capabilityStatement: IBaseConformance?, ): MutableList<String> + NestedBlockDepth:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$private fun executeQuery(dataType: String?, map: SearchParameterMap): IBaseResource? + NestedBlockDepth:SearchParameterMap.kt$SearchParameterMap$fun toNormalizedQueryString(theCtx: FhirContext): String + NestedBlockDepth:SearchParameterMap.kt$SearchParameterMap$private fun clean( theParamName: String?, theAndOrParams: MutableList<MutableList<IQueryParameterType>>, ) + ObjectPropertyNaming:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$private const val _PATIENT_123 = "123" + PrintStackTrace:FhirExecutionTestBase.kt$FhirExecutionTestBase$e + PrintStackTrace:FhirHelpersDstu2Test.kt$FhirHelpersDstu2Test$e + PrintStackTrace:FhirHelpersDstu3Test.kt$FhirHelpersDstu3Test$e + ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( codes: Iterable<Code?>?, valueSet: String?, ): MutableList<TokenOrListParam> + ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun getCodeParams( dataType: String?, codePath: String?, codes: Iterable<Code?>?, valueSet: String?, ): Pair<String, MutableList<TokenOrListParam>>? + ReturnCount:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$protected fun innerSetupQueries( templateParam: Pair<String, IQueryParameterType>?, contextParam: Pair<String, IQueryParameterType>?, dateRangeParams: MutableList<Pair<String, DateRangeParam>>?, codeParams: MutableList<Pair<String, MutableList<TokenOrListParam>>>?, ): MutableList<SearchParameterMap> + ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toCqlType(value: Any?): Value? + ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$override fun toFhirType(value: Value?): IBase? + ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime + ReturnCount:BaseFhirTypeConverter.kt$BaseFhirTypeConverter$protected fun toTime(calendar: Calendar, calendarConstant: Int): Time + ReturnCount:Dstu2FhirModelResolver.kt$Dstu2FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String? + ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval? + ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? + ReturnCount:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType? + ReturnCount:Dstu2TypeConverterTests.kt$Dstu2TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean + ReturnCount:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String? + ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval? + ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? + ReturnCount:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType? + ReturnCount:Dstu3TypeConverterTests.kt$Dstu3TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean + ReturnCount:FhirModelResolver.kt$FhirModelResolver$fun toCqlValue( target: Any?, expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, ): ClassInstance? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$private fun resolveTypeUncached(typeName: String?): Class<*>? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun `is`(valueType: String, type: QName): kotlin.Boolean? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun getContextPath( contextType: kotlin.String?, targetType: kotlin.String?, ): kotlin.String? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$override fun resolveId(target: Value?): kotlin.String? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun innerGetContextPath( visitedElements: MutableSet<String?>, child: BaseRuntimeChildDefinition, type: Class<out IBase?>?, ): String? + ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun resolveRuntimeDefinition(base: IBase): BaseRuntimeElementCompositeDefinition<*> + ReturnCount:FhirModelResolver.kt$FhirModelResolver$protected fun toDateTime( value: BaseDateTimeType, calendarConstant: Int = this.getCalendarConstant(value), ): DateTime + ReturnCount:Issue1226.kt$Issue1226.<no name provided>$override fun retrieve( context: String?, contextPath: String?, contextValue: String?, dataType: String, templateId: String?, codePath: String?, codes: Iterable<Code>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, ): Iterable<Value?> + ReturnCount:Parser.kt$private fun extractPropertyFromJsonObjectAsCqlValue( jsonObject: JsonObject, propertyKey: kotlin.String, dataType: DataType, model: Model, ): Value? + ReturnCount:Parser.kt$private fun isFhirPrimitiveType(dataType: ClassType): kotlin.Boolean + ReturnCount:R4FhirModelResolver.kt$R4FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String? + ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval? + ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? + ReturnCount:R4FhirTypeConverter.kt$R4FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType? + ReturnCount:R4TypeConverterTests.kt$R4TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean + ReturnCount:R5FhirModelResolver.kt$R5FhirModelResolver$override fun getContextPath(contextType: String?, targetType: String?): String? + ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toCqlInterval(value: ICompositeType?): Interval? + ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toCqlTemporal(value: IPrimitiveType<Date>?): BaseTemporal? + ReturnCount:R5FhirTypeConverter.kt$R5FhirTypeConverter$override fun toFhirPeriod(value: Interval?): ICompositeType? + ReturnCount:R5TypeConverterTests.kt$R5TypeConverterTests$private fun compareObjects(left: Any?, right: Any?): Boolean + ReturnCount:SearchParameterResolver.kt$SearchParameterResolver$fun createSearchParameter( context: String?, dataType: String?, path: String?, value: String?, ): Pair<String, IQueryParameterType>? + ReturnCount:SearchParameterResolver.kt$SearchParameterResolver$fun getSearchParameterDefinition( dataType: String?, path: String?, paramType: RestSearchParameterTypeEnum?, ): RuntimeSearchParam? + ReturnCount:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.<no name provided>$override fun retrieve( context: String?, contextPath: String?, contextValue: String?, dataType: String, templateId: String?, codePath: String?, codes: Iterable<Code>?, valueSet: String?, datePath: String?, dateLowPath: String?, dateHighPath: String?, dateRange: Interval?, ): Iterable<Value?>? + ReturnCount:TestCqlEngineRelatedContextSupport.kt$TestCqlEngineRelatedContextSupport.Companion$private fun codesEqual(codes: Iterable<Code>?, equalTo: String): Boolean + ReturnCount:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, ) + SpreadOperator:RestFhirRetrieveProvider.kt$RestFhirRetrieveProvider$(*codings) + SwallowedException:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$ex: Exception + SwallowedException:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$rnfe: ResourceNotFoundException + SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: IllegalAccessException + SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: InstantiationException + SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: InvocationTargetException + SwallowedException:FhirModelResolver.kt$FhirModelResolver$e: NoSuchMethodException + SwallowedException:FhirModelResolverTest.kt$e: AssertionError + SwallowedException:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$ex: Exception + SwallowedException:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$rnfe: ResourceNotFoundException + SwallowedException:SearchParamFhirRetrieveProvider.kt$SearchParamFhirRetrieveProvider$exception: FhirVersionMisMatchException + SwallowedException:TestDstu2ModelResolver.kt$TestDstu2ModelResolver$e: Exception + ThrowsCount:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$fun setupCql( classToUse: Class<*>, librariesToPopulate: MutableList<Library?>, libraryManagerToUse: LibraryManager, ) + ThrowsCount:FhirModelResolver.kt$FhirModelResolver$protected fun createHapiInstance(clazz: Class<*>): Any + ThrowsCount:TestFhirPath.kt$TestFhirPath$protected fun runTest( test: Test, basePathInput: String?, fhirContext: FhirContext, provider: CompositeDataProvider?, resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, ) + TooGenericExceptionCaught:Dstu3FhirQueryGenerator.kt$Dstu3FhirQueryGenerator$ex: Exception + TooGenericExceptionCaught:Dstu3FhirTerminologyProvider.kt$Dstu3FhirTerminologyProvider$e: Exception + TooGenericExceptionCaught:R4FhirQueryGenerator.kt$R4FhirQueryGenerator$ex: Exception + TooGenericExceptionCaught:R4FhirTerminologyProvider.kt$R4FhirTerminologyProvider$e: Exception + TooGenericExceptionThrown:Dstu3FhirTest.kt$Dstu3FhirTest.Companion$throw RuntimeException( "Failed to determine a port for the wiremock server", ex, ) + TooGenericExceptionThrown:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$throw RuntimeException(error, exception) + TooGenericExceptionThrown:R4FhirTest.kt$R4FhirTest.Companion$throw RuntimeException( "Failed to determine a port for the wiremock server", ex, ) + TooGenericExceptionThrown:SearchParamFhirRetrieveProvider.kt$SearchParamFhirRetrieveProvider$throw RuntimeException(exception.message) + TooManyFunctions:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator : FhirVersionIntegrityChecker + TooManyFunctions:BaseFhirTypeConverter.kt$BaseFhirTypeConverter : FhirTypeConverter + TooManyFunctions:Dstu2FhirModelResolver.kt$Dstu2FhirModelResolver : FhirModelResolver + TooManyFunctions:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter : BaseFhirTypeConverter + TooManyFunctions:Dstu3FhirModelResolver.kt$Dstu3FhirModelResolver : FhirModelResolver + TooManyFunctions:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter : BaseFhirTypeConverter + TooManyFunctions:FhirTypeConverter.kt$FhirTypeConverter + TooManyFunctions:R4FhirModelResolver.kt$R4FhirModelResolver : FhirModelResolver + TooManyFunctions:R4FhirTypeConverter.kt$R4FhirTypeConverter : BaseFhirTypeConverter + TooManyFunctions:R5FhirModelResolver.kt$R5FhirModelResolver : FhirModelResolver + TooManyFunctions:R5FhirTypeConverter.kt$R5FhirTypeConverter : BaseFhirTypeConverter + TooManyFunctions:SearchParameterMap.kt$SearchParameterMap : Serializable + TopLevelPropertyNaming:Constants.kt$const val fhirModelId = "FHIR" + TopLevelPropertyNaming:Constants.kt$const val fhirModelNamespaceUri = "http://hl7.org/fhir" + UnusedParameter:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$dateHighPath: String? + UnusedParameter:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator$dateLowPath: String? + UnusedPrivateClass:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$TestRetrieveProvider : RetrieveProvider + UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest$@Nonnull private fun getCqlEngineForFhirNewLibMgr(expressionCaching: Boolean): CqlEngine + UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibraryEvaluationParams(): Stream<Arguments?> + UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun multiLibrarySingleEvaluationAtATimeParams(): Stream<Arguments?> + UnusedPrivateMember:EvaluatedResourcesMultiLibComplexDepsTest.kt$EvaluatedResourcesMultiLibComplexDepsTest.Companion$@JvmStatic private fun singleLibraryEvaluationParams(): Stream<Arguments> + UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibEnsurePartialCacheAllowsUncachedLibsToBeCompiledParams(): List<Arguments> + UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun multiLibParams(): List<Arguments> + UnusedPrivateMember:EvaluatedResourcesMultiLibLinearDepsTest.kt$EvaluatedResourcesMultiLibLinearDepsTest.Companion$@JvmStatic private fun singleLibParams(): List<Arguments> + UnusedPrivateProperty:BaseFhirQueryGenerator.kt$BaseFhirQueryGenerator.Companion$i + UnusedPrivateProperty:EvaluatedResourceTestUtils.kt$EvaluatedResourceTestUtils$index + UnusedPrivateProperty:TestCodeRef.kt$TestCodeRef$private val terminologyProvider = Dstu3FhirTerminologyProvider(fhirClient) + UseRequire:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + UseRequire:Dstu2FhirTypeConverter.kt$Dstu2FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period") + UseRequire:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + UseRequire:Dstu3FhirTypeConverter.kt$Dstu3FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period") + UseRequire:FhirModelResolver.kt$FhirModelResolver$throw IllegalArgumentException( "Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase." ) + UseRequire:R4FhirTypeConverter.kt$R4FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + UseRequire:R4FhirTypeConverter.kt$R4FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period") + UseRequire:R5FhirTypeConverter.kt$R5FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + UseRequire:R5FhirTypeConverter.kt$R5FhirTypeConverter$throw IllegalArgumentException("value is not a FHIR Range or Period") + + diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/Constants.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/Constants.kt new file mode 100644 index 0000000000000000000000000000000000000000..203ccf66d44c04027b74b49cccb4c0e14826732f --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/Constants.kt @@ -0,0 +1,4 @@ +package org.opencds.cqf.cql.engine.fhir + +const val fhirModelId = "FHIR" +const val fhirModelNamespaceUri = "http://hl7.org/fhir" diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/parser/Parser.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/parser/Parser.kt new file mode 100644 index 0000000000000000000000000000000000000000..c304fae64e2e9bcca2c137b9016d3dbb720756b6 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/commonMain/kotlin/org/opencds/cqf/cql/engine/fhir/parser/Parser.kt @@ -0,0 +1,258 @@ +package org.opencds.cqf.cql.engine.fhir.parser + +import kotlinx.io.Source +import kotlinx.io.readString +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.intOrNull +import org.cqframework.cql.cql2elm.model.Model +import org.cqframework.cql.shared.BigDecimal +import org.cqframework.cql.shared.QName +import org.hl7.cql.model.ChoiceType +import org.hl7.cql.model.ClassType +import org.hl7.cql.model.DataType +import org.hl7.cql.model.ListType +import org.hl7.cql.model.NamedType +import org.hl7.cql.model.SimpleType +import org.opencds.cqf.cql.engine.fhir.fhirModelId +import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri +import org.opencds.cqf.cql.engine.runtime.ClassInstance +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.toCqlBoolean +import org.opencds.cqf.cql.engine.runtime.toCqlDecimal +import org.opencds.cqf.cql.engine.runtime.toCqlInteger +import org.opencds.cqf.cql.engine.runtime.toCqlList +import org.opencds.cqf.cql.engine.runtime.toCqlString +import org.opencds.cqf.cql.engine.util.offsetDateTimeParse +import org.opencds.cqf.cql.engine.util.zonedDateTimeNow + +/** Parses a JSON [Source] representing a FHIR resource into a CQL [Value]. */ +fun fhirResourceJsonToCqlValue(source: Source, model: Model): ClassInstance { + require(model.modelInfo.name == fhirModelId && model.modelInfo.url == fhirModelNamespaceUri) { + "Expected FHIR model for parsing FHIR resource, but got model ${model.modelInfo.name} with URL ${model.modelInfo.url}" + } + + val jsonElement = Json.parseToJsonElement(source.readString()) + require(jsonElement is JsonObject) { + "Expected JSON object for FHIR resource, but got $jsonElement" + } + return fhirResourceJsonObjectToCqlClassInstance(jsonElement, model) +} + +/** Converts a JSON object representing a FHIR resource into a CQL [ClassInstance]. */ +private fun fhirResourceJsonObjectToCqlClassInstance( + jsonObject: JsonObject, + model: Model, +): ClassInstance { + val resourceType = + (jsonObject["resourceType"] as? JsonPrimitive)?.contentOrNull + ?: throw IllegalArgumentException("Missing or non-string resourceType") + + val resourceClassType = + model.resolveTypeName(resourceType) as? ClassType + ?: throw IllegalArgumentException("Unsupported resource type $resourceType") + + return jsonObjectToCqlClassInstance(jsonObject, resourceClassType, model) +} + +/** + * Converts a JSON object representing a FHIR Resource, non-primitive type (complex datatype), or an + * objectified primitive type into a CQL [ClassInstance]. + */ +private fun jsonObjectToCqlClassInstance( + jsonObject: JsonObject, + dataType: ClassType, + model: Model, +): ClassInstance { + if (dataType.name == "FHIR.Resource") { + return fhirResourceJsonObjectToCqlClassInstance(jsonObject, model) + } + + return ClassInstance( + QName(fhirModelNamespaceUri, dataType.name.removePrefix(FHIR_PREFIX), fhirModelId), + dataType + .getAllElements() + .mapValues { (elementName, elementType) -> + extractPropertyFromJsonObjectAsCqlValue(jsonObject, elementName, elementType, model) + } + .toMutableMap(), + ) +} + +/** + * Extracts a property of a JSON object representing a FHIR Resource, non-primitive type (complex + * datatype), or an objectified primitive type as a CQL [Value]. + */ +private fun extractPropertyFromJsonObjectAsCqlValue( + jsonObject: JsonObject, + propertyKey: kotlin.String, + dataType: DataType, + model: Model, +): Value? { + if (dataType is ChoiceType) { + // Elements that have a choice of datatype cannot repeat + for (type in dataType.types) { + require(type is NamedType) { "Expected named type $type but got $dataType" } + val fhirType = type.name.removePrefix(FHIR_PREFIX) + val propertyKeyWithType = + "$propertyKey${fhirType.replaceFirstChar { it.uppercaseChar() }}" + if ( + jsonObject.containsKey(propertyKeyWithType) || + (type is ClassType && + isFhirPrimitiveType(type) && + jsonObject.containsKey("_$propertyKeyWithType")) + ) { + return extractPropertyFromJsonObjectAsCqlValue( + jsonObject, + propertyKeyWithType, + type, + model, + ) + } + } + return null + } + + if (dataType is SimpleType) { + val jsonPrimitive = jsonObject[propertyKey] as? JsonPrimitive ?: return null + + return when (dataType.name) { + "System.Boolean" -> jsonPrimitive.booleanOrNull?.toCqlBoolean() + "System.Integer" -> jsonPrimitive.intOrNull?.toCqlInteger() + "System.Decimal" -> jsonPrimitive.contentOrNull?.let { BigDecimal(it) }?.toCqlDecimal() + "System.String" -> jsonPrimitive.takeIf { it.isString }?.content?.toCqlString() + "System.Date" -> jsonPrimitive.takeIf { it.isString }?.content?.let { Date(it) } + "System.DateTime" -> + jsonPrimitive + .takeIf { it.isString } + ?.content + ?.let { + val zoneOffset = + try { + offsetDateTimeParse(it).getOffset() + } catch (_: Exception) { + zonedDateTimeNow().getOffset() + } + + DateTime(it, zoneOffset) + } + "System.Time" -> jsonPrimitive.takeIf { it.isString }?.content?.let { Time(it) } + else -> throw IllegalArgumentException("Unsupported simple type $dataType") + } + } + + if (dataType is ListType) { + val elementType = dataType.elementType + require(elementType is ClassType) { "Unsupported element type $elementType" } + + if (isFhirPrimitiveType(elementType)) { + val primitiveValues = jsonObject[propertyKey] as? JsonArray + val extraPropertiesOfPrimitiveValues = jsonObject["_$propertyKey"] as? JsonArray + val len = maxOf(primitiveValues?.size ?: 0, extraPropertiesOfPrimitiveValues?.size ?: 0) + + if (len == 0) return null + + return List(len) { i -> + primitiveValueAndExtraPropertiesToCqlClassInstance( + primitiveValues?.getOrNull(i) ?: JsonNull, + extraPropertiesOfPrimitiveValues?.getOrNull(i) ?: JsonNull, + elementType, + model, + ) + } + .toCqlList() + } + + return (jsonObject[propertyKey] as? JsonArray) + ?.map { element -> + if (element is JsonObject) jsonObjectToCqlClassInstance(element, elementType, model) + else null + } + ?.toCqlList() + } + + if (dataType is ClassType) { + if (isFhirPrimitiveType(dataType)) { + return primitiveValueAndExtraPropertiesToCqlClassInstance( + jsonObject[propertyKey] ?: JsonNull, + jsonObject["_$propertyKey"] ?: JsonNull, + dataType, + model, + ) + } + + val value = jsonObject[propertyKey] + return if (value is JsonObject) jsonObjectToCqlClassInstance(value, dataType, model) + else null + } + + throw IllegalArgumentException("Unsupported data type $dataType") +} + +/** + * Converts the JSON elements representing the FHIR primitive value and its extra properties (`id`, + * `extension`) into a CQL [ClassInstance] of the given FHIR primitive type. + */ +private fun primitiveValueAndExtraPropertiesToCqlClassInstance( + primitiveValue: JsonElement, + extraProperties: JsonElement, + dataType: ClassType, + model: Model, +): ClassInstance? { + if (primitiveValue is JsonNull && extraProperties is JsonNull) { + return null + } + val jsonObject = + JsonObject( + mapOf("value" to primitiveValue).let { + when (extraProperties) { + is JsonNull -> it + is JsonObject -> it + extraProperties + else -> + throw IllegalArgumentException( + "Expected JSON object or null but got $extraProperties" + ) + } + } + ) + return jsonObjectToCqlClassInstance(jsonObject, dataType, model) +} + +private fun isFhirPrimitiveType(dataType: ClassType): kotlin.Boolean { + val typeName = dataType.name.removePrefix(FHIR_PREFIX) + val firstChar = typeName.firstOrNull() ?: return false + if (firstChar.lowercaseChar() == firstChar) { + return true + } + val baseType = dataType.baseType + if (baseType is ClassType && baseType.name == "FHIR.Element") { + val element = dataType.elements.singleOrNull() ?: return false + val elementType = element.type + if ( + element.name == "value" && + elementType is SimpleType && + elementType.name == "System.String" + ) { + return true + } + } + + return false +} + +/** Collects all elements of a class type, including inherited elements. */ +private fun ClassType.getAllElements(): Map { + return (if (baseType is ClassType) (baseType as ClassType).getAllElements() else emptyMap()) + + elements.associate { it.name to it.type } +} + +private const val FHIR_PREFIX = "FHIR." diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu2/model/AnnotatedUuidType.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu2/model/AnnotatedUuidType.kt new file mode 100644 index 0000000000000000000000000000000000000000..9ce5828189272d3278dbbc6f8d92466f97bb7400 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu2/model/AnnotatedUuidType.kt @@ -0,0 +1,6 @@ +package org.hl7.fhir.dstu2.model + +import ca.uhn.fhir.model.api.annotation.DatatypeDef +import ca.uhn.fhir.model.primitive.UriDt + +@DatatypeDef(name = "uuid") class AnnotatedUuidType : UriDt() diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu3/model/AnnotatedUuidType.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu3/model/AnnotatedUuidType.kt new file mode 100644 index 0000000000000000000000000000000000000000..766243652144490b692aee481f233954c05a44bb --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/dstu3/model/AnnotatedUuidType.kt @@ -0,0 +1,5 @@ +package org.hl7.fhir.dstu3.model + +import ca.uhn.fhir.model.api.annotation.DatatypeDef + +@DatatypeDef(name = "uuid") class AnnotatedUuidType : UuidType() diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/r4/model/AnnotatedUuidType.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/r4/model/AnnotatedUuidType.kt new file mode 100644 index 0000000000000000000000000000000000000000..40a0dfa337169870cd412b09e4e16aa4dbdc387d --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/hl7/fhir/r4/model/AnnotatedUuidType.kt @@ -0,0 +1,5 @@ +package org.hl7.fhir.r4.model + +import ca.uhn.fhir.model.api.annotation.DatatypeDef + +@DatatypeDef(name = "uuid") class AnnotatedUuidType : UuidType() diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/BaseFhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/BaseFhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..d7c9dc0e9ff829d95898084078f8934625a4397f --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/BaseFhirTypeConverter.kt @@ -0,0 +1,471 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.io.PrintWriter +import java.io.StringWriter +import java.math.BigDecimal +import java.util.* +import org.apache.commons.lang3.NotImplementedException +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.opencds.cqf.cql.engine.exception.InvalidPrecision +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Precision +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.TemporalHelper +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName +import org.opencds.cqf.cql.engine.runtime.dateTypeName +import org.opencds.cqf.cql.engine.runtime.quantityTypeName +import org.opencds.cqf.cql.engine.runtime.toCqlBoolean +import org.opencds.cqf.cql.engine.runtime.toCqlDecimal +import org.opencds.cqf.cql.engine.runtime.toCqlInteger +import org.opencds.cqf.cql.engine.runtime.toCqlList +import org.opencds.cqf.cql.engine.runtime.toCqlLong +import org.opencds.cqf.cql.engine.runtime.toCqlString + +internal abstract class BaseFhirTypeConverter : FhirTypeConverter { + override fun isFhirType(value: Any): kotlin.Boolean { + require(value !is Iterable<*>) { "isFhirType can not be used for Iterables" } + return value is IBase + } + + override fun toFhirTypes(values: List): MutableList { + val converted: MutableList = ArrayList() + for (value in values) { + if (value == null) { + converted.add(null) + } else if (value is List) { + converted.add(toFhirTypes(value)) + } else if (isFhirType(value)) { + converted.add(value) + } else { + converted.add(toFhirType(value)) + } + } + + return converted + } + + override fun toFhirType(value: Value?): IBase? { + if (value == null) { + return null + } + + require(value !is List) { "use toFhirTypes(Iterable) for iterables" } + + if (value is Exception) { + return toFhirOperationOutcome(value) + } + + if (isFhirType(value)) { + return value as IBase + } + + require(isCqlType(value)) { "can't convert ${value.javaClass.name} to FHIR type" } + + when (value) { + is Boolean -> return toFhirBoolean(value) + is Integer -> return toFhirInteger(value) + is Long -> return toFhirLong(value) + is Decimal -> return toFhirDecimal(value) + is Date -> return toFhirDate(value) + is DateTime -> return toFhirDateTime(value) + is Time -> return toFhirTime(value) + is String -> return toFhirString(value) + is Quantity -> return toFhirQuantity(value) + is Ratio -> return toFhirRatio(value) + is Code -> return toFhirCoding(value) + is Concept -> return toFhirCodeableConcept(value) + is Interval -> return toFhirInterval(value) + is Tuple -> return toFhirTuple(value) + else -> return toCqlText(value) + } + } + + /** + * Converts a Long to the FHIR type that System.Long maps to in this FHIR version. Defaults to + * integer64; versions without integer64 override this. + * + * @param value the value to convert + * @return the FHIR representation of the Long + */ + protected open fun toFhirLong(value: Long): IBase? { + return toFhirInteger64(value) + } + + /** + * Determines whether the given string is a CQL calendar unit + * + * @param unit + * @return true if the given unit is a CQL calendar unit + */ + override fun isCqlCalendarUnit(unit: kotlin.String?): kotlin.Boolean { + if (unit == null) { + return false + } + + return when (unit) { + "milliseconds", + "millisecond", + "seconds", + "second", + "minutes", + "minute", + "hours", + "hour", + "days", + "day", + "weeks", + "week", + "months", + "month", + "years", + "year" -> true + else -> false + } + } + + /** + * Converts the given CQL unit to a UCUM definite-time duration unit according to the table and + * process defined in the CQL specification: https://cql.hl7.org/02-authorsguide.html#quantities + * + * @param unit + * @return An equivalent UCUM unit for the given CQL calendar duration unit, if the input is a + * CQL calendar duration unit, otherwise returns the input unit. + */ + override fun toUcumUnit(unit: kotlin.String?): kotlin.String? { + if (unit == null) { + return null + } + + return when (unit) { + "milliseconds", + "millisecond" -> "ms" + "seconds", + "second" -> "s" + "minutes", + "minute" -> "min" + "hours", + "hour" -> "h" + "days", + "day" -> "d" + "weeks", + "week" -> "wk" + "months", + "month" -> "mo" + "years", + "year" -> "a" + else -> unit + } + } + + /** + * Converts a Ucum unit to the equivalent CQL unit according to the table defined in the CQL + * specification: https://cql.hl7.org/02-authorsguide.html#quantities + * + * @param unit + * @return A CQL calendar unit if the input unit is a Ucum definite-duration unit, otherwise, + * the input unit + */ + override fun toCqlCalendarUnit(unit: kotlin.String?): kotlin.String? { + return when (unit) { + null -> null + "ms" -> "millisecond" + "s" -> "second" + "min" -> "minute" + "h" -> "hour" + "d" -> "day" + "wk" -> "week" + "mo" -> "month" + "a" -> "year" + else -> unit + } + } + + override fun toFhirInterval(value: Interval?): IBase? { + if (value == null) { + return null + } + + return when (value.pointType) { + dateTypeName, + dateTimeTypeName -> toFhirPeriod(value) + quantityTypeName -> toFhirRange(value) + else -> toCqlText(value) + } + } + + override fun isCqlType(value: Any): kotlin.Boolean { + return value is Value + } + + override fun toCqlTypes(values: Iterable<*>): Iterable { + val converted = mutableListOf() + for (value in values) { + if (value == null) { + converted.add(null) + } else if (value is Iterable<*>) { + converted.add(toCqlTypes(value).toCqlList()) + } else if (isCqlType(value)) { + converted.add(value as Value) + } else { + converted.add(toCqlType(value)) + } + } + + return converted + } + + override fun toCqlType(value: Any?): Value? { + if (value == null) { + return null + } + + require(value !is Iterable<*>) { "use toCqlTypes(Iterable) for iterables" } + + if (isCqlType(value)) { + return value as Value + } + + require(isFhirType(value)) { "can't convert ${value.javaClass.name} to CQL type" } + + when (value.javaClass.getSimpleName()) { + "IdType" -> return toCqlId(value as IIdType) + "BooleanType" -> return toCqlBoolean(value.asIPrimitive()) + "IntegerType" -> return toCqlInteger(value.asIPrimitive()) + "Integer64Type" -> return toCqlLong(value.asIPrimitive()) + "DecimalType" -> return toCqlDecimal(value.asIPrimitive()) + "DateType" -> return toCqlDate(value.asIPrimitive()) + "InstantType", + "DateTimeType" -> return toCqlDateTime(value.asIPrimitive()) + "TimeType" -> return toCqlTime(value.asIPrimitive()) + "StringType" -> return toCqlString(value.asIPrimitive()) + "Quantity" -> return toCqlQuantity(value as ICompositeType) + "Ratio" -> return toCqlRatio(value as ICompositeType) + "Coding" -> return toCqlCode(value as IBaseCoding) + "CodeableConcept" -> return toCqlConcept(value as ICompositeType) + "Period", + "Range" -> return toCqlInterval(value as ICompositeType) + else -> + throw IllegalArgumentException( + "missing case statement for: ${value.javaClass.name}" + ) + } + } + + private fun Any?.asIPrimitive(): IPrimitiveType? { + @Suppress("UNCHECKED_CAST") + return this as? IPrimitiveType + } + + override fun toCqlId(value: IIdType?): String? { + if (value == null) { + return null + } + + return value.idPart?.toCqlString() + } + + override fun toCqlBoolean(value: IPrimitiveType?): Boolean? { + if (value == null) { + return null + } + + return value.getValue()?.toCqlBoolean() + } + + override fun toCqlInteger(value: IPrimitiveType?): Integer? { + if (value == null) { + return null + } + + return value.getValue()?.toCqlInteger() + } + + override fun toCqlLong(value: IPrimitiveType?): Long? { + if (value == null) { + return null + } + + return value.getValue()?.toCqlLong() + } + + override fun toCqlDecimal(value: IPrimitiveType?): Decimal? { + if (value == null) { + return null + } + + return value.getValue()?.toCqlDecimal() + } + + override fun toCqlTime(value: IPrimitiveType?): Time? { + if (value == null) { + return null + } + + return Time(value.getValue()) + } + + override fun toCqlString(value: IPrimitiveType?): String? { + if (value == null) { + return null + } + + return value.getValue()?.toCqlString() + } + + override fun toCqlTuple(value: IBase?): Tuple? { + if (value == null) { + return null + } + + throw NotImplementedException("toCqlTuple is not yet implemented") + } + + protected fun toTime(calendar: Calendar, calendarConstant: Int): Time { + when (calendarConstant) { + Calendar.HOUR -> return Time(calendar.get(Calendar.HOUR)) + Calendar.MINUTE -> + return Time(calendar.get(Calendar.HOUR), calendar.get(Calendar.MINUTE)) + + Calendar.SECOND -> + return Time( + calendar.get(Calendar.HOUR), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + ) + + Calendar.MILLISECOND -> + return Time( + calendar.get(Calendar.HOUR), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + calendar.get(Calendar.MILLISECOND), + ) + + else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant") + } + } + + protected fun toDateTime(calendar: Calendar, calendarConstant: Int): DateTime { + val tz = + if (calendar.getTimeZone() == null) TimeZone.getDefault() else calendar.getTimeZone() + val zoneOffset = tz.toZoneId().rules.getStandardOffset(calendar.toInstant()) + when (calendarConstant) { + Calendar.YEAR -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + ) + Calendar.MONTH -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + ) + + Calendar.DAY_OF_MONTH -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + ) + + Calendar.HOUR_OF_DAY -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + ) + + Calendar.MINUTE -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + ) + + Calendar.SECOND -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + ) + + Calendar.MILLISECOND -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + calendar.get(Calendar.MILLISECOND), + ) + + else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant") + } + } + + protected fun toDate(calendar: Calendar, calendarConstant: Int): Date { + return when (calendarConstant) { + Calendar.YEAR -> Date(calendar.get(Calendar.YEAR)) + Calendar.MONTH -> Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1) + + Calendar.DAY_OF_MONTH -> + Date( + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + ) + + else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant") + } + } + + protected fun toFhirPrecision(precision: Precision): TemporalPrecisionEnum { + val name = + when (precision) { + Precision.WEEK, + Precision.HOUR, + Precision.MINUTE -> TemporalPrecisionEnum.DAY.name + Precision.MILLISECOND -> TemporalPrecisionEnum.MILLI.name + else -> precision.name + } + return TemporalPrecisionEnum.valueOf(name) + } + + protected fun getStackTraceAsString(exception: Exception): kotlin.String { + val sw = StringWriter() + PrintWriter(sw).use { pw -> exception.printStackTrace(pw) } + return sw.toString() + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2FhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2FhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..bc3e867cdc9319f8dca6d70f3c452c3047ec7809 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2FhirTypeConverter.kt @@ -0,0 +1,578 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.math.BigDecimal +import java.util.* +import java.util.stream.Collectors +import org.apache.commons.lang3.NotImplementedException +import org.hl7.fhir.dstu2.model.BaseDateTimeType +import org.hl7.fhir.dstu2.model.BooleanType +import org.hl7.fhir.dstu2.model.CodeType +import org.hl7.fhir.dstu2.model.CodeableConcept +import org.hl7.fhir.dstu2.model.Coding +import org.hl7.fhir.dstu2.model.DateTimeType +import org.hl7.fhir.dstu2.model.DateType +import org.hl7.fhir.dstu2.model.DecimalType +import org.hl7.fhir.dstu2.model.IdType +import org.hl7.fhir.dstu2.model.IntegerType +import org.hl7.fhir.dstu2.model.OperationOutcome +import org.hl7.fhir.dstu2.model.Parameters +import org.hl7.fhir.dstu2.model.Period +import org.hl7.fhir.dstu2.model.Range +import org.hl7.fhir.dstu2.model.Resource +import org.hl7.fhir.dstu2.model.SimpleQuantity +import org.hl7.fhir.dstu2.model.StringType +import org.hl7.fhir.dstu2.model.TimeType +import org.hl7.fhir.dstu2.model.Type +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseDatatype +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName +import org.opencds.cqf.cql.engine.runtime.dateTypeName +import org.opencds.cqf.cql.engine.runtime.quantityTypeName + +internal class Dstu2FhirTypeConverter : BaseFhirTypeConverter() { + override fun toFhirId(value: String?): IIdType? { + if (value == null) { + return null + } + + return IdType(value.value) + } + + override fun toFhirBoolean(value: Boolean?): BooleanType? { + if (value == null) { + return null + } + + return BooleanType(value.value) + } + + override fun toFhirInteger(value: Integer?): IPrimitiveType? { + if (value == null) { + return null + } + + return IntegerType(value.value) + } + + override fun toFhirInteger64(value: Long?): IPrimitiveType { + throw IllegalArgumentException("FHIR DSTU2 does not support Long/Integer64 values") + } + + override fun toFhirDecimal(value: Decimal?): IPrimitiveType? { + if (value == null) { + return null + } + + return DecimalType(value.value) + } + + override fun toFhirDate( + value: org.opencds.cqf.cql.engine.runtime.Date? + ): IPrimitiveType? { + if (value == null) { + return null + } + + return DateType(value.toStringInner()) + } + + override fun toFhirDateTime(value: DateTime?): IPrimitiveType? { + if (value == null) { + return null + } + + val result = DateTimeType(value.toDateString()) + result.precision = toFhirPrecision(value.precision!!) + return result + } + + override fun toFhirTime(value: Time?): IPrimitiveType? { + if (value == null) { + return null + } + + return TimeType(value.toStringInner()) + } + + override fun toFhirString(value: String?): IPrimitiveType? { + if (value == null) { + return null + } + + return StringType(value.value) + } + + override fun toFhirQuantity(value: Quantity?): ICompositeType? { + if (value == null) { + return null + } + + val unit = value.unit + val system = + if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units" + else "http://unitsofmeasure.org" + val ucumUnit = toUcumUnit(unit) + + return org.hl7.fhir.dstu2.model + .Quantity() + .setSystem(system) + .setCode(ucumUnit) + .setValue(value.value) + .setUnit(unit) + } + + override fun toFhirRatio(value: Ratio?): ICompositeType? { + if (value == null) { + return null + } + + return org.hl7.fhir.dstu2.model + .Ratio() + .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.dstu2.model.Quantity?) + .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.dstu2.model.Quantity?) + } + + override fun toFhirCoding(value: Code?): IBaseCoding? { + if (value == null) { + return null + } + + val coding = Coding() + coding.setSystem(value.system) + coding.setCode(value.code) + coding.setDisplay(value.display) + coding.setVersion(value.version) + return coding + } + + override fun toFhirCodeableConcept(value: Concept?): ICompositeType? { + if (value == null) { + return null + } + + val codeableConcept = CodeableConcept() + codeableConcept.setText(value.display) + if (value.codes != null) { + for (c in value.codes) { + codeableConcept.addCoding(toFhirCoding(c) as Coding?) + } + } + + return codeableConcept + } + + override fun toFhirPeriod(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + val period = Period() + if (value.pointType == dateTimeTypeName) { + if (value.start != null) { + period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType? + } + + if (value.end != null) { + period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType? + } + + return period + } else if (value.pointType == dateTypeName) { + // TODO: This will construct DateTimeType values in FHIR with the system timezone id, + // not the + // timezoneoffset of the evaluation request..... this is a bug waiting to happen + if (value.start != null) { + period.setStart( + toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + if (value.end != null) { + period.setEnd( + toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + return period + } + + throw IllegalArgumentException( + "FHIR Period can only be created from an Interval of Date or DateTime type" + ) + } + + override fun toFhirRange(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + require(value.pointType == quantityTypeName) { + "FHIR Range can only be created from an Interval of Quantity type" + } + + val range = Range() + val start = toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.dstu2.model.Quantity? + if (start != null) { + range.setLow(toSimpleQuantity(start)) + } + + val end = toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.dstu2.model.Quantity? + if (end != null) { + range.setHigh(toSimpleQuantity(end)) + } + + return range + } + + private fun addElementToParameter( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Value?, + ) { + if (value == null) { + // Null value, add a single empty value with an extension indicating the reason + val dataAbsentValue: BooleanType = + emptyBooleanWithExtension( + DATA_ABSENT_REASON_EXT_URL, + CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE), + ) + addPartWithNameAndValue(param, key, dataAbsentValue) + return + } + + if (value !is List) { + // Single, non-null value + addPartWithNameAndValue(param, key, toFhirType(value)!!) + return + } + + val iterable = value + + if (!iterable.iterator().hasNext()) { + // Empty list + val emptyListValue: BooleanType = + emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true)) + addPartWithNameAndValue(param, key, emptyListValue) + } else { + // Non-empty list, one part per value + val fhirTypes = this.toFhirTypes(iterable) + for (fhirType in fhirTypes) { + addPartWithNameAndValue(param, key, fhirType!!) + } + } + } + + override fun toFhirTuple(value: Tuple?): IBase? { + if (value == null) { + return null + } + + val parameters = Parameters() + val param = parameters.addParameter() + + if (value.elements.isEmpty()) { + param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true))) + } + + for (key in value.elements.keys) { + addElementToParameter(param, key, value.elements[key]) + } + + return param + } + + override fun toCqlQuantity(value: ICompositeType?): Quantity? { + if (value == null) { + return null + } + + require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" } + + val quantity = value as org.hl7.fhir.dstu2.model.Quantity + require(!quantity.hasComparator()) { + "Cannot convert a FHIR Quantity with a comparator to a CQL quantity" + } + return Quantity() + .withUnit(toCqlCalendarUnit(quantity.getUnit())) + .withValue(quantity.getValue()) + } + + override fun toCqlRatio(value: ICompositeType?): Ratio? { + if (value == null) { + return null + } + + require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" } + + val ratio = value as org.hl7.fhir.dstu2.model.Ratio + + return Ratio() + .withNumerator(toCqlQuantity(ratio.numerator)) + .withDenominator(toCqlQuantity(ratio.denominator)) + } + + override fun toCqlAny(value: IBase?): Any? { + if (value == null) { + return null + } + + throw NotImplementedException("Unable to convert to System.Any type") + } + + override fun toCqlCode(value: IBaseCoding?): Code? { + if (value == null) { + return null + } + + val coding = value as Coding + + return Code() + .withSystem(coding.getSystem()) + .withCode(coding.getCode()) + .withVersion(coding.getVersion()) + .withDisplay(coding.getDisplay()) + } + + override fun toCqlConcept(value: ICompositeType?): Concept? { + if (value == null) { + return null + } + + require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" } + + val codeableConcept = value as CodeableConcept + + return Concept() + .withDisplay(codeableConcept.getText()) + .withCodes( + codeableConcept + .getCoding() + .stream() + .map { x: Coding? -> toCqlCode(x) } + .collect(Collectors.toList()) + ) + } + + override fun toCqlInterval(value: ICompositeType?): Interval? { + if (value == null) { + return null + } + + if (value.fhirType() == "Range") { + val range = value as Range + return Interval( + toCqlQuantity(range.getLow()), + true, + toCqlQuantity(range.getHigh()), + true, + ) + } else if (value.fhirType() == "Period") { + val period = value as Period + return Interval( + toCqlTemporal(period.startElement), + true, + toCqlTemporal(period.endElement), + true, + ) + } else { + throw IllegalArgumentException("value is not a FHIR Range or Period") + } + } + + override fun toCqlDate(value: IPrimitiveType?): org.opencds.cqf.cql.engine.runtime.Date? { + if (value == null) { + return null + } + + require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) { + "value is not a FHIR Date or DateTime" + } + + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate(toCalendar(baseDateTime)!!, baseDateTime.precision.calendarConstant) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + throw IllegalArgumentException("value has a precision higher than a CQL Date") + + else -> throw IllegalArgumentException("value has a precision higher than a CQL Date") + } + } + + override fun toCqlDateTime(value: IPrimitiveType?): DateTime? { + if (value == null) { + return null + } + + if (value.fhirType() == "instant" || value.fhirType() == "dateTime") { + val baseDateTime = value as BaseDateTimeType + return toDateTime(toCalendar(baseDateTime)!!, baseDateTime.precision.calendarConstant) + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toCqlTemporal(value: IPrimitiveType?): BaseTemporal? { + if (value == null) { + return null + } + + if ( + value.fhirType() == "instant" || + value.fhirType() == "dateTime" || + value.fhirType() == "date" + ) { + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate( + toCalendar(baseDateTime)!!, + baseDateTime.precision.calendarConstant, + ) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + return toDateTime( + toCalendar(baseDateTime)!!, + baseDateTime.precision.calendarConstant, + ) + + else -> + return toDateTime( + toCalendar(baseDateTime)!!, + baseDateTime.precision.calendarConstant, + ) + } + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? { + if (exception == null) { + return null + } + + val outcome = OperationOutcome() + outcome + .addIssue() + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.EXCEPTION) + .setDiagnostics(exception.message) + .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception))) + + return outcome + } + + override fun toCqlText(value: Value?): IBaseDatatype? { + if (value == null) { + return null + } + + val s = ToStringEvaluator.toString(value)?.value + val text = StringType(s) + text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true)) + return text + } + + // The built-in "toCalendar" function is bugged. + // It does not correctly populate the Calendar + private fun toCalendar(dateTimeType: BaseDateTimeType): Calendar? { + if (dateTimeType.value == null) { + return null + } + val cal = + if (dateTimeType.timeZone != null) { + GregorianCalendar(dateTimeType.timeZone) + } else { + GregorianCalendar() + } + cal.setTime(dateTimeType.value) + + return cal + } + + // The built-in "castToSimpleQuantity" automatically creates + // missing elements, which causes comparisons to fail + private fun toSimpleQuantity(quantity: org.hl7.fhir.dstu2.model.Quantity): SimpleQuantity { + val simple = SimpleQuantity() + simple.setValue(quantity.getValue()) + simple.setCode(quantity.getCode()) + simple.setSystem(quantity.getSystem()) + simple.setComparator(quantity.getComparator()) + return simple + } + + companion object { + private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType { + val result = BooleanType(null as kotlin.String?) + result.addExtension().setUrl(url).setValue(value) + return result + } + + private fun addPartWithNameAndValue( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Any, + ) { + if (value is Parameters.ParametersParameterComponent) { + value.setName(key) + param.addPart(value) + } else { + val part = param.addPart().setName(key) + when (value) { + is Resource -> { + part.setResource(value) + } + + is Type -> { + part.setValue(value) + } + + else -> { + throw IllegalArgumentException( + "Unsupported FHIR type: " + value.javaClass.getName() + ) + } + } + } + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu3FhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu3FhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..7a5fa7088d108062a0fff4dcfe8f01f0ee3e4521 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu3FhirTypeConverter.kt @@ -0,0 +1,550 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.math.BigDecimal +import java.time.format.DateTimeFormatter +import java.util.* +import java.util.stream.Collectors +import org.apache.commons.lang3.NotImplementedException +import org.hl7.fhir.dstu3.model.BaseDateTimeType +import org.hl7.fhir.dstu3.model.BooleanType +import org.hl7.fhir.dstu3.model.CodeType +import org.hl7.fhir.dstu3.model.CodeableConcept +import org.hl7.fhir.dstu3.model.Coding +import org.hl7.fhir.dstu3.model.DateTimeType +import org.hl7.fhir.dstu3.model.DateType +import org.hl7.fhir.dstu3.model.DecimalType +import org.hl7.fhir.dstu3.model.IdType +import org.hl7.fhir.dstu3.model.IntegerType +import org.hl7.fhir.dstu3.model.OperationOutcome +import org.hl7.fhir.dstu3.model.Parameters +import org.hl7.fhir.dstu3.model.Period +import org.hl7.fhir.dstu3.model.Range +import org.hl7.fhir.dstu3.model.Resource +import org.hl7.fhir.dstu3.model.StringType +import org.hl7.fhir.dstu3.model.TimeType +import org.hl7.fhir.dstu3.model.Type +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseDatatype +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName +import org.opencds.cqf.cql.engine.runtime.dateTypeName +import org.opencds.cqf.cql.engine.runtime.quantityTypeName + +internal class Dstu3FhirTypeConverter : BaseFhirTypeConverter() { + override fun toFhirId(value: String?): IIdType? { + if (value == null) { + return null + } + + return IdType(value.value) + } + + override fun toFhirBoolean(value: Boolean?): BooleanType? { + if (value == null) { + return null + } + + return BooleanType(value.value) + } + + override fun toFhirInteger(value: Integer?): IPrimitiveType? { + if (value == null) { + return null + } + + return IntegerType(value.value) + } + + override fun toFhirInteger64(value: Long?): IPrimitiveType { + throw IllegalArgumentException("FHIR DSTU3 does not support Long/Integer64 values") + } + + override fun toFhirDecimal(value: Decimal?): IPrimitiveType? { + if (value == null) { + return null + } + + return DecimalType(value.value) + } + + override fun toFhirDate( + value: org.opencds.cqf.cql.engine.runtime.Date? + ): IPrimitiveType? { + if (value == null) { + return null + } + + return DateType(value.toStringInner()) + } + + override fun toFhirDateTime(value: DateTime?): IPrimitiveType? { + if (value == null) { + return null + } + + val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + result.precision = toFhirPrecision(value.precision!!) + return result + } + + override fun toFhirTime(value: Time?): IPrimitiveType? { + if (value == null) { + return null + } + + return TimeType(value.toStringInner()) + } + + override fun toFhirString(value: String?): IPrimitiveType? { + if (value == null) { + return null + } + + return StringType(value.value) + } + + override fun toFhirQuantity(value: Quantity?): ICompositeType? { + if (value == null) { + return null + } + + val unit = value.unit + val system = + if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units" + else "http://unitsofmeasure.org" + val ucumUnit = toUcumUnit(unit) + + return org.hl7.fhir.dstu3.model + .Quantity() + .setSystem(system) + .setCode(ucumUnit) + .setValue(value.value) + .setUnit(unit) + } + + override fun toFhirRatio(value: Ratio?): ICompositeType? { + if (value == null) { + return null + } + + return org.hl7.fhir.dstu3.model + .Ratio() + .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.dstu3.model.Quantity?) + .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.dstu3.model.Quantity?) + } + + override fun toFhirCoding(value: Code?): IBaseCoding? { + if (value == null) { + return null + } + + val coding = Coding() + coding.setSystem(value.system) + coding.setCode(value.code) + coding.setDisplay(value.display) + coding.setVersion(value.version) + return coding + } + + override fun toFhirCodeableConcept(value: Concept?): ICompositeType? { + if (value == null) { + return null + } + + val codeableConcept = CodeableConcept() + codeableConcept.setText(value.display) + if (value.codes != null) { + for (c in value.codes) { + codeableConcept.addCoding(toFhirCoding(c) as Coding?) + } + } + + return codeableConcept + } + + override fun toFhirPeriod(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + val period = Period() + if (value.pointType == dateTimeTypeName) { + if (value.start != null) { + period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType? + } + + if (value.end != null) { + period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType? + } + + return period + } else if (value.pointType == dateTypeName) { + // TODO: This will construct DateTimeType values in FHIR with the system timezone id, + // not the + // timezoneoffset of the evaluation request..... this is a bug waiting to happen + if (value.start != null) { + period.setStart( + toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + if (value.end != null) { + period.setEnd( + toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + return period + } + + throw IllegalArgumentException( + "FHIR Period can only be created from an Interval of Date or DateTime type" + ) + } + + override fun toFhirRange(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + require(value.pointType == quantityTypeName) { + "FHIR Range can only be created from an Interval of Quantity type" + } + + val range = Range() + val start = toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.dstu3.model.Quantity? + if (start != null) { + range.setLow(start.castToSimpleQuantity(start)) + } + + val end = toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.dstu3.model.Quantity? + if (end != null) { + range.setHigh(end.castToSimpleQuantity(end)) + } + + return range + } + + private fun addElementToParameter( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Value?, + ) { + if (value == null) { + // Null value, add a single empty value with an extension indicating the reason + val dataAbsentValue: BooleanType = + emptyBooleanWithExtension( + DATA_ABSENT_REASON_EXT_URL, + CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE), + ) + addPartWithNameAndValue(param, key, dataAbsentValue) + return + } + + if (value !is List) { + // Single, non-null value + addPartWithNameAndValue(param, key, toFhirType(value)!!) + return + } + + val iterable = value + + if (!iterable.iterator().hasNext()) { + // Empty list + val emptyListValue: BooleanType = + emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true)) + addPartWithNameAndValue(param, key, emptyListValue) + } else { + // Non-empty list, one part per value + val fhirTypes = this.toFhirTypes(iterable) + for (fhirType in fhirTypes) { + addPartWithNameAndValue(param, key, fhirType!!) + } + } + } + + override fun toFhirTuple(value: Tuple?): IBase? { + if (value == null) { + return null + } + + val parameters = Parameters() + val param = parameters.addParameter() + + if (value.elements.isEmpty()) { + param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true))) + } + + for (key in value.elements.keys) { + addElementToParameter(param, key, value.elements[key]) + } + + return param + } + + override fun toCqlQuantity(value: ICompositeType?): Quantity? { + if (value == null) { + return null + } + + require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" } + + val quantity = value as org.hl7.fhir.dstu3.model.Quantity + require(!quantity.hasComparator()) { + "Cannot convert a FHIR Quantity with a comparator to a CQL quantity" + } + return Quantity() + .withUnit(toCqlCalendarUnit(quantity.getUnit())) + .withValue(quantity.getValue()) + } + + override fun toCqlRatio(value: ICompositeType?): Ratio? { + if (value == null) { + return null + } + + require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" } + + val ratio = value as org.hl7.fhir.dstu3.model.Ratio + + return Ratio() + .withNumerator(toCqlQuantity(ratio.numerator)) + .withDenominator(toCqlQuantity(ratio.denominator)) + } + + override fun toCqlAny(value: IBase?): Any? { + if (value == null) { + return null + } + + throw NotImplementedException("Unable to convert to System.Any type") + } + + override fun toCqlCode(value: IBaseCoding?): Code? { + if (value == null) { + return null + } + + val coding = value as Coding + + return Code() + .withSystem(coding.getSystem()) + .withCode(coding.getCode()) + .withVersion(coding.getVersion()) + .withDisplay(coding.getDisplay()) + } + + override fun toCqlConcept(value: ICompositeType?): Concept? { + if (value == null) { + return null + } + + require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" } + + val codeableConcept = value as CodeableConcept + + return Concept() + .withDisplay(codeableConcept.getText()) + .withCodes( + codeableConcept + .getCoding() + .stream() + .map { x: Coding? -> toCqlCode(x) } + .collect(Collectors.toList()) + ) + } + + override fun toCqlInterval(value: ICompositeType?): Interval? { + if (value == null) { + return null + } + + if (value.fhirType() == "Range") { + val range = value as Range + return Interval( + toCqlQuantity(range.getLow()), + true, + toCqlQuantity(range.getHigh()), + true, + ) + } else if (value.fhirType() == "Period") { + val period = value as Period + return Interval( + toCqlTemporal(period.startElement), + true, + toCqlTemporal(period.endElement), + true, + ) + } else { + throw IllegalArgumentException("value is not a FHIR Range or Period") + } + } + + override fun toCqlDate(value: IPrimitiveType?): org.opencds.cqf.cql.engine.runtime.Date? { + if (value == null) { + return null + } + + require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) { + "value is not a FHIR Date or DateTime" + } + + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + throw IllegalArgumentException("value has a precision higher than a CQL Date") + + else -> throw IllegalArgumentException("value has a precision higher than a CQL Date") + } + } + + override fun toCqlDateTime(value: IPrimitiveType?): DateTime? { + if (value == null) { + return null + } + + if (value.fhirType() == "instant" || value.fhirType() == "dateTime") { + val baseDateTime = value as BaseDateTimeType + return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toCqlTemporal(value: IPrimitiveType?): BaseTemporal? { + if (value == null) { + return null + } + + if ( + value.fhirType() == "instant" || + value.fhirType() == "dateTime" || + value.fhirType() == "date" + ) { + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + else -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + } + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? { + if (exception == null) { + return null + } + + val outcome = OperationOutcome() + outcome + .addIssue() + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.EXCEPTION) + .setDiagnostics(exception.message) + .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception))) + + return outcome + } + + override fun toCqlText(value: Value?): IBaseDatatype? { + if (value == null) { + return null + } + + val s = ToStringEvaluator.toString(value)?.value + val text = StringType(s) + text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true)) + return text + } + + companion object { + private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType { + val result = BooleanType(null as kotlin.String?) + result.addExtension().setUrl(url).setValue(value) + return result + } + + private fun addPartWithNameAndValue( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Any, + ) { + if (value is Parameters.ParametersParameterComponent) { + value.setName(key) + param.addPart(value) + } else { + val part = param.addPart().setName(key) + when (value) { + is Resource -> { + part.setResource(value) + } + + is Type -> { + part.setValue(value) + } + + else -> { + throw IllegalArgumentException( + "Unsupported FHIR type: " + value.javaClass.getName() + ) + } + } + } + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..8e51e29aacdd5b0249b18c45676cafd16e36dd54 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverter.kt @@ -0,0 +1,444 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import java.math.BigDecimal +import java.util.* +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseDatatype +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value + +/** + * Provides functions for converting from CQL-to-FHIR and vice versa. The return types on the + * functions represent the most derived common type or interface across all FHIR versions. The + * implementations of this interface are expected to return the appropriate version specific + * structure for a given conversion (e.g. the interface for toFhirBoolean is defined as + * IPrimitiveType<Boolean> but it will return n dstu3.model.BooleanType or + * r4.model.BooleanType and so on). + */ +interface FhirTypeConverter { + // CQL-to-FHIR conversions + /** + * Tests if an Object is a FHIR structure + * + * @param value the value to test + * @return true if value is a FHIR structure, false otherwise + * @throws NullPointerException if value is null + */ + fun isFhirType(value: Any): kotlin.Boolean + + /** + * Converts an Object to a FHIR structure. + * + * @param value the value to convert + * @return a FHIR structure + * @throws IllegalArgumentException is value is an Iterable + */ + fun toFhirType(value: Value?): IBase? + + /** + * Converts an iterable of Objects to FHIR structures. Preserves ordering, nulls, and sublist + * hierarchy + * + * @param values an Iterable containing CQL structures, nulls, or sublists + * @return n List containing FHIR types, nulls, and sublists + */ + fun toFhirTypes(values: List): MutableList? + + /** + * Converts an Object to the equivalent CQL representation. This is used for arbitrary types + * that do not have well-defined FHIR mappings, such as CQL Integer Intervals. + * + * The default implementation should use the CQL ToString operator and embed add the cqf-cqlText + * extension to the FHIR structure. + * + * @param value the value to convert + * @return a FHIR String + * @return + */ + fun toCqlText(value: Value?): IBaseDatatype? + + /** + * Converts an Exception to a FHIR OperationOutcome. + * + * The default implementation should create an OperationOutcome with an issue of type + * "exception" and severity "error", and include the exception message and stack trace in the + * details. + * + * @param exception + * @return a FHIR OperationOutcome + */ + fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? + + /** + * Converts a String to a FHIR Id + * + * @param value the value to convert + * @return a FHIR Id + */ + fun toFhirId(value: String?): IIdType? + + /** + * Converts a Boolean to a FHIR Boolean + * + * @param value the value to convert + * @return a FHIR Boolean + */ + fun toFhirBoolean(value: Boolean?): IPrimitiveType? + + /** + * Converts an Integer to a FHIR Integer + * + * @param value the value to convert + * @return a FHIR Integer + */ + fun toFhirInteger(value: Integer?): IPrimitiveType? + + /** + * Converts a Long to a FHIR Integer64 + * + * @param value the value to convert + * @return a FHIR Integer64 + */ + fun toFhirInteger64(value: Long?): IPrimitiveType? + + /** + * Converts a BigDecimal to a FHIR Decimal + * + * @param value the value to convert + * @return a FHIR Decimal + */ + fun toFhirDecimal(value: Decimal?): IPrimitiveType? + + /** + * Converts a CQL Date to a FHIR Date + * + * @param value the value to convert + * @return a FHIR Date + */ + fun toFhirDate(value: org.opencds.cqf.cql.engine.runtime.Date?): IPrimitiveType? + + /** + * Converts a CQL DateTime to a FHIR DateTime + * + * @param value the value to convert + * @return a FHIR DateTime + */ + fun toFhirDateTime(value: DateTime?): IPrimitiveType? + + /** + * Converts a CQL Time to a FHIR Time + * + * @param value the value to convert + * @return a FHIR Time + */ + fun toFhirTime(value: Time?): IPrimitiveType? + + /** + * Converts a String to a FHIR String + * + * @param value the value to convert + * @return a FHIR String + */ + fun toFhirString(value: String?): IPrimitiveType? + + /** + * Converts a CQL Quantity to a FHIR Quantity + * + * @param value the value to convert + * @return a FHIR Quantity + */ + fun toFhirQuantity(value: Quantity?): ICompositeType? + + /** + * Determines whether the given string is a CQL calendar unit + * + * @param unit + * @return true if the given unit is a CQL calendar unit + */ + fun isCqlCalendarUnit(unit: kotlin.String?): kotlin.Boolean + + /** + * Converts the given CQL unit to a UCUM definite-time duration unit according to the table and + * process defined in the CQL specification: https://cql.hl7.org/02-authorsguide.html#quantities + * + * @param unit + * @return An equivalent UCUM unit for the given CQL calendar duration unit, if the input is a + * CQL calendar duration unit, otherwise returns the input unit. + */ + fun toUcumUnit(unit: kotlin.String?): kotlin.String? + + /** + * Converts an Ucum unit to the equivalent CQL unit according to the table defined in the CQL + * specification: https://cql.hl7.org/02-authorsguide.html#quantities + * + * @param unit + * @return A CQL calendar unit if the input unit is an Ucum definite-duration unit, otherwise, + * the input unit + */ + fun toCqlCalendarUnit(unit: kotlin.String?): kotlin.String? + + /** + * Converts a CQL Ratio to a FHIR Ratio + * + * @param value the value to convert + * @return a FHIR Ratio + */ + fun toFhirRatio(value: Ratio?): ICompositeType? + + /** + * Converts a CQL Code to a FHIR Coding + * + * @param value the value to convert + * @return a FHIR Coding + */ + fun toFhirCoding(value: Code?): IBaseCoding? + + /** + * Converts a CQL Concept to a FHIR CodeableConcept + * + * @param value the value to convert + * @return a FHIR CodeableConcept + */ + fun toFhirCodeableConcept(value: Concept?): ICompositeType? + + /** + * Converts a CQL Interval to a FHIR Period + * + * @param value a Date or DateTime Interval + * @return a FHIR Period + */ + fun toFhirPeriod(value: Interval?): ICompositeType? + + /** + * Converts a CQL Interval to a FHIR Range + * + * @param value a Quantity Interval + * @return a FHIR Range + */ + fun toFhirRange(value: Interval?): ICompositeType? + + /** + * Converts a CQL Interval to FHIR Range or Period + * + * @param value a Quantity, Date, or DateTime interval + * @return A FHIR Range or Period + */ + fun toFhirInterval(value: Interval?): IBase? + + /** + * Converts a CQL Tuple to a FHIR Structure + * + * @param value the value to convert + * @return a FHIR Structure + */ + fun toFhirTuple(value: Tuple?): IBase? + + // FHIR-to-CQL conversions + /** + * Tests if an Object is a CQL type + * + * @param value the value to convert + * @return true if value is a CQL type, false otherwise + * @throws NullPointerException if value is null + */ + fun isCqlType(value: Any): kotlin.Boolean + + /** + * Converts an Object to a CQL type. + * + * @param value the value to convert a FHIR structure + * @return a CQL type + * @throws IllegalArgumentException is value is an Iterable + */ + fun toCqlType(value: Any?): Any? + + /** + * Converts an iterable of Objects to CQL types. Preserves ordering, nulls, and sublist + * hierarchy + * + * @param values the values to convert an Iterable containing FHIR structures, nulls, or + * sublists + * @return an Iterable containing CQL types, nulls, and sublists + */ + fun toCqlTypes(values: Iterable<*>): Iterable? + + /** + * Converts a FHIR Id to a CQL String + * + * @param value the value to convert + * @return a String + */ + fun toCqlId(value: IIdType?): String? + + /** + * Converts a FHIR Boolean to a CQL Boolean + * + * @param value the value to convert + * @return a Boolean + */ + fun toCqlBoolean(value: IPrimitiveType?): Boolean? + + /** + * Converts a FHIR Integer to a CQL Integer + * + * @param value the value to convert + * @return an Integer + */ + fun toCqlInteger(value: IPrimitiveType?): Integer? + + /** + * Converts a FHIR Integer64 to a CQL Long + * + * @param value the value to convert + * @return a Long + */ + fun toCqlLong(value: IPrimitiveType?): Long? + + /** + * Converts a FHIR Decimal to a CQL Decimal + * + * @param value the value to convert + * @return a BigDecimal + */ + fun toCqlDecimal(value: IPrimitiveType?): Decimal? + + /** + * Converts a FHIR Date to a CQL Date + * + * @param value the value to convert + * @return a CQL Date + * @throws IllegalArgumentException if value is not a Date + */ + fun toCqlDate(value: IPrimitiveType?): org.opencds.cqf.cql.engine.runtime.Date? + + /** + * Converts a FHIR DateTime to a CQL DateTime + * + * @param value the value to convert + * @return a CQL DateTime + * @throws IllegalArgumentException if value is not a DateTime + */ + fun toCqlDateTime(value: IPrimitiveType?): DateTime? + + /** + * Converts a FHIR DateTime, Date, or Instance to a CQL BaseTemporal + * + * @param value the value to convert + * @return a CQL BaseTemporal + * @throws IllegalArgumentException if value is not a DateTime, Date, or Instant + */ + fun toCqlTemporal(value: IPrimitiveType?): BaseTemporal? + + /** + * Converts a FHIR Time to a CQL Time + * + * @param value the value to convert + * @return a CQL Time + * @throws IllegalArgumentException if value is not a Time + */ + fun toCqlTime(value: IPrimitiveType?): Time? + + /** + * Converts a FHIR String to a CQL String + * + * @param value the value to convert + * @return a String + */ + fun toCqlString(value: IPrimitiveType?): String? + + /** + * Converts a FHIR Quantity to a CQL Quantity + * + * @param value the value to convert + * @return a CQL Quantity + * @throws IllegalArgumentException if value is not a Quantity + */ + fun toCqlQuantity(value: ICompositeType?): Quantity? + + /** + * Converts a FHIR Ratio to a CQL Ratio + * + * @param value the value to convert + * @return a CQL Ratio + * @throws IllegalArgumentException if value is not a Ratio + */ + fun toCqlRatio(value: ICompositeType?): Ratio? + + /** + * Converts a FHIR Any to a CQL Any + * + * @param value the value to convert + * @return a CQL Any + */ + fun toCqlAny(value: IBase?): Any? + + /** + * Converts a FHIR Coding to a CQL Code + * + * @param value the value to convert + * @return a CQL Code + */ + fun toCqlCode(value: IBaseCoding?): Code? + + /** + * Converts a FHIR CodeableConcept to a CQL Concept + * + * @param value the value to convert + * @return a CQL Concept + * @throws IllegalArgumentException if value is not a CodeableConcept + */ + fun toCqlConcept(value: ICompositeType?): Concept? + + /** + * Converts a FHIR Range or Period to a CQL Interval + * + * @param value the value to convert + * @return a CQL Interval + * @throws IllegalArgumentException if value is not a Range or Period + */ + fun toCqlInterval(value: ICompositeType?): Interval? + + /** + * Converts a FHIR Structure to a CQL Tuple + * + * @param value the value to convert + * @return a CQL Tuple + */ + fun toCqlTuple(value: IBase?): Tuple? + + companion object { + const val EMPTY_LIST_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-isEmptyList" + const val EMPTY_TUPLE_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-isEmptyTuple" + const val DATA_ABSENT_REASON_EXT_URL = + "http://hl7.org/fhir/StructureDefinition/data-absent-reason" + const val DATA_ABSENT_REASON_UNKNOWN_CODE = "unknown" + const val CQL_TYPE_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-cqlType" + + // Stacktrace of an exception that occurred during CQL evaluation, as the native platform + // represents it (e.g. Java) + const val NATIVE_STACK_TRACE_EXT_URL = + "http://hl7.org/fhir/StructureDefinition/cqf-nativeStackTrace" + + // The CQL representation of a FHIR structure. + const val CQL_TEXT_EXT_URL = "http://hl7.org/fhir/StructureDefinition/cqf-cqlText" + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverterFactory.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverterFactory.kt new file mode 100644 index 0000000000000000000000000000000000000000..61834097d59260065e11f7812216f5fb547adadc --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/FhirTypeConverterFactory.kt @@ -0,0 +1,25 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.context.FhirVersionEnum + +class FhirTypeConverterFactory { + /** + * Creates a FHIR version specific FhirTypeConverter + * + * @param fhirVersionEnum the version of FHIR to create a converter for + * @return a FhirTypeConverter + * @throws IllegalArgumentException if the FHIR version specified is not supported + */ + fun create(fhirVersionEnum: FhirVersionEnum): FhirTypeConverter { + return when (fhirVersionEnum) { + FhirVersionEnum.DSTU2_HL7ORG -> Dstu2FhirTypeConverter() + FhirVersionEnum.DSTU3 -> Dstu3FhirTypeConverter() + FhirVersionEnum.R4 -> R4FhirTypeConverter() + FhirVersionEnum.R5 -> R5FhirTypeConverter() + else -> + throw IllegalArgumentException( + "Unsupported FHIR version for type conversion: $fhirVersionEnum" + ) + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R4FhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R4FhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..0bd6fd4e13948ceb1bfdc4bb25fe0cb3083b9bf8 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R4FhirTypeConverter.kt @@ -0,0 +1,545 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.math.BigDecimal +import java.time.format.DateTimeFormatter +import java.util.* +import java.util.stream.Collectors +import org.apache.commons.lang3.NotImplementedException +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseDatatype +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.hl7.fhir.r4.model.BaseDateTimeType +import org.hl7.fhir.r4.model.BooleanType +import org.hl7.fhir.r4.model.CodeType +import org.hl7.fhir.r4.model.CodeableConcept +import org.hl7.fhir.r4.model.Coding +import org.hl7.fhir.r4.model.DateTimeType +import org.hl7.fhir.r4.model.DateType +import org.hl7.fhir.r4.model.DecimalType +import org.hl7.fhir.r4.model.IdType +import org.hl7.fhir.r4.model.IntegerType +import org.hl7.fhir.r4.model.OperationOutcome +import org.hl7.fhir.r4.model.Parameters +import org.hl7.fhir.r4.model.Period +import org.hl7.fhir.r4.model.Range +import org.hl7.fhir.r4.model.Resource +import org.hl7.fhir.r4.model.StringType +import org.hl7.fhir.r4.model.TimeType +import org.hl7.fhir.r4.model.Type +import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TYPE_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName +import org.opencds.cqf.cql.engine.runtime.dateTypeName +import org.opencds.cqf.cql.engine.runtime.quantityTypeName + +internal class R4FhirTypeConverter : BaseFhirTypeConverter() { + override fun toFhirId(value: String?): IIdType? { + if (value == null) { + return null + } + + return IdType(value.value) + } + + override fun toFhirBoolean(value: Boolean?): BooleanType? { + if (value == null) { + return null + } + + return BooleanType(value.value) + } + + override fun toFhirInteger(value: Integer?): IPrimitiveType? { + if (value == null) { + return null + } + + return IntegerType(value.value) + } + + override fun toFhirInteger64(value: Long?): IPrimitiveType { + throw IllegalArgumentException("FHIR R4 does not support Long/Integer64 values") + } + + // R4 has no integer64, so Using CQL with FHIR maps System.Long to FHIR.string, without the L + // suffix of the CQL literal. cqf-cqlType keeps the result from reading as a System.String. + override fun toFhirLong(value: Long): IBase? { + val result = StringType(value.value.toString()) + result.addExtension(CQL_TYPE_EXT_URL, StringType("System.Long")) + return result + } + + override fun toFhirDecimal(value: Decimal?): IPrimitiveType? { + if (value == null) { + return null + } + + return DecimalType(value.value) + } + + override fun toFhirDate( + value: org.opencds.cqf.cql.engine.runtime.Date? + ): IPrimitiveType? { + if (value == null) { + return null + } + + return DateType(value.toStringInner()) + } + + override fun toFhirDateTime(value: DateTime?): IPrimitiveType? { + if (value == null) { + return null + } + + val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + result.precision = toFhirPrecision(value.precision!!) + return result + } + + override fun toFhirTime(value: Time?): IPrimitiveType? { + if (value == null) { + return null + } + + return TimeType(value.toStringInner()) + } + + override fun toFhirString(value: String?): IPrimitiveType? { + if (value == null) { + return null + } + + return StringType(value.value) + } + + override fun toFhirQuantity(value: Quantity?): ICompositeType? { + if (value == null) { + return null + } + + val unit = value.unit + val system = + if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units" + else "http://unitsofmeasure.org" + val ucumUnit = toUcumUnit(unit) + + return org.hl7.fhir.r4.model + .Quantity() + .setSystem(system) + .setCode(ucumUnit) + .setValue(value.value) + .setUnit(unit) + } + + override fun toFhirRatio(value: Ratio?): ICompositeType? { + if (value == null) { + return null + } + + return org.hl7.fhir.r4.model + .Ratio() + .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.r4.model.Quantity?) + .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.r4.model.Quantity?) + } + + override fun toFhirCoding(value: Code?): IBaseCoding? { + if (value == null) { + return null + } + + val coding = Coding() + coding.setSystem(value.system) + coding.setCode(value.code) + coding.setDisplay(value.display) + coding.setVersion(value.version) + return coding + } + + override fun toFhirCodeableConcept(value: Concept?): ICompositeType? { + if (value == null) { + return null + } + + val codeableConcept = CodeableConcept() + codeableConcept.setText(value.display) + if (value.codes != null) { + for (c in value.codes) { + codeableConcept.addCoding(toFhirCoding(c) as Coding?) + } + } + + return codeableConcept + } + + override fun toFhirPeriod(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + val period = Period() + if (value.pointType == dateTimeTypeName) { + if (value.start != null) { + period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType? + } + + if (value.end != null) { + period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType? + } + + return period + } else if (value.pointType == dateTypeName) { + // TODO: This will construct DateTimeType values in FHIR with the system + // timezone id, not the + // timezoneoffset of the evaluation request..... this is a bug waiting to happen + if (value.start != null) { + period.setStart( + toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + if (value.end != null) { + period.setEnd( + toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + return period + } + + throw IllegalArgumentException( + "FHIR Period can only be created from an Interval of Date or DateTime type" + ) + } + + override fun toFhirRange(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + require(value.pointType == quantityTypeName) { + "FHIR Range can only be created from an Interval of Quantity type" + } + + val range = Range() + range.setLow(toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.r4.model.Quantity?) + range.setHigh(toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.r4.model.Quantity?) + + return range + } + + private fun addElementToParameter( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Value?, + ) { + if (value == null) { + // Null value, add a single empty value with an extension indicating the reason + val dataAbsentValue: BooleanType = + emptyBooleanWithExtension( + DATA_ABSENT_REASON_EXT_URL, + CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE), + ) + addPartWithNameAndValue(param, key, dataAbsentValue) + return + } + + if (value !is List) { + // Single, non-null value + addPartWithNameAndValue(param, key, toFhirType(value)!!) + return + } + + val iterable = value + + if (!iterable.iterator().hasNext()) { + // Empty list + val emptyListValue: BooleanType = + emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true)) + addPartWithNameAndValue(param, key, emptyListValue) + } else { + // Non-empty list, one part per value + val fhirTypes = this.toFhirTypes(iterable) + for (fhirType in fhirTypes) { + addPartWithNameAndValue(param, key, fhirType!!) + } + } + } + + override fun toFhirTuple(value: Tuple?): IBase? { + if (value == null) { + return null + } + + val parameters = Parameters() + val param = parameters.addParameter() + + if (value.elements.isEmpty()) { + param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true))) + } + + for (key in value.elements.keys) { + addElementToParameter(param, key, value.elements[key]) + } + + return param + } + + override fun toCqlQuantity(value: ICompositeType?): Quantity? { + if (value == null) { + return null + } + + require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" } + + val quantity = value as org.hl7.fhir.r4.model.Quantity + require(!quantity.hasComparator()) { + "Cannot convert a FHIR Quantity with a comparator to a CQL quantity" + } + return Quantity() + .withUnit(toCqlCalendarUnit(quantity.getUnit())) + .withValue(quantity.getValue()) + } + + override fun toCqlRatio(value: ICompositeType?): Ratio? { + if (value == null) { + return null + } + + require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" } + + val ratio = value as org.hl7.fhir.r4.model.Ratio + + return Ratio() + .withNumerator(toCqlQuantity(ratio.getNumerator())) + .withDenominator(toCqlQuantity(ratio.getDenominator())) + } + + override fun toCqlAny(value: IBase?): Any? { + if (value == null) { + return null + } + + throw NotImplementedException("Unable to convert to System.Any type") + } + + override fun toCqlCode(value: IBaseCoding?): Code? { + if (value == null) { + return null + } + + val coding = value as Coding + + return Code() + .withSystem(coding.getSystem()) + .withCode(coding.getCode()) + .withVersion(coding.getVersion()) + .withDisplay(coding.getDisplay()) + } + + override fun toCqlConcept(value: ICompositeType?): Concept? { + if (value == null) { + return null + } + + require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" } + + val codeableConcept = value as CodeableConcept + + return Concept() + .withDisplay(codeableConcept.getText()) + .withCodes( + codeableConcept + .getCoding() + .stream() + .map { x: Coding? -> toCqlCode(x) } + .collect(Collectors.toList()) + ) + } + + override fun toCqlInterval(value: ICompositeType?): Interval? { + if (value == null) { + return null + } + + if (value.fhirType() == "Range") { + val range = value as Range + return Interval( + toCqlQuantity(range.getLow()), + true, + toCqlQuantity(range.getHigh()), + true, + ) + } else if (value.fhirType() == "Period") { + val period = value as Period + return Interval( + toCqlTemporal(period.startElement), + true, + toCqlTemporal(period.endElement), + true, + ) + } else { + throw IllegalArgumentException("value is not a FHIR Range or Period") + } + } + + override fun toCqlDate(value: IPrimitiveType?): org.opencds.cqf.cql.engine.runtime.Date? { + if (value == null) { + return null + } + + require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) { + "value is not a FHIR Date or DateTime" + } + + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + throw IllegalArgumentException("value has a precision higher than a CQL Date") + + else -> throw IllegalArgumentException("value has a precision higher than a CQL Date") + } + } + + override fun toCqlDateTime(value: IPrimitiveType?): DateTime? { + if (value == null) { + return null + } + + if (value.fhirType() == "instant" || value.fhirType() == "dateTime") { + val baseDateTime = value as BaseDateTimeType + return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toCqlTemporal(value: IPrimitiveType?): BaseTemporal? { + if (value == null) { + return null + } + + if ( + value.fhirType() == "instant" || + value.fhirType() == "dateTime" || + value.fhirType() == "date" + ) { + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + else -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + } + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? { + if (exception == null) { + return null + } + + val outcome = OperationOutcome() + outcome + .addIssue() + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.EXCEPTION) + .setDiagnostics(exception.message) + .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception))) + + return outcome + } + + override fun toCqlText(value: Value?): IBaseDatatype? { + if (value == null) { + return null + } + + val s = ToStringEvaluator.toString(value)?.value + val text = StringType(s) + text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true)) + return text + } + + companion object { + private fun emptyBooleanWithExtension(url: kotlin.String?, value: Type?): BooleanType { + val result = BooleanType(null as kotlin.String?) + result.addExtension().setUrl(url).setValue(value) + return result + } + + private fun addPartWithNameAndValue( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Any, + ) { + if (value is Parameters.ParametersParameterComponent) { + value.setName(key) + param.addPart(value) + } else { + val part = param.addPart().setName(key) + when (value) { + is Resource -> part.setResource(value) + is Type -> part.setValue(value) + else -> + throw IllegalArgumentException( + "Unsupported FHIR type: " + value.javaClass.getName() + ) + } + } + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R5FhirTypeConverter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R5FhirTypeConverter.kt new file mode 100644 index 0000000000000000000000000000000000000000..accb1076b7d66b7108a1097f5a767e5ae2fd9b22 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/converter/R5FhirTypeConverter.kt @@ -0,0 +1,541 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.math.BigDecimal +import java.time.format.DateTimeFormatter +import java.util.* +import java.util.stream.Collectors +import org.apache.commons.lang3.NotImplementedException +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseDatatype +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.hl7.fhir.r5.model.BaseDateTimeType +import org.hl7.fhir.r5.model.BooleanType +import org.hl7.fhir.r5.model.CodeType +import org.hl7.fhir.r5.model.CodeableConcept +import org.hl7.fhir.r5.model.Coding +import org.hl7.fhir.r5.model.DataType +import org.hl7.fhir.r5.model.DateTimeType +import org.hl7.fhir.r5.model.DateType +import org.hl7.fhir.r5.model.DecimalType +import org.hl7.fhir.r5.model.IdType +import org.hl7.fhir.r5.model.Integer64Type +import org.hl7.fhir.r5.model.IntegerType +import org.hl7.fhir.r5.model.OperationOutcome +import org.hl7.fhir.r5.model.Parameters +import org.hl7.fhir.r5.model.Period +import org.hl7.fhir.r5.model.Range +import org.hl7.fhir.r5.model.Resource +import org.hl7.fhir.r5.model.StringType +import org.hl7.fhir.r5.model.TimeType +import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.CQL_TEXT_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.DATA_ABSENT_REASON_UNKNOWN_CODE +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_LIST_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.EMPTY_TUPLE_EXT_URL +import org.opencds.cqf.cql.engine.fhir.converter.FhirTypeConverter.Companion.NATIVE_STACK_TRACE_EXT_URL +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Long +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Ratio +import org.opencds.cqf.cql.engine.runtime.String +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.dateTimeTypeName +import org.opencds.cqf.cql.engine.runtime.dateTypeName +import org.opencds.cqf.cql.engine.runtime.quantityTypeName + +internal class R5FhirTypeConverter : BaseFhirTypeConverter() { + override fun toFhirId(value: String?): IIdType? { + if (value == null) { + return null + } + + return IdType(value.value) + } + + override fun toFhirBoolean(value: Boolean?): BooleanType? { + if (value == null) { + return null + } + + return BooleanType(value.value) + } + + override fun toFhirInteger(value: Integer?): IPrimitiveType? { + if (value == null) { + return null + } + + return IntegerType(value.value) + } + + override fun toFhirInteger64(value: Long?): IPrimitiveType? { + if (value == null) { + return null + } + + return Integer64Type(value.value) + } + + override fun toFhirDecimal(value: Decimal?): IPrimitiveType? { + if (value == null) { + return null + } + + return DecimalType(value.value) + } + + override fun toFhirDate( + value: org.opencds.cqf.cql.engine.runtime.Date? + ): IPrimitiveType? { + if (value == null) { + return null + } + + return DateType(value.toStringInner()) + } + + override fun toFhirDateTime(value: DateTime?): IPrimitiveType? { + if (value == null) { + return null + } + + val result = DateTimeType(value.dateTime!!.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + result.precision = toFhirPrecision(value.precision!!) + return result + } + + override fun toFhirTime(value: Time?): IPrimitiveType? { + if (value == null) { + return null + } + + return TimeType(value.toStringInner()) + } + + override fun toFhirString(value: String?): IPrimitiveType? { + if (value == null) { + return null + } + + return StringType(value.value) + } + + override fun toFhirQuantity(value: Quantity?): ICompositeType? { + if (value == null) { + return null + } + + val unit = value.unit + val system = + if (isCqlCalendarUnit(unit)) "http://hl7.org/fhirpath/CodeSystem/calendar-units" + else "http://unitsofmeasure.org" + val ucumUnit = toUcumUnit(unit) + + return org.hl7.fhir.r5.model + .Quantity() + .setSystem(system) + .setCode(ucumUnit) + .setValue(value.value) + .setUnit(unit) + } + + override fun toFhirRatio(value: Ratio?): ICompositeType? { + if (value == null) { + return null + } + + return org.hl7.fhir.r5.model + .Ratio() + .setNumerator(toFhirQuantity(value.numerator) as org.hl7.fhir.r5.model.Quantity?) + .setDenominator(toFhirQuantity(value.denominator) as org.hl7.fhir.r5.model.Quantity?) + } + + override fun toFhirCoding(value: Code?): IBaseCoding? { + if (value == null) { + return null + } + + val coding = Coding() + coding.setSystem(value.system) + coding.setCode(value.code) + coding.setDisplay(value.display) + coding.setVersion(value.version) + return coding + } + + override fun toFhirCodeableConcept(value: Concept?): ICompositeType? { + if (value == null) { + return null + } + + val codeableConcept = CodeableConcept() + codeableConcept.setText(value.display) + if (value.codes != null) { + for (c in value.codes) { + codeableConcept.addCoding(toFhirCoding(c) as Coding?) + } + } + + return codeableConcept + } + + override fun toFhirPeriod(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + val period = Period() + if (value.pointType == dateTimeTypeName) { + if (value.start != null) { + period.startElement = toFhirDateTime(value.start as DateTime?) as DateTimeType? + } + + if (value.end != null) { + period.endElement = toFhirDateTime(value.end as DateTime?) as DateTimeType? + } + + return period + } else if (value.pointType == dateTypeName) { + // TODO: This will construct DateTimeType values in FHIR with the system timezone id, + // not the + // timezoneoffset of the evaluation request..... this is a bug waiting to happen + if (value.start != null) { + period.setStart( + toFhirDate(value.start as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + if (value.end != null) { + period.setEnd( + toFhirDate(value.end as org.opencds.cqf.cql.engine.runtime.Date?)!!.getValue() + ) + } + + return period + } + + throw IllegalArgumentException( + "FHIR Period can only be created from an Interval of Date or DateTime type" + ) + } + + override fun toFhirRange(value: Interval?): ICompositeType? { + if (value == null) { + return null + } + + require(value.pointType == quantityTypeName) { + "FHIR Range can only be created from an Interval of Quantity type" + } + + val range = Range() + range.setLow(toFhirQuantity(value.start as Quantity?) as org.hl7.fhir.r5.model.Quantity?) + range.setHigh(toFhirQuantity(value.end as Quantity?) as org.hl7.fhir.r5.model.Quantity?) + + return range + } + + private fun addElementToParameter( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Value?, + ) { + if (value == null) { + // Null value, add a single empty value with an extension indicating the reason + val dataAbsentValue: BooleanType = + emptyBooleanWithExtension( + DATA_ABSENT_REASON_EXT_URL, + CodeType(DATA_ABSENT_REASON_UNKNOWN_CODE), + ) + addPartWithNameAndValue(param, key, dataAbsentValue) + return + } + + if (value !is List) { + // Single, non-null value + addPartWithNameAndValue(param, key, toFhirType(value)!!) + return + } + + val iterable = value + + if (!iterable.iterator().hasNext()) { + // Empty list + val emptyListValue: BooleanType = + emptyBooleanWithExtension(EMPTY_LIST_EXT_URL, BooleanType(true)) + addPartWithNameAndValue(param, key, emptyListValue) + } else { + // Non-empty list, one part per value + val fhirTypes = this.toFhirTypes(iterable) + for (fhirType in fhirTypes) { + addPartWithNameAndValue(param, key, fhirType!!) + } + } + } + + override fun toFhirTuple(value: Tuple?): IBase? { + if (value == null) { + return null + } + + val parameters = Parameters() + val param = parameters.addParameter() + + if (value.elements.isEmpty()) { + param.setValue(emptyBooleanWithExtension(EMPTY_TUPLE_EXT_URL, BooleanType(true))) + } + + for (key in value.elements.keys) { + addElementToParameter(param, key, value.elements[key]) + } + + return param + } + + override fun toCqlQuantity(value: ICompositeType?): Quantity? { + if (value == null) { + return null + } + + require(value.fhirType() == "Quantity") { "value is not a FHIR Quantity" } + + val quantity = value as org.hl7.fhir.r5.model.Quantity + require(!quantity.hasComparator()) { + "Cannot convert a FHIR Quantity with a comparator to a CQL quantity" + } + return Quantity() + .withUnit(toCqlCalendarUnit(quantity.getUnit())) + .withValue(quantity.getValue()) + } + + override fun toCqlRatio(value: ICompositeType?): Ratio? { + if (value == null) { + return null + } + + require(value.fhirType() == "Ratio") { "value is not a FHIR Ratio" } + + val ratio = value as org.hl7.fhir.r5.model.Ratio + + return Ratio() + .withNumerator(toCqlQuantity(ratio.getNumerator())) + .withDenominator(toCqlQuantity(ratio.getDenominator())) + } + + override fun toCqlAny(value: IBase?): Any? { + if (value == null) { + return null + } + + throw NotImplementedException("Unable to convert to System.Any type") + } + + override fun toCqlCode(value: IBaseCoding?): Code? { + if (value == null) { + return null + } + + val coding = value as Coding + + return Code() + .withSystem(coding.getSystem()) + .withCode(coding.getCode()) + .withVersion(coding.getVersion()) + .withDisplay(coding.getDisplay()) + } + + override fun toCqlConcept(value: ICompositeType?): Concept? { + if (value == null) { + return null + } + + require(value.fhirType() == "CodeableConcept") { "value is not a FHIR CodeableConcept" } + + val codeableConcept = value as CodeableConcept + + return Concept() + .withDisplay(codeableConcept.getText()) + .withCodes( + codeableConcept + .getCoding() + .stream() + .map { value: Coding? -> this.toCqlCode(value) } + .collect(Collectors.toList()) + ) + } + + override fun toCqlInterval(value: ICompositeType?): Interval? { + if (value == null) { + return null + } + + if (value.fhirType() == "Range") { + val range = value as Range + return Interval( + toCqlQuantity(range.getLow()), + true, + toCqlQuantity(range.getHigh()), + true, + ) + } else if (value.fhirType() == "Period") { + val period = value as Period + return Interval( + toCqlTemporal(period.startElement), + true, + toCqlTemporal(period.endElement), + true, + ) + } else { + throw IllegalArgumentException("value is not a FHIR Range or Period") + } + } + + override fun toCqlDate(value: IPrimitiveType?): org.opencds.cqf.cql.engine.runtime.Date? { + if (value == null) { + return null + } + + require(!(value.fhirType() != "date" || value.fhirType() == "dateTime")) { + "value is not a FHIR Date or DateTime" + } + + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + throw IllegalArgumentException("value has a precision higher than a CQL Date") + + else -> throw IllegalArgumentException("value has a precision higher than a CQL Date") + } + } + + override fun toCqlDateTime(value: IPrimitiveType?): DateTime? { + if (value == null) { + return null + } + + if (value.fhirType() == "instant" || value.fhirType() == "dateTime") { + val baseDateTime = value as BaseDateTimeType + return toDateTime(baseDateTime.valueAsCalendar, baseDateTime.precision.calendarConstant) + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toCqlTemporal(value: IPrimitiveType?): BaseTemporal? { + if (value == null) { + return null + } + + if ( + value.fhirType() == "instant" || + value.fhirType() == "dateTime" || + value.fhirType() == "date" + ) { + val baseDateTime = value as BaseDateTimeType + when (baseDateTime.precision) { + TemporalPrecisionEnum.YEAR, + TemporalPrecisionEnum.DAY, + TemporalPrecisionEnum.MONTH -> + return toDate( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + TemporalPrecisionEnum.SECOND, + TemporalPrecisionEnum.MILLI, + TemporalPrecisionEnum.MINUTE -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + + else -> + return toDateTime( + baseDateTime.valueAsCalendar, + baseDateTime.precision.calendarConstant, + ) + } + } else { + throw IllegalArgumentException("value is not a FHIR Instant or DateTime") + } + } + + override fun toFhirOperationOutcome(exception: Exception?): IBaseOperationOutcome? { + if (exception == null) { + return null + } + + val outcome = OperationOutcome() + outcome + .addIssue() + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.EXCEPTION) + .setDiagnostics(exception.message) + .addExtension(NATIVE_STACK_TRACE_EXT_URL, StringType(getStackTraceAsString(exception))) + + return outcome + } + + override fun toCqlText(value: Value?): IBaseDatatype? { + if (value == null) { + return null + } + + val s = ToStringEvaluator.toString(value)?.value + val text = StringType(s) + text.addExtension(CQL_TEXT_EXT_URL, BooleanType(true)) + return text + } + + companion object { + private fun emptyBooleanWithExtension(url: kotlin.String?, value: DataType?): BooleanType { + val result = BooleanType(null as kotlin.String?) + result.addExtension().setUrl(url).setValue(value) + return result + } + + private fun addPartWithNameAndValue( + param: Parameters.ParametersParameterComponent, + key: kotlin.String?, + value: Any, + ) { + if (value is Parameters.ParametersParameterComponent) { + value.setName(key) + param.addPart(value) + } else { + val part = param.addPart().setName(key) + when (value) { + is Resource -> part.setResource(value) + is DataType -> part.setValue(value) + else -> + throw IllegalArgumentException( + "Unsupported FHIR type: " + value.javaClass.getName() + ) + } + } + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/FhirVersionMisMatchException.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/FhirVersionMisMatchException.kt new file mode 100644 index 0000000000000000000000000000000000000000..f13546ed8fe64ecb93a9dea7e68bb661b0707b17 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/FhirVersionMisMatchException.kt @@ -0,0 +1,3 @@ +package org.opencds.cqf.cql.engine.fhir.exception + +class FhirVersionMisMatchException(message: String?) : RuntimeException(message) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownElement.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownElement.kt new file mode 100644 index 0000000000000000000000000000000000000000..5098ef37a062ff1a656faebb8141e148c8f02d42 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownElement.kt @@ -0,0 +1,5 @@ +package org.opencds.cqf.cql.engine.fhir.exception + +import org.opencds.cqf.cql.engine.exception.DataProviderException + +class UnknownElement(message: String?) : DataProviderException(message) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownPath.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownPath.kt new file mode 100644 index 0000000000000000000000000000000000000000..083f85ae0b7c5ee50cacf347579aecadaf0680bd --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownPath.kt @@ -0,0 +1,5 @@ +package org.opencds.cqf.cql.engine.fhir.exception + +import org.opencds.cqf.cql.engine.exception.DataProviderException + +class UnknownPath(message: String?) : DataProviderException(message) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownType.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownType.kt new file mode 100644 index 0000000000000000000000000000000000000000..15b8ec37c993b6fedcd922fa0e192ba5f31399d0 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/exception/UnknownType.kt @@ -0,0 +1,5 @@ +package org.opencds.cqf.cql.engine.fhir.exception + +import org.opencds.cqf.cql.engine.exception.DataProviderException + +class UnknownType(message: String?) : DataProviderException(message) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu2FhirModelResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu2FhirModelResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..bf3ca4739f8f2199fb075e24899e750b71a7640b --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu2FhirModelResolver.kt @@ -0,0 +1,156 @@ +package org.opencds.cqf.cql.engine.fhir.model + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import java.util.* +import org.hl7.fhir.dstu2.model.AnnotatedUuidType +import org.hl7.fhir.dstu2.model.Base +import org.hl7.fhir.dstu2.model.BaseDateTimeType +import org.hl7.fhir.dstu2.model.EnumFactory +import org.hl7.fhir.dstu2.model.Enumeration +import org.hl7.fhir.dstu2.model.Enumerations +import org.hl7.fhir.dstu2.model.IdType +import org.hl7.fhir.dstu2.model.Resource +import org.hl7.fhir.dstu2.model.SimpleQuantity +import org.hl7.fhir.dstu2.model.TimeType +import org.hl7.fhir.instance.model.api.IBaseResource +import org.opencds.cqf.cql.engine.runtime.BaseTemporal + +open class Dstu2FhirModelResolver(fhirContext: FhirContext) : + FhirModelResolver< + Base, + BaseDateTimeType, + TimeType, + SimpleQuantity, + IdType, + Resource, + Enumeration<*>, + EnumFactory<*>, + >(fhirContext) { + constructor() : this(FhirContext.forDstu2()) + + init { + this.packageNames = + (mutableListOf( + "ca.uhn.fhir.model.dstu2", + "org.hl7.fhir.dstu2.model", + "ca.uhn.fhir.model.primitive", + )) + require(fhirContext.version.version == FhirVersionEnum.DSTU2) { + "The supplied context is not configured for DSTU2" + } + } + + override fun initialize() { + // HAPI has some bugs where it's missing annotations on certain types. This patches that. + this.fhirContext.registerCustomType(AnnotatedUuidType::class.java) + + // The context loads Resources on demand which can cause resolution to fail in certain cases + // This forces all Resource types to be loaded. + + // force calling of validateInitialized(); + this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode()) + + val myNameToResourceType: MutableMap> + try { + val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType") + f.setAccessible(true) + + // This is magic reflection to handle the fact that we need to manually + // initialize this map, but it's a private field with no accessor. + @Suppress("UNCHECKED_CAST") + myNameToResourceType = + f.get(this.fhirContext) as MutableMap> + + val toLoad: MutableList> = + ArrayList>(myNameToResourceType.size) + + for (type in Enumerations.ResourceType.entries) { + // These are abstract types that should never be resolved directly. + when (type) { + Enumerations.ResourceType.DOMAINRESOURCE, + Enumerations.ResourceType.RESOURCE, + Enumerations.ResourceType.NULL -> continue + else -> {} + } + if (myNameToResourceType.containsKey(type.toCode().lowercase())) + toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!) + } + + // Sends a list of all classes to be loaded in bulk. + val m = + this.fhirContext.javaClass.getDeclaredMethod( + "scanResourceTypes", + MutableCollection::class.java, + ) + m.setAccessible(true) + m.invoke(this.fhirContext, toLoad) + } catch (_: Exception) { + // intentionally ignored + } + } + + override fun castToSimpleQuantity(base: Base): SimpleQuantity { + return base.castToSimpleQuantity(base) + } + + override fun getCalendar(dateTime: BaseDateTimeType): Calendar { + return dateTime.toCalendar() + } + + override fun getCalendarConstant(dateTime: BaseDateTimeType): Int { + return dateTime.precision.calendarConstant + } + + override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) { + target.setPrecision(toTemporalPrecisionEnum(value.precision!!)) + } + + override fun timeToString(time: TimeType): String { + return time.value + } + + override fun idToString(id: IdType): String { + return id.idPart + } + + override fun getResourceType(resource: Resource): String { + return resource.fhirType() + } + + override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> { + return Enumeration(factory) + } + + override fun enumChecker(`object`: Any): Boolean { + return `object` is Enumeration<*> + } + + override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> { + val value: Enum<*>? = enumeration.getValue() + if (value != null) { + val enumSimpleName = value.javaClass.getSimpleName() + return this.resolveType(enumSimpleName + "EnumFactory")!! + } else { + val myEnumFactoryField = enumeration.javaClass.getDeclaredField("myEnumFactory") + myEnumFactoryField.setAccessible(true) + val factory = myEnumFactoryField.get(enumeration) as EnumFactory<*> + return factory.javaClass + } + } + + override fun getContextPath(contextType: String?, targetType: String?): String? { + if (targetType == null || contextType == null) { + return null + } + + if ("Patient" == contextType) { + when (targetType) { + "QuestionnaireResponse" -> return "subject" + else -> {} + } + } + + return super.getContextPath(contextType, targetType) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu3FhirModelResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu3FhirModelResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..e9cdb61c9d53623e16bfe4485be31fa1df59b74f --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/Dstu3FhirModelResolver.kt @@ -0,0 +1,162 @@ +package org.opencds.cqf.cql.engine.fhir.model + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import java.util.* +import org.hl7.fhir.dstu3.model.AnnotatedUuidType +import org.hl7.fhir.dstu3.model.Base +import org.hl7.fhir.dstu3.model.BaseDateTimeType +import org.hl7.fhir.dstu3.model.EnumFactory +import org.hl7.fhir.dstu3.model.Enumeration +import org.hl7.fhir.dstu3.model.Enumerations +import org.hl7.fhir.dstu3.model.IdType +import org.hl7.fhir.dstu3.model.Resource +import org.hl7.fhir.dstu3.model.SimpleQuantity +import org.hl7.fhir.dstu3.model.TimeType +import org.hl7.fhir.instance.model.api.IBaseResource +import org.opencds.cqf.cql.engine.runtime.BaseTemporal + +open class Dstu3FhirModelResolver(fhirContext: FhirContext) : + FhirModelResolver< + Base, + BaseDateTimeType, + TimeType, + SimpleQuantity, + IdType, + Resource, + Enumeration<*>, + EnumFactory<*>, + >(fhirContext) { + constructor() : this(FhirContext.forDstu3()) + + init { + this.packageNames = mutableListOf("org.hl7.fhir.dstu3.model") + require(fhirContext.version.version == FhirVersionEnum.DSTU3) { + "The supplied context is not configured for DSTU3" + } + } + + override fun initialize() { + // HAPI has some bugs where it's missing annotations on certain types. This patches that. + this.fhirContext.registerCustomType(AnnotatedUuidType::class.java) + + // The context loads Resources on demand which can cause resolution to fail in certain cases + // This forces all Resource types to be loaded. + + // force calling of validateInitialized(); + this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode()) + + val myNameToResourceType: MutableMap> + try { + val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType") + f.setAccessible(true) + + // This is magic reflection to handle the fact that we need to manually + // initialize this map, but it's a private field with no accessor. + @Suppress("UNCHECKED_CAST") + myNameToResourceType = + f.get(this.fhirContext) as MutableMap> + + val toLoad: MutableList> = + ArrayList>(myNameToResourceType.size) + + for (type in Enumerations.ResourceType.entries) { + // These are abstract types that should never be resolved directly. + when (type) { + Enumerations.ResourceType.DOMAINRESOURCE, + Enumerations.ResourceType.RESOURCE, + Enumerations.ResourceType.NULL -> continue + else -> {} + } + if (myNameToResourceType.containsKey(type.toCode().lowercase())) + toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!) + } + + // Sends a list of all classes to be loaded in bulk. + val m = + this.fhirContext.javaClass.getDeclaredMethod( + "scanResourceTypes", + MutableCollection::class.java, + ) + m.setAccessible(true) + m.invoke(this.fhirContext, toLoad) + } catch (_: Exception) { + // intentionally ignored + } + } + + override fun castToSimpleQuantity(base: Base): SimpleQuantity { + return base.castToSimpleQuantity(base) + } + + override fun getCalendar(dateTime: BaseDateTimeType): Calendar { + return dateTime.valueAsCalendar + } + + override fun getCalendarConstant(dateTime: BaseDateTimeType): Int { + return dateTime.precision.calendarConstant + } + + override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) { + target.precision = toTemporalPrecisionEnum(value.precision!!) + } + + override fun timeToString(time: TimeType): String { + return time.value + } + + override fun idToString(id: IdType): String { + return id.idPart + } + + override fun getResourceType(resource: Resource): String { + return resource.fhirType() + } + + override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> { + return Enumeration(factory) + } + + override fun enumChecker(`object`: Any): Boolean { + return `object` is Enumeration<*> + } + + override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> { + return enumeration.getEnumFactory().javaClass + } + + override fun resolveType(typeName: String?): Class<*>? { + // TODO: Might be able to patch some of these by registering custom types in HAPI. + + var typeName = typeName + when (typeName) { + "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality" + "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus" + "EventStatus" -> typeName = $$"Procedure$ProcedureStatus" + "qualityType" -> typeName = $$"Sequence$QualityType" + "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus" + "repositoryType" -> typeName = $$"Sequence$RepositoryType" + "SampledDataDataType" -> typeName = "StringType" + } + + return super.resolveType(typeName) + } + + override fun getContextPath(contextType: String?, targetType: String?): String? { + if (targetType == null || contextType == null) { + return null + } + + if ("Patient" == contextType) { + when (targetType) { + "MedicationStatement", + "QuestionnaireResponse" -> return "subject" + "Task" -> return "for" + "Coverage" -> return "beneficiary" + else -> {} + } + } + + return super.getContextPath(contextType, targetType) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/FhirModelResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/FhirModelResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..834ff39d16b395c88f8e6108bf43386222db47ca --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/FhirModelResolver.kt @@ -0,0 +1,768 @@ +package org.opencds.cqf.cql.engine.fhir.model + +import ca.uhn.fhir.context.BaseRuntimeChildDefinition +import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.RuntimeChildResourceBlockDefinition +import ca.uhn.fhir.context.RuntimeChildResourceDefinition +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.lang.reflect.InvocationTargetException +import java.util.Calendar +import java.util.GregorianCalendar +import java.util.Optional +import java.util.concurrent.ConcurrentHashMap +import javax.xml.namespace.QName +import org.hl7.fhir.instance.model.api.IAnyResource +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseBackboneElement +import org.hl7.fhir.instance.model.api.IBaseElement +import org.hl7.fhir.instance.model.api.IBaseEnumFactory +import org.hl7.fhir.instance.model.api.IBaseEnumeration +import org.hl7.fhir.instance.model.api.IBaseHasExtensions +import org.hl7.fhir.instance.model.api.IBaseResource +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.instance.model.api.IIdType +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator +import org.opencds.cqf.cql.engine.exception.InvalidPrecision +import org.opencds.cqf.cql.engine.fhir.exception.UnknownType +import org.opencds.cqf.cql.engine.fhir.fhirModelId +import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri +import org.opencds.cqf.cql.engine.model.ModelResolver +import org.opencds.cqf.cql.engine.runtime.BaseTemporal +import org.opencds.cqf.cql.engine.runtime.Boolean +import org.opencds.cqf.cql.engine.runtime.ClassInstance +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Precision +import org.opencds.cqf.cql.engine.runtime.TemporalHelper +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.anyTypeName +import org.opencds.cqf.cql.engine.runtime.toCqlBoolean +import org.opencds.cqf.cql.engine.runtime.toCqlDecimal +import org.opencds.cqf.cql.engine.runtime.toCqlInteger +import org.opencds.cqf.cql.engine.runtime.toCqlList +import org.opencds.cqf.cql.engine.runtime.toCqlLong +import org.opencds.cqf.cql.engine.runtime.toCqlString + +// TODO: Probably quite a bit of redundancy here. Probably only really need the BaseType and the +// PrimitiveType +/* + * type-to-class and contextPath resolutions are potentially expensive and can be cached + * for improved performance. + * + * See + * for a decorator that adds caching logic for ModelResolvers. + */ +@Suppress("TooManyFunctions") +abstract class FhirModelResolver< + BaseType : IBase, + BaseDateTimeType : IPrimitiveType, + TimeType : IPrimitiveType, + SimpleQuantityType : ICompositeType, + IdType : IIdType, + ResourceType : IBaseResource, + EnumerationType : IBaseEnumeration<*>, + EnumFactoryType : IBaseEnumFactory<*>, +>( // getters & setters + // Data members + var fhirContext: FhirContext +) : ModelResolver { + /** Memo for [resolveType]; see the note there. Concurrent because a resolver is shared. */ + private val resolvedTypes = ConcurrentHashMap>>() + + protected abstract fun initialize() + + abstract fun castToSimpleQuantity(base: BaseType): SimpleQuantityType + + protected abstract fun getCalendar(dateTime: BaseDateTimeType): Calendar + + protected abstract fun getCalendarConstant(dateTime: BaseDateTimeType): Int + + protected abstract fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) + + protected abstract fun idToString(id: IdType): String + + protected abstract fun timeToString(time: TimeType): String + + protected abstract fun getResourceType(resource: ResourceType): String + + protected abstract fun enumConstructor(factory: EnumFactoryType): EnumerationType + + protected abstract fun enumChecker(`object`: Any): kotlin.Boolean + + protected abstract fun enumFactoryTypeGetter(enumeration: EnumerationType): Class<*> + + init { + this.initialize() + } + + override fun resolveId(target: Value?): kotlin.String? { + if (target is ClassInstance && target.type.namespaceURI == fhirModelNamespaceUri) { + val clazz = this.resolveType(target.type.localPart) ?: return null + if (IBaseResource::class.java.isAssignableFrom(clazz)) { + val id = target.elements["id"] as? ClassInstance ?: return null + return (id.elements["value"] as? org.opencds.cqf.cql.engine.runtime.String)?.value + } + } + return null + } + + override fun getContextPath( + contextType: kotlin.String?, + targetType: kotlin.String?, + ): kotlin.String? { + if (targetType == null || contextType == null) { + return null + } + + if ( + contextType == "Unfiltered" || + contextType == "Unspecified" || + contextType == "Population" + ) { + return null + } + + if (targetType == contextType) { + return "id" + } + + val resourceDefinition = this.fhirContext.getResourceDefinition(targetType) + val theValue = this.createHapiInstance(contextType) + + // Because we created this instance from the local FhirContext, we know it is an IBase + // The model resolver interface is not generic, so we have to cast here + @Suppress("UNCHECKED_CAST") val type = theValue.javaClass as Class + + val children = resourceDefinition.children + for (child in children) { + val visitedElements: MutableSet = HashSet() + val path = this.innerGetContextPath(visitedElements, child, type) + if (path != null) { + return path + } + } + + return null + } + + protected fun innerGetContextPath( + visitedElements: MutableSet, + child: BaseRuntimeChildDefinition, + type: Class?, + ): String? { + visitedElements.add(child.elementName) + + if (child is RuntimeChildResourceDefinition) { + for (resourceClass in child.resourceTypes) { + if (resourceClass == type) { + return child.elementName + } + } + + return null + } + + if (child is RuntimeChildResourceBlockDefinition) { + val currentName = child.elementName + val element = child.getChildByName(currentName) + + // Potential Kotlin/Java interop issue here? + // element.getChildren() returns ListBaseRuntimeChildDefinition> + @Suppress("UNCHECKED_CAST") + val children = element.getChildren() as List + + for (nextChild in children) { + if (visitedElements.contains(nextChild.elementName)) { + continue + } + + val path = this.innerGetContextPath(visitedElements, nextChild, type) + if (path != null) { + return "$currentName.$path" + } + } + } + + return null + } + + override fun `is`(valueType: String, type: QName): kotlin.Boolean? { + // System.Any is a supertype of all types + if (type == anyTypeName) { + return true + } + + if (type.namespaceURI != fhirModelNamespaceUri) { + // FHIR model types only extend System.Any or other FHIR model types + return false + } + + val valueTypeClass = resolveType(valueType) ?: return null + val typeClass = resolveType(type.localPart) ?: return null + + return typeClass.isAssignableFrom(valueTypeClass) + } + + override fun objectEquivalent( + left: ClassInstance, + right: ClassInstance, + equivalent: (l: Value?, r: Value?) -> Boolean, + ): Boolean { + // "id" elements are excluded from equivalence checking for instances of FHIR.Resource and + // FHIR.Element (see https://hl7.org/fhir/fhirpath.html#changes) + if ( + `is`(left.type.localPart, QName(fhirModelNamespaceUri, "Resource")) == true || + `is`(left.type.localPart, QName(fhirModelNamespaceUri, "Element")) == true + ) { + return EquivalentEvaluator.structuredValueElementsEquivalent( + left.elements.filterKeys { it != "id" }, + right.elements.filterKeys { it != "id" }, + equivalent, + ) + } + + return EquivalentEvaluator.structuredValueElementsEquivalent( + left.elements, + right.elements, + equivalent, + ) + } + + override fun createInstance(typeName: String?): Value { + return toCqlValue(createHapiInstance(typeName!!), true)!! + } + + /** The package names of Java objects supported by this model */ + open var packageNames = mutableListOf() + + /** + * Resolve the Java class that corresponds to the given model type. + * + * @param typeName E.g. "Patient" + * @return The Java class that corresponds to the given model type, e.g. + * `org.hl7.fhir.r4.model.Patient`. + */ + /** + * Resolution is deterministic for a given type name, and a miss is expensive: the lookups below + * fall through to a `Class.forName` per configured package -- twice -- each throwing and + * discarding a `ClassNotFoundException`, and then to a scan of every registered resource. The + * set of type names a model produces is small and closed, so the answers are cached. + * + * Negative results are cached too. They cost the most to compute and recur just as often. + * + * Read-then-write rather than `computeIfAbsent`: the result does not depend on what else is in + * the map, so a racing duplicate computation is harmless, and this cannot deadlock if a + * resolution path ever re-enters this method. + */ + open fun resolveType(typeName: String?): Class<*>? { + if (typeName == null) { + return resolveTypeUncached(null) + } + // A present entry is authoritative even when it holds null: a name that resolved to nothing + // must not be recomputed, or negative results would never actually be cached. + val cached = resolvedTypes[typeName] + return if (cached != null) cached.orElse(null) + else + resolveTypeUncached(typeName).also { resolvedTypes[typeName] = Optional.ofNullable(it) } + } + + private fun resolveTypeUncached(typeName: String?): Class<*>? { + // For Dstu2 + var typeName = typeName + if (typeName!!.startsWith("FHIR.")) { + typeName = typeName.replace("FHIR.", "") + } + // dataTypes + val definition = this.fhirContext.getElementDefinition(typeName) + if (definition != null) { + return definition.getImplementingClass() + } + + try { + // Resources + return this.fhirContext.getResourceDefinition(typeName).implementingClass + } catch (_: Exception) {} + + try { + if (typeName.contains(".")) { + val path = typeName.split(".") + val resourceDefinition = + if (this.fhirContext.resourceTypes.contains(path[0])) + this.fhirContext.getResourceDefinition(path[0]) + else this.fhirContext.getElementDefinition(path[0]) + var childName = path[1][0].lowercaseChar().toString() + path[1].substring(1) + var childDefinition = + resourceDefinition!!.getChildByName(childName) + ?: return resolveChildren(resourceDefinition.children, childName) + var childElement = childDefinition.getChildByName(childName) + for (i in 2.., + childName: String, + ): Class<*>? { + for (c in children) { + if (c.validChildNames.contains(childName)) { + return c.getChildByName(childName).getImplementingClass() + } + if (c is RuntimeChildResourceBlockDefinition) { + for (childrenName in c.validChildNames) { + if (c.elementName == childrenName) continue + + @Suppress("UNCHECKED_CAST") + val nextChildren = + c.getChildByName(childrenName).getChildren() + as List + resolveChildren(nextChildren, childName) + } + } + } + return null + } + + // Resolutions + protected fun resolveRuntimeDefinition(base: IBase): BaseRuntimeElementCompositeDefinition<*> { + when (base) { + is IAnyResource -> { + return this.fhirContext.getResourceDefinition(base) + } + + is IBaseBackboneElement, + is IBaseElement -> { + return (this.fhirContext.getElementDefinition(base.javaClass) + as BaseRuntimeElementCompositeDefinition<*>?)!! + } + + is ICompositeType -> { + @Suppress("UNCHECKED_CAST") + return this.fhirContext.getElementDefinition(base.javaClass) + as BaseRuntimeElementCompositeDefinition + } + + else -> + throw UnknownType( + "Unable to resolve the runtime definition for ${base.javaClass.name}" + ) + } + } + + private fun deepSearch(typeName: String): Class<*>? { + // Special case for "Codes". This suffix is often removed from the HAPI type. + val codelessName = typeName.replace("Codes", "").lowercase() + val lowerName = typeName.lowercase() + + val elements = this.fhirContext.elementDefinitions + for (element in elements) { + val innerClasses = element.getImplementingClass().getDeclaredClasses() + for (clazz in innerClasses) { + val clazzLowerName = clazz.getSimpleName().lowercase() + if (clazzLowerName == lowerName || clazzLowerName == codelessName) { + return clazz + } + } + } + + return null + } + + // Creators + + /** + * Creates an instance of the Java class that corresponds to the given model type. + * + * @param typeName E.g. "Patient" + * @return An instance of the HAPI FHIR class like `org.hl7.fhir.r4.model.Patient`. + */ + fun createHapiInstance(typeName: String): Any { + val clazz = + this.resolveType(typeName) ?: throw UnknownType("Could not resolve type $typeName") + return createHapiInstance(clazz) + } + + protected fun createHapiInstance(clazz: Class<*>): Any { + try { + if (clazz.isEnum) { + val factoryClass = this.resolveType(clazz.getName() + "EnumFactory") + + @Suppress("UNCHECKED_CAST") + val factory = this.createHapiInstance(factoryClass!!) as EnumFactoryType + return this.enumConstructor(factory) + } + + return clazz.getDeclaredConstructor().newInstance() + } catch (e: NoSuchMethodException) { + throw UnknownType( + "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}" + ) + } catch (e: InvocationTargetException) { + throw UnknownType( + "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}" + ) + } catch (e: InstantiationException) { + throw UnknownType( + "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}" + ) + } catch (e: IllegalAccessException) { + throw UnknownType( + "Could not create an instance of class ${clazz.name}.\nRoot cause: ${e.message}" + ) + } + } + + protected fun toTime(value: TimeType): Time { + return Time(timeToString(value)) + } + + // Transformations + protected fun toDateTime( + value: BaseDateTimeType, + calendarConstant: Int = this.getCalendarConstant(value), + ): DateTime { + val calendar = this.getCalendar(value) + + // TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() : + // calendar.getTimeZone(); + // ZoneOffset zoneOffset = + // tz.toZoneId().getRules().getStandardOffset(calendar.toInstant()); + val zoneOffset = (calendar as GregorianCalendar).toZonedDateTime().offset + when (calendarConstant) { + Calendar.YEAR -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + ) + Calendar.MONTH -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + ) + + Calendar.DAY_OF_MONTH -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + ) + + Calendar.HOUR_OF_DAY -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + ) + + Calendar.MINUTE -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + ) + + Calendar.SECOND -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + ) + + Calendar.MILLISECOND -> + return DateTime( + TemporalHelper.zoneToOffset(zoneOffset), + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + calendar.get(Calendar.HOUR_OF_DAY), + calendar.get(Calendar.MINUTE), + calendar.get(Calendar.SECOND), + calendar.get(Calendar.MILLISECOND), + ) + + else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant") + } + } + + protected fun toDate( + value: BaseDateTimeType, + calendarConstant: Int = this.getCalendarConstant(value), + ): Date { + val calendar = this.getCalendar(value) + // TimeZone tz = calendar.getTimeZone() == null ? TimeZone.getDefault() : + // calendar.getTimeZone(); + // ZoneOffset zoneOffset = + // tz.toZoneId().getRules().getStandardOffset(calendar.toInstant()); + return when (calendarConstant) { + Calendar.YEAR -> Date(calendar.get(Calendar.YEAR)) + Calendar.MONTH -> Date(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1) + + Calendar.DAY_OF_MONTH -> + Date( + calendar.get(Calendar.YEAR), + calendar.get(Calendar.MONTH) + 1, + calendar.get(Calendar.DAY_OF_MONTH), + ) + + else -> throw InvalidPrecision("Invalid temporal precision $calendarConstant") + } + } + + fun setBaseValue(value: Any?, target: IBase?): IBase? { + if (target is IPrimitiveType<*>) { + setPrimitiveValue(value, target) + } + return value as IBase? + } + + fun setPrimitiveValue(value: Any?, target: IPrimitiveType<*>) { + val simpleName = target.javaClass.getSimpleName() + when (simpleName) { + "DateTimeType", + "InstantType" -> { + // Ensure offset is taken into account from the ISO datetime String instead of the + // default timezone + target.valueAsString = (value as DateTime).toDateString() + + @Suppress("UNCHECKED_CAST") + setCalendarConstant(target as BaseDateTimeType, value as BaseTemporal) + } + "DateType" -> { + val targetValue = (value as Date).toJavaDate() + + @Suppress("UNCHECKED_CAST") + target as BaseDateTimeType + target.value = targetValue + setCalendarConstant(target, value as BaseTemporal) + } + + "TimeType" -> target.asIPrimitive().value = value.toString() + "Base64BinaryType" -> target.valueAsString = value as String? + else -> target.asIPrimitive().value = value + } + } + + private fun Any?.asIPrimitive(): IPrimitiveType { + @Suppress("UNCHECKED_CAST") + return this as IPrimitiveType + } + + fun toTemporalPrecisionEnum(precision: Precision): TemporalPrecisionEnum { + return when (precision) { + Precision.YEAR -> TemporalPrecisionEnum.YEAR + Precision.MONTH -> TemporalPrecisionEnum.MONTH + Precision.DAY -> TemporalPrecisionEnum.DAY + Precision.HOUR, + Precision.MINUTE -> TemporalPrecisionEnum.MINUTE + Precision.SECOND -> TemporalPrecisionEnum.SECOND + Precision.MILLISECOND -> TemporalPrecisionEnum.MILLI + else -> throw IllegalArgumentException("Unknown precision $precision") + } + } + + /* + * // 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; } } + */ + fun toSimpleCqlType(primitiveType: IPrimitiveType<*>): Value? { + val value = primitiveType.value + + if (value == null) { + return null + } + + val simpleName = primitiveType.javaClass.getSimpleName() + @Suppress("UNCHECKED_CAST") + return when (simpleName) { + "InstantType", + "DateTimeType" -> toDateTime(primitiveType as BaseDateTimeType) + "DateType" -> toDate(primitiveType as BaseDateTimeType) + "TimeType" -> toTime(primitiveType as TimeType) + "IdType" -> this.idToString(primitiveType as IdType).toCqlString() + "Base64BinaryType" -> primitiveType.valueAsString?.toCqlString() + else -> + when (value) { + is kotlin.Boolean -> value.toCqlBoolean() + is kotlin.Int -> value.toCqlInteger() + is kotlin.Long -> value.toCqlLong() + is java.math.BigDecimal -> value.toCqlDecimal() + is kotlin.String -> value.toCqlString() + else -> + throw IllegalArgumentException( + "Unable to convert a value of type ${value.javaClass.name} to a CQL simple type." + ) + } + } + } + + /** + * Recursively converts a HAPI FHIR construct to a CQL-native equivalent. + * + * @param target The HAPI FHIR object to convert + * @param expandPrimitivesAndEnumerationsWithNoValues Whether to convert a HAPI FHIR + * primitive/enumeration with no value to a structured type instance with a null `value` + * child, or to null. + */ + fun toCqlValue( + target: Any?, + expandPrimitivesAndEnumerationsWithNoValues: kotlin.Boolean = false, + ): ClassInstance? { + if (target == null) { + return null + } + + if (target !is IBase) { + throw IllegalArgumentException( + "Unable to convert an instance of ${target.javaClass.name} to a CQL value. Expected an instance of IBase." + ) + } + + if (this.enumChecker(target)) { + @Suppress("UNCHECKED_CAST") + target as EnumerationType + + val elements = primitiveElements(target) + + // If the instance is a primitive (including or even especially an enumeration), and it + // has no value, return null + if ( + !expandPrimitivesAndEnumerationsWithNoValues && + !target.hasValue() && + elements.all { it.value == null } + ) { + return null + } + + // For FHIR enumerations, use the type of the backing Enum + val factoryName = this.enumFactoryTypeGetter(target).simpleName + val typeName = factoryName.substringBefore("EnumFactory") + + elements["value"] = target.valueAsString?.toCqlString() + + return ClassInstance(QName(fhirModelNamespaceUri, typeName, fhirModelId), elements) + } + + if (target is IPrimitiveType<*>) { + val elements = primitiveElements(target) + + // If the instance is a primitive (including or even especially an enumeration), and it + // has no value, return null + if ( + !expandPrimitivesAndEnumerationsWithNoValues && + !target.hasValue() && + elements.all { it.value == null } + ) { + return null + } + + val elementDefinition = this.fhirContext.getElementDefinition(target.javaClass) + + elements["value"] = toSimpleCqlType(target) + + return ClassInstance( + QName(fhirModelNamespaceUri, elementDefinition.name, fhirModelId), + elements, + ) + } + + // Composite definitions include id, extension and modifierExtension (where applicable) as + // children, so they're converted here along with the rest of the children. + val definition = resolveRuntimeDefinition(target) + val elements = mutableMapOf() + + for (child in definition.children) { + elements[child.elementName] = + child.accessor + .getValues(target) + .map { toCqlValue(it) } + .let { + if (child.max == 1) { + it.firstOrNull() + } else { + if (it.isEmpty()) null else it.toCqlList() + } + } + } + + return ClassInstance(QName(fhirModelNamespaceUri, definition.name, fhirModelId), elements) + } + + /** + * The id and extension elements of a FHIR primitive. Like all FHIR types, primitives may have + * an id and extensions, with or without a value. + */ + private fun primitiveElements(target: IBase): MutableMap { + val elements = mutableMapOf() + + if (target is IBaseHasExtensions) { + val extensionsAsCqlValues = target.extension.map { toCqlValue(it) } + elements["extension"] = + if (extensionsAsCqlValues.isEmpty()) null else extensionsAsCqlValues.toCqlList() + } + + if (target is IBaseElement) { + elements["id"] = target.id?.toCqlString() + } + + return elements + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R4FhirModelResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R4FhirModelResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..f55a4c2922a4963e4536082ec95847f0b366808c --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R4FhirModelResolver.kt @@ -0,0 +1,169 @@ +package org.opencds.cqf.cql.engine.fhir.model + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import java.util.* +import org.hl7.fhir.instance.model.api.IBaseResource +import org.hl7.fhir.r4.model.AnnotatedUuidType +import org.hl7.fhir.r4.model.Base +import org.hl7.fhir.r4.model.BaseDateTimeType +import org.hl7.fhir.r4.model.EnumFactory +import org.hl7.fhir.r4.model.Enumeration +import org.hl7.fhir.r4.model.Enumerations +import org.hl7.fhir.r4.model.IdType +import org.hl7.fhir.r4.model.Resource +import org.hl7.fhir.r4.model.SimpleQuantity +import org.hl7.fhir.r4.model.TimeType +import org.opencds.cqf.cql.engine.runtime.BaseTemporal + +open class R4FhirModelResolver(fhirContext: FhirContext) : + FhirModelResolver< + Base, + BaseDateTimeType, + TimeType, + SimpleQuantity, + IdType, + Resource, + Enumeration<*>, + EnumFactory<*>, + >(fhirContext) { + constructor() : this(FhirContext.forR4()) + + init { + this.packageNames = mutableListOf("org.hl7.fhir.r4.model") + require(fhirContext.version.version == FhirVersionEnum.R4) { + "The supplied context is not configured for R4" + } + } + + override fun initialize() { + // HAPI has some bugs where it's missing annotations on certain types. This patches that. + this.fhirContext.registerCustomType(AnnotatedUuidType::class.java) + + // The context loads Resources on demand which can cause resolution to fail in certain cases + // This forces all Resource types to be loaded. + + // force calling of validateInitialized(); + this.fhirContext.getResourceDefinition(Enumerations.ResourceType.ACCOUNT.toCode()) + + val myNameToResourceType: MutableMap> + try { + val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType") + f.setAccessible(true) + + // This is magic reflection to handle the fact that we need to manually + // initialize this map, but it's a private field with no accessor. + @Suppress("UNCHECKED_CAST") + myNameToResourceType = + f.get(this.fhirContext) as MutableMap> + + val toLoad: MutableList> = + ArrayList>(myNameToResourceType.size) + + for (type in Enumerations.ResourceType.entries) { + // These are abstract types that should never be resolved directly. + when (type) { + Enumerations.ResourceType.DOMAINRESOURCE, + Enumerations.ResourceType.RESOURCE, + Enumerations.ResourceType.NULL -> continue + else -> {} + } + if (myNameToResourceType.containsKey(type.toCode().lowercase(Locale.getDefault()))) + toLoad.add(myNameToResourceType[type.toCode().lowercase()]!!) + } + + // Sends a list of all classes to be loaded in bulk. + val m = + this.fhirContext.javaClass.getDeclaredMethod( + "scanResourceTypes", + MutableCollection::class.java, + ) + m.setAccessible(true) + m.invoke(this.fhirContext, toLoad) + } catch (_: Exception) { + // intentionally ignored + } + } + + override fun castToSimpleQuantity(base: Base): SimpleQuantity { + return base.castToSimpleQuantity(base) + } + + override fun getCalendar(dateTime: BaseDateTimeType): Calendar { + return dateTime.valueAsCalendar + } + + override fun getCalendarConstant(dateTime: BaseDateTimeType): Int { + return dateTime.precision.calendarConstant + } + + override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) { + target.precision = toTemporalPrecisionEnum(value.precision!!) + } + + override fun timeToString(time: TimeType): String { + return time.value + } + + override fun idToString(id: IdType): String { + return id.idPart + } + + override fun getResourceType(resource: Resource): String { + return resource.fhirType() + } + + override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> { + return Enumeration(factory) + } + + override fun enumChecker(`object`: Any): Boolean { + return `object` is Enumeration<*> + } + + override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> { + return enumeration.getEnumFactory().javaClass + } + + override fun resolveType(typeName: String?): Class<*>? { + // TODO: Might be able to patch some of these by registering custom types in HAPI. + + var typeName = typeName + when (typeName) { + "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality" + "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus" + "EventStatus" -> typeName = $$"Procedure$ProcedureStatus" + "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus" + "SampledDataDataType" -> typeName = "StringType" + "ClaimProcessingCodes" -> typeName = $$"ClaimResponse$RemittanceOutcome" + "vConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality" + "ContractResourcePublicationStatusCodes" -> + typeName = $$"Contract$ContractPublicationStatus" + "CurrencyCode" -> typeName = "CodeType" + "Messageheader_Response_Request" -> + typeName = $$"MessageDefinition$MessageheaderResponseRequest" + "MimeType" -> typeName = "CodeType" + else -> {} + } + + return super.resolveType(typeName) + } + + override fun getContextPath(contextType: String?, targetType: String?): String? { + if (targetType == null || contextType == null) { + return null + } + + if ("Patient" == contextType) { + when (targetType) { + "MedicationStatement", + "QuestionnaireResponse" -> return "subject" + "Task" -> return "for" + "Coverage" -> return "beneficiary" + else -> {} + } + } + + return super.getContextPath(contextType, targetType) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R5FhirModelResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R5FhirModelResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..1d5aa351f3219f0882325666fae7a53fb30fe53b --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/model/R5FhirModelResolver.kt @@ -0,0 +1,187 @@ +package org.opencds.cqf.cql.engine.fhir.model + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import java.util.* +import org.hl7.fhir.exceptions.FHIRException +import org.hl7.fhir.instance.model.api.IBaseResource +import org.hl7.fhir.r5.model.Base +import org.hl7.fhir.r5.model.BaseDateTimeType +import org.hl7.fhir.r5.model.EnumFactory +import org.hl7.fhir.r5.model.Enumeration +import org.hl7.fhir.r5.model.Enumerations.FHIRTypes +import org.hl7.fhir.r5.model.IdType +import org.hl7.fhir.r5.model.Quantity +import org.hl7.fhir.r5.model.Resource +import org.hl7.fhir.r5.model.SimpleQuantity +import org.hl7.fhir.r5.model.TimeType +import org.opencds.cqf.cql.engine.runtime.BaseTemporal + +open class R5FhirModelResolver(fhirContext: FhirContext) : + FhirModelResolver< + Base, + BaseDateTimeType, + TimeType, + SimpleQuantity, + IdType, + Resource, + Enumeration<*>, + EnumFactory<*>, + >(fhirContext) { + constructor() : this(FhirContext.forR5()) + + init { + this.packageNames = mutableListOf("org.hl7.fhir.r5.model") + require(fhirContext.version.version == FhirVersionEnum.R5) { + "The supplied context is not configured for R5" + } + } + + override fun initialize() { + // The context loads Resources on demand which can cause resolution to fail in + // certain cases + // This forces all Resource types to be loaded. + + // force calling of validateInitialized(); + + this.fhirContext.getResourceDefinition(FHIRTypes.ACCOUNT.toCode()) + + val myNameToResourceType: MutableMap> + try { + val f = this.fhirContext.javaClass.getDeclaredField("myNameToResourceType") + f.setAccessible(true) + + // This is magic reflection to handle the fact that we need to manually + // initialize this map, but it's a private field with no accessor. + @Suppress("UNCHECKED_CAST") + myNameToResourceType = + f.get(this.fhirContext) as MutableMap> + + val toLoad = ArrayList?>(myNameToResourceType.size) + + for (type in FHIRTypes.entries) { + // These are abstract types that should never be resolved directly. + when (type) { + FHIRTypes.DOMAINRESOURCE, + FHIRTypes.RESOURCE, + FHIRTypes.NULL -> continue + else -> {} + } + if (myNameToResourceType.containsKey(type.toCode().lowercase(Locale.getDefault()))) + toLoad.add(myNameToResourceType[type.toCode().lowercase(Locale.getDefault())]) + } + + // Sends a list of all classes to be loaded in bulk. + val m = + this.fhirContext.javaClass.getDeclaredMethod( + "scanResourceTypes", + MutableCollection::class.java, + ) + m.setAccessible(true) + m.invoke(this.fhirContext, toLoad) + } catch (_: Exception) { + // intentionally ignored + } + } + + override fun castToSimpleQuantity(base: Base): SimpleQuantity { + when (base) { + is SimpleQuantity -> return base + is Quantity -> { + val sq = SimpleQuantity() + sq.valueElement = base.valueElement + sq.comparatorElement = base.comparatorElement + sq.unitElement = base.unitElement + sq.systemElement = base.systemElement + sq.codeElement = base.codeElement + return sq + } + + else -> + throw FHIRException( + "Unable to convert a " + base.javaClass.getName() + " to an SimpleQuantity" + ) + } + } + + override fun getCalendar(dateTime: BaseDateTimeType): Calendar { + return dateTime.valueAsCalendar + } + + override fun getCalendarConstant(dateTime: BaseDateTimeType): Int { + return dateTime.precision.calendarConstant + } + + override fun setCalendarConstant(target: BaseDateTimeType, value: BaseTemporal) { + target.precision = toTemporalPrecisionEnum(value.precision!!) + } + + override fun timeToString(time: TimeType): String { + return time.value + } + + override fun idToString(id: IdType): String { + return id.idPart + } + + override fun getResourceType(resource: Resource): String { + return resource.fhirType() + } + + override fun enumConstructor(factory: EnumFactory<*>): Enumeration<*> { + return Enumeration(factory) + } + + override fun enumChecker(`object`: Any): Boolean { + return `object` is Enumeration<*> + } + + override fun enumFactoryTypeGetter(enumeration: Enumeration<*>): Class<*> { + return enumeration.getEnumFactory().javaClass + } + + override fun resolveType(typeName: String?): Class<*>? { + // TODO: Might be able to patch some of these by registering custom types in + // HAPI. + + var typeName = typeName + when (typeName) { + "ConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality" + "ContractResourceStatusCodes" -> typeName = $$"Contract$ContractStatus" + "EventStatus" -> typeName = $$"Procedure$ProcedureStatus" + "FinancialResourceStatusCodes" -> typeName = $$"ClaimResponse$ClaimResponseStatus" + "SampledDataDataType" -> typeName = "StringType" + "ClaimProcessingCodes" -> typeName = $$"ClaimResponse$RemittanceOutcome" + "vConfidentialityClassification" -> typeName = $$"Composition$DocumentConfidentiality" + "ContractResourcePublicationStatusCodes" -> + typeName = $$"Contract$ContractPublicationStatus" + "CurrencyCode" -> typeName = "CodeType" + "MedicationAdministrationStatus" -> typeName = "CodeType" + "MedicationDispenseStatus" -> typeName = "CodeType" + "MedicationKnowledgeStatus" -> typeName = "CodeType" + "Messageheader_Response_Request" -> typeName = "CodeType" + "MimeType" -> typeName = "CodeType" + else -> {} + } + + return super.resolveType(typeName) + } + + override fun getContextPath(contextType: String?, targetType: String?): String? { + if (targetType == null || contextType == null) { + return null + } + + if ("Patient" == contextType) { + when (targetType) { + "MedicationStatement", + "QuestionnaireResponse" -> return "subject" + "Task" -> return "for" + "Coverage" -> return "beneficiary" + else -> {} + } + } + + return super.getContextPath(contextType, targetType) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/BaseFhirQueryGenerator.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/BaseFhirQueryGenerator.kt new file mode 100644 index 0000000000000000000000000000000000000000..2516837f587c6c88da199725f06d8119a82cf2a8 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/BaseFhirQueryGenerator.kt @@ -0,0 +1,460 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import ca.uhn.fhir.model.api.IQueryParameterType +import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum +import ca.uhn.fhir.rest.param.DateParam +import ca.uhn.fhir.rest.param.DateRangeParam +import ca.uhn.fhir.rest.param.ParamPrefixEnum +import ca.uhn.fhir.rest.param.TokenOrListParam +import ca.uhn.fhir.rest.param.TokenParam +import ca.uhn.fhir.rest.param.TokenParamModifier +import java.util.* +import org.apache.commons.lang3.tuple.Pair +import org.hl7.fhir.instance.model.api.IBaseConformance +import org.hl7.fhir.instance.model.api.ICompositeType +import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver +import org.opencds.cqf.cql.engine.model.ModelResolver +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider +import org.opencds.cqf.cql.engine.terminology.ValueSetInfo + +abstract class BaseFhirQueryGenerator +protected constructor( + protected var searchParameterResolver: SearchParameterResolver, + protected var terminologyProvider: TerminologyProvider?, + protected var modelResolver: ModelResolver, + fhirContext: FhirContext, +) : FhirVersionIntegrityChecker { + protected var fhirContext: FhirContext + + var pageSize: Int? = null + set(value) { + require(value != null && value > 0) { "value must be a non-null integer > 0" } + field = value + } + + var maxCodesPerQuery: Int? = null + set(value) { + require(value != null && value > 0) { "value must be non-null integer > 0" } + field = value + } + + var queryBatchThreshold: Int? = null + set(value) { + require(value != null && value > 0) { "value must be non-null integer > 0" } + field = value + } + + // TODO: Think about how to best handle the decision to expand value sets... Should it be part + // of the + // terminology provider if it detects support for "code:in"? How does that feed back to the + // retriever? + var isExpandValueSets: Boolean = false + + init { + this.isExpandValueSets = DEFAULT_SHOULD_EXPAND_VALUESETS + + this.fhirContext = fhirContext + validateFhirVersionIntegrity(fetchFhirVersionEnum(this.fhirContext)) + } + + @Throws(FhirVersionMisMatchException::class) + override fun validateFhirVersionIntegrity(fhirVersion: FhirVersionEnum) { + require(fetchFhirVersionEnum(this.searchParameterResolver.fhirContext) == fhirVersion) + } + + fun fetchFhirVersionEnum(fhirContext: FhirContext): FhirVersionEnum { + return fhirContext.version.version + } + + abstract fun generateFhirQueries( + dataRequirement: ICompositeType?, + evaluationDateTime: DateTime?, + contextValues: MutableMap?, + parameters: MutableMap?, + capabilityStatement: IBaseConformance?, + ): MutableList + + protected fun getTemplateParam( + dataType: String?, + templateId: String?, + ): Pair? { + if (templateId == null || templateId == "") { + return null + } + + // Do something? + return null + } + + fun getDateRangeParam( + dataType: String?, + datePath: String?, + dateLowPath: String?, + dateHighPath: String?, + dateRange: Interval?, + ): Pair? { + if (dateRange == null) { + return null + } + + var low: DateParam? = null + var high: DateParam? = null + if (dateRange.low != null) { + if (dateRange.low is Date) { + low = + DateParam( + ParamPrefixEnum.GREATERTHAN_OR_EQUALS, + Date.from((dateRange.low as Date).toInstant()), + ) + } else if (dateRange.low is DateTime) { + low = + DateParam( + ParamPrefixEnum.GREATERTHAN_OR_EQUALS, + Date.from((dateRange.low as DateTime).dateTime!!.toInstant()), + ) + } + } + + if (dateRange.high != null) { + if (dateRange.low is Date) { + high = + DateParam( + ParamPrefixEnum.LESSTHAN_OR_EQUALS, + Date.from((dateRange.high as Date).toInstant()), + ) + } else if (dateRange.low is DateTime) { + high = + DateParam( + ParamPrefixEnum.LESSTHAN_OR_EQUALS, + Date.from((dateRange.high as DateTime).dateTime!!.toInstant()), + ) + } + } + val rangeParam = + if (high == null && low != null) { + DateRangeParam(low) + } else { + DateRangeParam(low, high) + } + + val dateParam = + this.searchParameterResolver.getSearchParameterDefinition( + dataType, + datePath, + RestSearchParameterTypeEnum.DATE, + ) + + if (dateParam == null) { + throw UnsupportedOperationException( + "Could not resolve a search parameter with date type for $dataType.$datePath " + ) + } + + return Pair.of(dateParam.name, rangeParam) + } + + protected fun getContextParam( + dataType: String?, + context: String?, + contextPath: String?, + contextValue: String?, + ): Pair? { + if ( + context != null && context == "Patient" && contextValue != null && contextPath != null + ) { + return this.searchParameterResolver.createSearchParameter( + context, + dataType, + contextPath, + contextValue, + ) + } + + return null + } + + protected fun getCodeParams( + dataType: String?, + codePath: String?, + codes: Iterable?, + valueSet: String?, + ): Pair>? { + var valueSet = valueSet + if (valueSet != null && valueSet.startsWith("urn:oid:")) { + valueSet = valueSet.replace("urn:oid:", "") + } + + require(!(codePath == null && (codes != null || valueSet != null))) { + "A code path must be provided when filtering on codes or a valueset." + } + + if (codePath == null || codePath.isEmpty()) { + return null + } + + // TODO: This assumes the code path will always be a token param. + val codeParamLists = this.getCodeParams(codes, valueSet) + if (codeParamLists.isEmpty()) { + return null + } + + val codeParam = + this.searchParameterResolver.getSearchParameterDefinition( + dataType, + codePath, + RestSearchParameterTypeEnum.TOKEN, + ) + + if (codeParam == null) { + return null + } + + return Pair.of>(codeParam.name, codeParamLists) + } + + // The code params will be either the literal set of codes in the event the data server doesn't + // have the referenced + // ValueSet (or doesn't support pulling and caching a ValueSet). If the target server DOES + // support that then it's + // "dataType.codePath in ValueSet" + protected fun getCodeParams( + codes: Iterable?, + valueSet: String?, + ): MutableList { + var codes = codes + if (valueSet != null) { + if (!this.isExpandValueSets) { + return mutableListOf( + TokenOrListParam() + .addOr(TokenParam(valueSet).setModifier(TokenParamModifier.IN)) + ) + } else { + requireNotNull(terminologyProvider) { + "Expand value sets cannot be used without a terminology provider and no terminology provider is set." + } + val valueSetInfo = ValueSetInfo().withId(valueSet) + codes = terminologyProvider!!.expand(valueSetInfo) + } + } + + if (codes == null) { + return mutableListOf() + } + + // If the number of queries generated as a result of the code list size and maxCodesPerQuery + // constraint would + // result in a number of queries that is greater than the queryBatchThreshold value, then + // codeParams will + // be omitted altogether. + if (this.maxCodesPerQuery != null && this.queryBatchThreshold != null) { + if ( + (getIterableSize(codes) / this.maxCodesPerQuery!!.toFloat()) > + this.queryBatchThreshold!! + ) { + return mutableListOf() + } + } + + val codeParamsList: MutableList = mutableListOf() + var codeParams: TokenOrListParam? = null + var codeCount = 0 + for (code in codes) { + if (this.maxCodesPerQuery == null) { + if (codeCount == 0 && codeParams == null) { + codeParams = TokenOrListParam() + } + } else if (codeCount % this.maxCodesPerQuery!! == 0) { + if (codeParams != null) { + codeParamsList.add(codeParams) + } + + codeParams = TokenOrListParam() + } + + codeCount++ + if (code != null) { + codeParams!!.addOr(TokenParam(code.system, code.code)) + } + } + + if (codeParams != null) { + codeParamsList.add(codeParams) + } + + return codeParamsList + } + + protected fun setupQueries( + context: String?, + contextPath: String?, + contextValue: String?, + dataType: String?, + templateId: String?, + codeFilters: MutableList?, + dateFilters: MutableList?, + ): MutableList { + val templateParam = this.getTemplateParam(dataType, templateId) + + val contextParam = this.getContextParam(dataType, context, contextPath, contextValue) + + val dateRangeParams: MutableList> = mutableListOf() + if (dateFilters != null) { + for (df in dateFilters) { + val dateRangeParam = + this.getDateRangeParam( + dataType, + df.datePath, + df.dateLowPath, + df.dateHighPath, + df.dateRange, + ) + if (dateRangeParam != null) { + dateRangeParams.add(dateRangeParam) + } + } + } + + val codeParamList: MutableList>> = + ArrayList>>() + if (codeFilters != null) { + for (cf in codeFilters) { + val codeParams = this.getCodeParams(dataType, cf.codePath, cf.codes, cf.valueSet) + + if (codeParams != null) { + codeParamList.add(codeParams) + } + } + } + + return this.innerSetupQueries(templateParam, contextParam, dateRangeParams, codeParamList) + } + + fun setupQueries( + context: String?, + contextPath: String?, + contextValue: String?, + dataType: String?, + templateId: String?, + codePath: String?, + codes: Iterable?, + valueSet: String?, + datePath: String?, + dateLowPath: String?, + dateHighPath: String?, + dateRange: Interval?, + ): MutableList { + return setupQueries( + context, + contextPath, + contextValue, + dataType, + templateId, + if (codePath != null) mutableListOf(CodeFilter(codePath, codes, valueSet)) else null, + if (datePath != null || dateLowPath != null || dateHighPath != null) + mutableListOf(DateFilter(datePath, dateLowPath, dateHighPath, dateRange)) + else null, + ) + } + + protected fun innerSetupQueries( + templateParam: Pair?, + contextParam: Pair?, + dateRangeParams: MutableList>?, + codeParams: MutableList>>?, + ): MutableList { + if (codeParams == null || codeParams.isEmpty()) { + return mutableListOf( + this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams) + ) + } + + var chunkedCodeParam: Pair>? = null + for (cp in codeParams) { + if (cp.value != null && cp.value!!.size > 1) { + require(chunkedCodeParam == null) { + "Cannot evaluate multiple chunked code filters on ${chunkedCodeParam!!.key} and ${cp.key}" + } + chunkedCodeParam = cp + } + } + + if (chunkedCodeParam == null) { + return mutableListOf( + this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams) + ) + } + + val maps: MutableList = mutableListOf() + for (t in chunkedCodeParam.value!!) { + val base = this.getBaseMap(templateParam, contextParam, dateRangeParams, codeParams) + base.add(chunkedCodeParam.key!!, t) + maps.add(base) + } + + return maps + } + + fun getBaseMap( + templateParam: Pair?, + contextParam: Pair?, + dateRangeParams: MutableList>?, + codeParams: MutableList>>?, + ): SearchParameterMap { + val baseMap = SearchParameterMap() + baseMap.lastUpdated = DateRangeParam() + + if (this.pageSize != null) { + baseMap.count = pageSize + } + + if (templateParam != null) { + baseMap.add(templateParam.key!!, templateParam.value) + } + + if (dateRangeParams != null) { + for (drp in dateRangeParams) { + baseMap.add(drp.key!!, drp.value) + } + } + + if (codeParams != null) { + for (cp in codeParams) { + if (cp.value == null || cp.value!!.isEmpty() || cp.value!!.size > 1) { + // NOTE: Ignores "chunked" code parameters so they don't have to be removed + continue + } + baseMap.add(cp.key!!, cp.value!![0]) + } + } + + if (contextParam != null) { + baseMap.add(contextParam.key!!, contextParam.value) + } + + return baseMap + } + + companion object { + protected const val DEFAULT_SHOULD_EXPAND_VALUESETS: Boolean = false + + private fun getIterableSize(iterable: Iterable<*>): Int { + if (iterable is MutableCollection<*>) { + return iterable.size + } + + var counter = 0 + for (i in iterable) { + counter++ + } + return counter + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/CodeFilter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/CodeFilter.kt new file mode 100644 index 0000000000000000000000000000000000000000..3be3ba514e27b071131938330256e4bd76a0c014 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/CodeFilter.kt @@ -0,0 +1,9 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import org.opencds.cqf.cql.engine.runtime.Code + +class CodeFilter( + @JvmField val codePath: String?, + @JvmField val codes: Iterable?, + @JvmField val valueSet: String?, +) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/DateFilter.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/DateFilter.kt new file mode 100644 index 0000000000000000000000000000000000000000..63328ae97c7232a6a8d4fbb06e7e3afb3eef6c03 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/DateFilter.kt @@ -0,0 +1,10 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import org.opencds.cqf.cql.engine.runtime.Interval + +class DateFilter( + @JvmField val datePath: String?, + @JvmField val dateLowPath: String?, + @JvmField val dateHighPath: String?, + @JvmField val dateRange: Interval?, +) diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/Dstu3FhirQueryGenerator.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/Dstu3FhirQueryGenerator.kt new file mode 100644 index 0000000000000000000000000000000000000000..ab06f766b2164911d63a4e3f52db64430e6a74b3 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/Dstu3FhirQueryGenerator.kt @@ -0,0 +1,215 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirVersionEnum +import java.net.URLDecoder +import java.time.OffsetDateTime +import org.hl7.fhir.dstu3.model.CapabilityStatement +import org.hl7.fhir.dstu3.model.DataRequirement +import org.hl7.fhir.dstu3.model.DateTimeType +import org.hl7.fhir.dstu3.model.Duration +import org.hl7.fhir.dstu3.model.Period +import org.hl7.fhir.dstu3.model.Reference +import org.hl7.fhir.instance.model.api.IBaseConformance +import org.hl7.fhir.instance.model.api.ICompositeType +import org.opencds.cqf.cql.engine.elm.executing.SubtractEvaluator +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver +import org.opencds.cqf.cql.engine.model.ModelResolver +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider + +class Dstu3FhirQueryGenerator( + searchParameterResolver: SearchParameterResolver, + terminologyProvider: TerminologyProvider?, + modelResolver: ModelResolver, +) : + BaseFhirQueryGenerator( + searchParameterResolver, + terminologyProvider, + modelResolver, + searchParameterResolver.fhirContext, + ) { + override val fhirVersion = FhirVersionEnum.DSTU3 + + override fun generateFhirQueries( + dataRequirement: ICompositeType?, + evaluationDateTime: DateTime?, + contextValues: MutableMap?, + parameters: MutableMap?, + capabilityStatement: IBaseConformance?, + ): MutableList { + require(dataRequirement is DataRequirement) { + "dataRequirement argument must be a DataRequirement" + } + require(!(capabilityStatement != null && capabilityStatement !is CapabilityStatement)) { + "capabilityStatement argument must be a CapabilityStatement" + } + + val queries: MutableList = ArrayList() + + val codeFilters: MutableList = ArrayList() + + if (dataRequirement.hasCodeFilter()) { + for (codeFilterComponent in dataRequirement.getCodeFilter()) { + if (!codeFilterComponent.hasPath()) { + continue + } + var codes: MutableList? = null + var valueSet: String? = null + + val codePath = codeFilterComponent.getPath() + + // TODO: What to do if/when System is not provided... + if (codeFilterComponent.hasValueCode()) { + codes = ArrayList() + val codeFilterValueCode = codeFilterComponent.getValueCode() + for (codeType in codeFilterValueCode) { + val code = Code() + code.code = codeType.asStringValue() + codes.add(code) + } + } + if (codeFilterComponent.hasValueCoding()) { + codes = ArrayList() + + val codeFilterValueCodings = codeFilterComponent.getValueCoding() + for (coding in codeFilterValueCodings) { + if (coding.hasCode()) { + val code = Code() + code.system = coding.getSystem() + code.code = coding.getCode() + codes.add(code) + } + } + } + if (codeFilterComponent.hasValueCodeableConcept()) { + val codeFilterValueCodeableConcepts = + codeFilterComponent.getValueCodeableConcept() + for (codeableConcept in codeFilterValueCodeableConcepts) { + val codeFilterValueCodeableConceptCodings = codeableConcept.getCoding() + for (coding in codeFilterValueCodeableConceptCodings) { + if (coding.hasCode()) { + val code = Code() + code.system = coding.getSystem() + code.code = coding.getCode() + codes!!.add(code) + } + } + } + } + if (codeFilterComponent.hasValueSet()) { + if (codeFilterComponent.valueSetReference.getReference() is String) { + valueSet = (codeFilterComponent.getValueSet() as Reference).getReference() + } else if (codeFilterComponent.valueSetReference is Reference) { + valueSet = codeFilterComponent.valueSetReference.getReference() + } + } + + codeFilters.add(CodeFilter(codePath, codes, valueSet)) + } + } + + val dateFilters: MutableList = ArrayList() + + if (dataRequirement.hasDateFilter()) { + for (dateFilterComponent in dataRequirement.getDateFilter()) { + if (!dateFilterComponent.hasPath()) { + throw UnsupportedOperationException("A path must be provided") + } + var dateLowPath: String? = null + var dateHighPath: String? = null + var dateRange: Interval? = null + + val datePath = dateFilterComponent.getPath() + + // TODO: Deal with the case that the value is expressed as an expression extension + if (dateFilterComponent.hasValue()) { + when (val dateFilterValue = dateFilterComponent.getValue()) { + is DateTimeType if dateFilterValue.hasPrimitiveValue() -> { + dateLowPath = "valueDateTime" + dateHighPath = "valueDateTime" + val offsetDateTimeString = dateFilterValue.valueAsString + val dateTime = DateTime(OffsetDateTime.parse(offsetDateTimeString)) + + dateRange = Interval(dateTime, true, dateTime, true) + } + + is Duration if dateFilterValue.hasValue() -> { + // If a Duration is specified, the filter will return only those data + // items that fall within + // Duration before now. + val dateFilterAsDuration = dateFilterValue + + val dateFilterDurationAsCQLQuantity = + Quantity() + .withValue(dateFilterAsDuration.getValue()) + .withUnit(dateFilterAsDuration.getUnit()) + + // Passing null as the state argument to the subtract method is fine + // here since that method only uses the state when it has to convert + // Quantities with different units which cannot happen here. + val diff = + (SubtractEvaluator.subtract( + evaluationDateTime, + dateFilterDurationAsCQLQuantity, + null, + ) as DateTime?) + + dateRange = Interval(diff, true, evaluationDateTime, true) + } + + is Period if dateFilterValue.hasStart() && dateFilterValue.hasEnd() -> { + dateLowPath = "valueDateTime" + dateHighPath = "valueDateTime" + dateRange = + Interval( + Date.fromJavaDate(dateFilterValue.getStart()), + true, + Date.fromJavaDate(dateFilterValue.getEnd()), + true, + ) + } + } + + dateFilters.add(DateFilter(datePath, dateLowPath, dateHighPath, dateRange)) + } + } + } + + // STU3 only supported Patient context + val contextType = "Patient" + val contextPath = modelResolver.getContextPath(contextType, dataRequirement.getType()) + val contextValue = contextValues?.get(contextType) + val templateId = + if (dataRequirement.getProfile() != null && !dataRequirement.getProfile().isEmpty()) + dataRequirement.getProfile()[0].value + else null + + val maps = + setupQueries( + contextType, + contextPath, + contextValue, + dataRequirement.getType(), + templateId, + codeFilters, + dateFilters, + ) + + for (map in maps) { + val query = + try { + URLDecoder.decode(map.toNormalizedQueryString(fhirContext), "UTF-8") + } catch (ex: Exception) { + map.toNormalizedQueryString(fhirContext) + } + queries.add(dataRequirement.getType() + query) + } + + return queries + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirBundleCursor.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirBundleCursor.kt new file mode 100644 index 0000000000000000000000000000000000000000..490f45093dd9f8f8c69185ee81950f842bdfcce2 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirBundleCursor.kt @@ -0,0 +1,142 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.util.BundleUtil +import org.hl7.fhir.instance.model.api.IBaseBundle +import org.hl7.fhir.instance.model.api.IBaseResource +import org.opencds.cqf.cql.engine.fhir.exception.UnknownElement + +class FhirBundleCursor // This constructor filters the bundle based on dataType +// If templateId is provided, this is a trusted cursor, meaning that it will only return results +// for resources that declare they conform to the given profile +@JvmOverloads +constructor( + private val fhirClient: IGenericClient, + private val results: IBaseBundle?, + private val dataType: String? = null, + private val templateId: String? = null, +) : Iterable { + /** + * Returns an iterator over elements of type `T`. + * + * @return an Iterator. + */ + override fun iterator(): Iterator { + return FhirBundleIterator(fhirClient, results, dataType, templateId) + } + + private inner class FhirBundleIterator( + private var fhirClient: IGenericClient, + private var results: IBaseBundle?, + private var dataType: String?, + private var templateId: String?, + ) : Iterator { + private var current: Int + private var dataTypeClass: Class? = null + private var currentEntry: MutableList + + init { + this.current = -1 + + // Do not test templateId for base resource "profiles" + if ( + this.templateId != null && + this.templateId!!.startsWith( + "http://hl7.org/fhir/StructureDefinition/$dataType" + ) + ) { + this.templateId = null + } + + if (dataType != null) { + this.dataTypeClass = + this.fhirClient.fhirContext + .getResourceDefinition(this.dataType) + .implementingClass + } + + this.currentEntry = this.entry + } + + /** + * Returns `true` if the iteration has more elements. (In other words, returns `true` if + * [.next] would return an element rather than throwing an exception.) + * + * @return `true` if the iteration has more elements + */ + override fun hasNext(): Boolean { + return current < this.currentEntry.size - 1 || this.link != null + } + + val entry: MutableList + get() { + return if (this.dataTypeClass != null) { + val entries: MutableList = + BundleUtil.toListOfResourcesOfType( + this.fhirClient.fhirContext, + this.results, + this.dataTypeClass, + ) + if (templateId != null) { + getTrustedEntries(entries, templateId) + } else { + entries + } + } else { + BundleUtil.toListOfResources(this.fhirClient.fhirContext, this.results) + } + } + + fun getTrustedEntries( + entries: MutableList, + templateId: String?, + ): MutableList { + val trustedEntries: MutableList = ArrayList() + for (entry in entries) { + if (entry.meta != null && entry.meta.profile != null) { + for (profile in entry.meta.profile) { + if (profile.hasValue() && profile.valueAsString == templateId) { + trustedEntries.add(entry) + } + } + } + } + return trustedEntries + } + + val link: String? + get() = + BundleUtil.getLinkUrlOfType( + this.fhirClient.fhirContext, + this.results, + IBaseBundle.LINK_NEXT, + ) + + /** + * Returns the next element in the iteration. + * + * @return the next element in the iteration + * @throws UnknownElement if the iteration has no more elements + */ + override fun next(): Any { + current++ + if (current < this.currentEntry.size) { + return this.currentEntry[current] + } else { + this.results = fhirClient.loadPage().next(results).execute() + this.currentEntry = this.entry + current = 0 + if (this.currentEntry.isNotEmpty()) { + return this.currentEntry[current] + } + } + + // TODO: It would be possible to get here if the next link was present, but the returned + // page had 0 + // entries... + // NOTE: This is especially true if the page has only data that is not conformant to the + // given profile + throw UnknownElement("The iteration has no more elements.") + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirQueryGeneratorFactory.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirQueryGeneratorFactory.kt new file mode 100644 index 0000000000000000000000000000000000000000..039035b1c2440e0ef69544c6f69ebd9c84a6c503 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirQueryGeneratorFactory.kt @@ -0,0 +1,81 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirVersionEnum +import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver +import org.opencds.cqf.cql.engine.model.ModelResolver +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider + +object FhirQueryGeneratorFactory { + /** + * Creates a FHIR version-specific FhirQueryGenerator + * + * @param modelResolver is the model resolver for specific fhir version + * @param searchParameterResolver the SearchParameterResolver instance the Generator should use + * @param terminologyProvider the TerminologyProvider instance the Generator should use + * @return a BaseFhirQueryGenerator + * @throws IllegalArgumentException if the FHIR version specified is not supported + */ + @Throws(FhirVersionMisMatchException::class) + fun create( + modelResolver: ModelResolver, + searchParameterResolver: SearchParameterResolver, + terminologyProvider: TerminologyProvider?, + ): BaseFhirQueryGenerator { + return when (val fhirVersionEnum = searchParameterResolver.fhirContext.version.version) { + FhirVersionEnum.DSTU3 -> { + Dstu3FhirQueryGenerator(searchParameterResolver, terminologyProvider, modelResolver) + } + FhirVersionEnum.R4 -> { + R4FhirQueryGenerator(searchParameterResolver, terminologyProvider, modelResolver) + } + else -> { + throw IllegalArgumentException( + "Unsupported FHIR version for FHIR Query Generation: $fhirVersionEnum" + ) + } + } + } + + /** + * Creates a FHIR version-specific FhirQueryGenerator + * + * @param modelResolver is the model resolver for specific fhir version + * @param searchParameterResolver the SearchParameterResolver instance the Generator should use + * @param terminologyProvider the TerminologyProvider instance the Generator should use + * @param shouldExpandValueSets configuration indicating whether or not ValueSets should be + * expanded for querying via list of codes as opposed to using the :in modifier. + * @param maxCodesPerQuery configuration indicating how many codes, at most, should be included + * on a query string + * @param pageSize configuration indicating what the _count should be on the query + * @return a BaseFhirQueryGenerator + * @throws IllegalArgumentException if the FHIR version specified is not supported + */ + @Throws(FhirVersionMisMatchException::class) + fun create( + modelResolver: ModelResolver, + searchParameterResolver: SearchParameterResolver, + terminologyProvider: TerminologyProvider?, + shouldExpandValueSets: Boolean?, + maxCodesPerQuery: Int?, + pageSize: Int?, + queryBatchThreshold: Int?, + ): BaseFhirQueryGenerator { + val baseFhirQueryGenerator = + create(modelResolver, searchParameterResolver, terminologyProvider) + if (shouldExpandValueSets != null) { + baseFhirQueryGenerator.isExpandValueSets = shouldExpandValueSets + } + if (maxCodesPerQuery != null) { + baseFhirQueryGenerator.maxCodesPerQuery = maxCodesPerQuery + } + if (queryBatchThreshold != null) { + baseFhirQueryGenerator.queryBatchThreshold = queryBatchThreshold + } + if (pageSize != null) { + baseFhirQueryGenerator.pageSize = pageSize + } + + return baseFhirQueryGenerator + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirVersionIntegrityChecker.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirVersionIntegrityChecker.kt new file mode 100644 index 0000000000000000000000000000000000000000..06ba347156733aedb5b2f175b562a0b2ec869e3c --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/FhirVersionIntegrityChecker.kt @@ -0,0 +1,11 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirVersionEnum +import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException + +interface FhirVersionIntegrityChecker { + @Throws(FhirVersionMisMatchException::class) + fun validateFhirVersionIntegrity(fhirVersion: FhirVersionEnum) + + val fhirVersion: FhirVersionEnum +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/R4FhirQueryGenerator.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/R4FhirQueryGenerator.kt new file mode 100644 index 0000000000000000000000000000000000000000..3e745cd125e7450a26481c11eeb82af68ba678b2 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/R4FhirQueryGenerator.kt @@ -0,0 +1,212 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirVersionEnum +import java.net.URLDecoder +import java.time.OffsetDateTime +import org.hl7.fhir.instance.model.api.IBaseConformance +import org.hl7.fhir.instance.model.api.ICompositeType +import org.hl7.fhir.r4.model.CapabilityStatement +import org.hl7.fhir.r4.model.Coding +import org.hl7.fhir.r4.model.DataRequirement +import org.hl7.fhir.r4.model.DateTimeType +import org.hl7.fhir.r4.model.Duration +import org.hl7.fhir.r4.model.Period +import org.opencds.cqf.cql.engine.elm.executing.SubtractEvaluator +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver +import org.opencds.cqf.cql.engine.model.ModelResolver +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.Quantity +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider + +class R4FhirQueryGenerator( + searchParameterResolver: SearchParameterResolver, + terminologyProvider: TerminologyProvider?, + modelResolver: ModelResolver, +) : + BaseFhirQueryGenerator( + searchParameterResolver, + terminologyProvider, + modelResolver, + searchParameterResolver.fhirContext, + ) { + + override val fhirVersion = FhirVersionEnum.R4 + + override fun generateFhirQueries( + dataRequirement: ICompositeType?, + evaluationDateTime: DateTime?, + contextValues: MutableMap?, + parameters: MutableMap?, + capabilityStatement: IBaseConformance?, + ): MutableList { + require(dataRequirement is DataRequirement) { + "dataRequirement argument must be a DataRequirement" + } + require(!(capabilityStatement != null && capabilityStatement !is CapabilityStatement)) { + "capabilityStatement argument must be a CapabilityStatement" + } + + val queries: MutableList = ArrayList() + + val codeFilters: MutableList = ArrayList() + if (dataRequirement.hasCodeFilter()) { + for (codeFilterComponent in dataRequirement.getCodeFilter()) { + if (!codeFilterComponent.hasPath()) continue + var codes: MutableList? = null + var valueSet: String? = null + + val codePath = codeFilterComponent.getPath() + + if (codeFilterComponent.hasValueSetElement()) { + valueSet = codeFilterComponent.getValueSet() + } + + if (codeFilterComponent.hasCode()) { + codes = ArrayList() + + val codeFilterValueCodings = codeFilterComponent.getCode() + for (coding in codeFilterValueCodings) { + if (coding.hasCode()) { + val code = Code() + code.system = coding.getSystem() + code.code = coding.getCode() + codes.add(code) + } + } + } + + codeFilters.add(CodeFilter(codePath, codes, valueSet)) + } + } + + val dateFilters: MutableList = ArrayList() + + if (dataRequirement.hasDateFilter()) { + for (dateFilterComponent in dataRequirement.getDateFilter()) { + var datePath: String? = null + var dateLowPath: String? = null + var dateHighPath: String? = null + var dateRange: Interval? = null + + if (dateFilterComponent.hasPath() && dateFilterComponent.hasSearchParam()) { + throw UnsupportedOperationException( + "Either a path or a searchParam must be provided, but not both" + ) + } + + if (dateFilterComponent.hasPath()) { + datePath = dateFilterComponent.getPath() + } else if (dateFilterComponent.hasSearchParam()) { + datePath = dateFilterComponent.getSearchParam() + } + + // TODO: Deal with the case that the value is expressed as an expression extension + if (dateFilterComponent.hasValue()) { + when (val dateFilterValue = dateFilterComponent.getValue()) { + is DateTimeType if dateFilterValue.hasPrimitiveValue() -> { + dateLowPath = "valueDateTime" + dateHighPath = "valueDateTime" + val offsetDateTimeString = dateFilterValue.valueAsString + val dateTime = DateTime(OffsetDateTime.parse(offsetDateTimeString)) + + dateRange = Interval(dateTime, true, dateTime, true) + } + + is Duration if dateFilterValue.hasValue() -> { + // If a Duration is specified, the filter will return only those data + // items that fall within + // Duration before now. + val dateFilterAsDuration = dateFilterValue + + val dateFilterDurationAsCQLQuantity = + Quantity() + .withValue(dateFilterAsDuration.getValue()) + .withUnit(dateFilterAsDuration.getUnit()) + + // Passing null as the state argument to the subtract method is fine + // here since that method only uses the state when it has to convert + // Quantities with different units which cannot happen here. + val diff = + (SubtractEvaluator.subtract( + evaluationDateTime, + dateFilterDurationAsCQLQuantity, + null, + ) as DateTime?) + + dateRange = Interval(diff, true, evaluationDateTime, true) + } + + is Period if dateFilterValue.hasStart() && dateFilterValue.hasEnd() -> { + dateLowPath = "valueDateTime" + dateHighPath = "valueDateTime" + dateRange = + Interval( + Date.fromJavaDate(dateFilterValue.getStart()), + true, + Date.fromJavaDate(dateFilterValue.getEnd()), + true, + ) + } + } + + dateFilters.add(DateFilter(datePath, dateLowPath, dateHighPath, dateRange)) + } + } + } + + // Patient is the default context if one is not specified + var contextType: String? = "Patient" + + require(!dataRequirement.hasSubjectReference()) { + "Cannot process data requirements with subjects specified as references" + } + + if (dataRequirement.hasSubjectCodeableConcept()) { + var c: Coding? = null + for (coding in dataRequirement.subjectCodeableConcept.getCoding()) { + if ("http://hl7.org/fhir/resource-types" == coding.getSystem()) { + c = coding + break + } + } + requireNotNull(c) { + "Cannot process data requirements with subjects not specified using a code from http://hl7.org/fhir/resource-types" + } + contextType = c.getCode() + } + + val contextPath = modelResolver.getContextPath(contextType, dataRequirement.getType()) + val contextValue = contextValues?.get(contextType) + val templateId = + if (dataRequirement.getProfile() != null && !dataRequirement.getProfile().isEmpty()) + dataRequirement.getProfile()[0].value + else null + + val maps = + setupQueries( + contextType, + contextPath, + contextValue, + dataRequirement.getType(), + templateId, + codeFilters, + dateFilters, + ) + + for (map in maps) { + val query = + try { + URLDecoder.decode(map.toNormalizedQueryString(fhirContext), "UTF-8") + } catch (ex: Exception) { + map.toNormalizedQueryString(fhirContext) + } + queries.add(dataRequirement.getType() + query) + } + + return queries + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/RestFhirRetrieveProvider.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/RestFhirRetrieveProvider.kt new file mode 100644 index 0000000000000000000000000000000000000000..c9478b08914953882c71fd325250a77dfbecb5e2 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/RestFhirRetrieveProvider.kt @@ -0,0 +1,168 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirVersionEnum +import ca.uhn.fhir.model.api.IQueryParameterType +import ca.uhn.fhir.rest.api.SearchStyleEnum +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.rest.gclient.TokenClientParam +import ca.uhn.fhir.rest.param.TokenParam +import java.util.function.BiFunction +import java.util.function.Consumer +import org.hl7.fhir.dstu3.model.Coding +import org.hl7.fhir.instance.model.api.IBaseBundle +import org.hl7.fhir.instance.model.api.IBaseCoding +import org.hl7.fhir.instance.model.api.IBaseResource +import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver + +class RestFhirRetrieveProvider( + searchParameterResolver: SearchParameterResolver, + modelResolver: FhirModelResolver<*, *, *, *, *, *, *, *>, + private val fhirClient: IGenericClient, +) : SearchParamFhirRetrieveProvider(searchParameterResolver, modelResolver) { + var searchStyle: SearchStyleEnum = DEFAULT_SEARCH_STYLE + + override fun executeQueries( + dataType: String?, + queries: MutableList, + ): Iterable { + if (queries.isEmpty()) { + return mutableListOf() + } + + val objects: MutableList = ArrayList() + val bundles: MutableList = ArrayList() + for (map in queries) { + val result = this.executeQuery(dataType, map) + if (result is IBaseBundle) { + bundles.add(result) + } else { + objects.add(result) + } + } + + // TODO: evaluate this lazily in case the engine only needs the first element + for (b in bundles) { + val cursor = FhirBundleCursor(fhirClient, b, dataType) + cursor.forEach(Consumer { e: Any? -> objects.add(e) }) + } + + return objects + } + + private fun executeQuery(dataType: String?, map: SearchParameterMap): IBaseResource? { + if (map.containsKey("_id")) { + return this.queryById(dataType, map) + } else { + var search = this.fhirClient.search().forResource(dataType) + + val flattenedMap: MutableMap> = mutableMapOf() + for (entry in map.entrySet()) { + val name: String = entry.key + + val value: MutableList> = entry.value + if (value.isEmpty()) { + continue + } + + val flattened: MutableList = ArrayList() + + for (subList in value) { + if (subList.isEmpty()) { + continue + } + + if (subList.size == 1) { + flattened.add(subList[0]) + continue + } + + // Sublists are logical "Ors" + // The only "Or" supported from the engine are tokens at the moment. + // So this is a hack to add them to a "criterion", which is the + // only way the HAPI POST api supports passing them. + val first = subList[0] + if (first is TokenParam) { + val tcp = TokenClientParam(name) + + val codings = this.toCodings(subList) + + val criterion = tcp.exactly().codings(*codings) + + search = search.where(criterion) + } else { + flattened.addAll(subList) + } + } + + flattenedMap[name] = flattened + } + + if (pageSize != null) { + search.count(pageSize!!) + } + + return search.where(flattenedMap).usingStyle(this.searchStyle).execute() + } + } + + private fun queryById(dataType: String?, map: SearchParameterMap): IBaseResource? { + require(map.entrySet().size <= 1) { + "Error querying $dataType. Queries by id must not have any other search criteria." + } + + val tokenList: MutableList = map.get("_id")!![0] + require(!tokenList.isEmpty()) { + "Error querying $dataType. Attempted query by id but no id was specified." + } + + require(tokenList.size <= 1) { + "Error querying $dataType. Attempted query by id but multiple ids were specified." + } + + val param = tokenList[0] + require(param is TokenParam) { + "Error querying $dataType. Attempted query by id but a non-token parameter was given." + } + + val id = param.value + + requireNotNull(id) { "Error querying $dataType. Attempted query by id but id was null." } + + return queryById(dataType, id) + } + + private fun queryById(dataType: String?, id: String?): IBaseResource? { + return this.fhirClient.read().resource(dataType).withId(id).execute() + } + + private fun toCodings(codingList: MutableList): Array { + val codings: MutableList = ArrayList() + + val codingConverter = + when (this.fhirClient.fhirContext.version.version) { + FhirVersionEnum.DSTU3 -> + BiFunction { system: String?, code: String? -> Coding(system, code, null) } + FhirVersionEnum.R4 -> + BiFunction { system: String?, code: String? -> + org.hl7.fhir.r4.model.Coding(system, code, null) + } + else -> throw IllegalArgumentException("Unhandled FHIR version") + } + + for (param in codingList) { + val token = param as TokenParam + + val coding = codingConverter.apply(token.system, token.value) + + codings.add(coding) + } + + return codings.toTypedArray() + } + + companion object { + private val DEFAULT_SEARCH_STYLE = SearchStyleEnum.GET + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/SearchParamFhirRetrieveProvider.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/SearchParamFhirRetrieveProvider.kt new file mode 100644 index 0000000000000000000000000000000000000000..d3b34e117bfa662b4e97b7b41ae44f3975db44bb --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/retrieve/SearchParamFhirRetrieveProvider.kt @@ -0,0 +1,111 @@ +package org.opencds.cqf.cql.engine.fhir.retrieve + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import org.opencds.cqf.cql.engine.fhir.exception.FhirVersionMisMatchException +import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterMap +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver +import org.opencds.cqf.cql.engine.retrieve.TerminologyAwareRetrieveProvider +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.Value + +abstract class SearchParamFhirRetrieveProvider +protected constructor( + val searchParameterResolver: SearchParameterResolver, + val modelResolver: FhirModelResolver<*, *, *, *, *, *, *, *>, +) : TerminologyAwareRetrieveProvider() { + protected val fhirContext: FhirContext + get() = searchParameterResolver.fhirContext + + var fhirQueryGenerator: BaseFhirQueryGenerator? = null + + var pageSize: Int? = null + set(value) { + require(value == null || value > 0) { "value must be a non-null integer > 0" } + field = value + } + + var maxCodesPerQuery: Int? = null + set(value) { + require(value != null && value >= 1) { "value must be a non-null integer > 0" } + field = value + } + + var queryBatchThreshold: Int? = null + set(value) { + require(value != null && value >= 1) { "value must be a non-null integer > 0" } + field = value + } + + protected abstract fun executeQueries( + dataType: String?, + queries: MutableList, + ): Iterable? + + override fun retrieve( + context: String?, + contextPath: String?, + contextValue: String?, + dataType: String, + templateId: String?, + codePath: String?, + codes: Iterable?, + valueSet: String?, + datePath: String?, + dateLowPath: String?, + dateHighPath: String?, + dateRange: Interval?, + ): Iterable? { + + try { + if (this.fhirContext.version.version == FhirVersionEnum.DSTU3) { + fhirQueryGenerator = + Dstu3FhirQueryGenerator( + searchParameterResolver, + terminologyProvider, + this.modelResolver, + ) + } else if (this.fhirContext.version.version == FhirVersionEnum.R4) { + fhirQueryGenerator = + R4FhirQueryGenerator( + searchParameterResolver, + terminologyProvider, + this.modelResolver, + ) + } + } catch (exception: FhirVersionMisMatchException) { + throw RuntimeException(exception.message) + } + fhirQueryGenerator!!.isExpandValueSets = isExpandValueSets + + if (maxCodesPerQuery != null) { + fhirQueryGenerator!!.maxCodesPerQuery = maxCodesPerQuery + } + if (queryBatchThreshold != null) { + fhirQueryGenerator!!.queryBatchThreshold = queryBatchThreshold + } + if (pageSize != null) { + fhirQueryGenerator!!.pageSize = pageSize + } + + val queries = + fhirQueryGenerator!!.setupQueries( + context, + contextPath, + contextValue, + dataType, + templateId, + codePath, + codes, + valueSet, + datePath, + dateLowPath, + dateHighPath, + dateRange, + ) + + return this.executeQueries(dataType, queries)?.map { modelResolver.toCqlValue(it) } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterMap.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterMap.kt new file mode 100644 index 0000000000000000000000000000000000000000..8025800df468867538d41cd42dcf0410dc164ae0 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterMap.kt @@ -0,0 +1,526 @@ +package org.opencds.cqf.cql.engine.fhir.searchparam + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.model.api.IQueryParameterAnd +import ca.uhn.fhir.model.api.IQueryParameterOr +import ca.uhn.fhir.model.api.IQueryParameterType +import ca.uhn.fhir.model.api.Include +import ca.uhn.fhir.rest.api.Constants +import ca.uhn.fhir.rest.api.SearchTotalModeEnum +import ca.uhn.fhir.rest.api.SortOrderEnum +import ca.uhn.fhir.rest.api.SortSpec +import ca.uhn.fhir.rest.api.SummaryEnum +import ca.uhn.fhir.rest.param.DateParam +import ca.uhn.fhir.rest.param.DateRangeParam +import ca.uhn.fhir.rest.param.QuantityParam +import ca.uhn.fhir.util.UrlUtil +import java.io.Serializable +import org.apache.commons.lang3.StringUtils +import org.apache.commons.lang3.Validate +import org.apache.commons.lang3.builder.ToStringBuilder +import org.apache.commons.lang3.builder.ToStringStyle +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +// This class was copied from package ca.uhn.fhir.jpa.searchparam.SearchParameterMap +// It included many unnecessary HAPI FHIR server dependencies. +// Justification for these suppressions: this is a copy of hapi-fhir code. +class SearchParameterMap : Serializable { + private val mySearchParameterMap: + MutableMap>> = + mutableMapOf() + + var count: Int? = null + var everythingMode: EverythingModeEnum? = null + private var myIncludes: MutableSet? = null + private var myLastUpdated: DateRangeParam? = null + var isLoadSynchronous: Boolean = false + private set + + var loadSynchronousUpTo: Int? = null + private set + + private var myRevIncludes: MutableSet? = null + var sort: SortSpec? = null + var summaryMode: SummaryEnum? = null + var searchTotalMode: SearchTotalModeEnum? = null + + constructor() : super() + + constructor(theName: String, theParam: IQueryParameterType?) { + add(theName, theParam) + } + + fun add(theName: String, theDateParam: DateParam?): SearchParameterMap { + add(theName, theDateParam as IQueryParameterOr<*>?) + return this + } + + fun add(theName: String, theAnd: IQueryParameterAnd<*>?) { + if (theAnd == null) { + return + } + if (!containsKey(theName)) { + put(theName, mutableListOf()) + } + + for (next in theAnd.getValuesAsQueryTokens()) { + if (next == null) { + continue + } + + get(theName)!!.add((next.getValuesAsQueryTokens() as MutableList)) + } + } + + fun add(theName: String, theOr: IQueryParameterOr<*>?) { + if (theOr == null) { + return + } + if (!containsKey(theName)) { + put(theName, mutableListOf()) + } + + get(theName)!!.add((theOr.getValuesAsQueryTokens() as MutableList)) + } + + fun values(): Collection>> { + return mySearchParameterMap.values + } + + fun add(theName: String, theParam: IQueryParameterType?): SearchParameterMap { + assert( + Constants.PARAM_LASTUPDATED != theName // this has it's own field in the map + ) + + if (theParam == null) { + return this + } + if (!containsKey(theName)) { + put(theName, mutableListOf()) + } + val list = ArrayList() + list.add(theParam) + get(theName)!!.add(list) + + return this + } + + fun addInclude(theInclude: Include) { + this.includes.add(theInclude) + } + + private fun addLastUpdateParam(b: StringBuilder, date: DateParam?) { + if (date != null && StringUtils.isNotBlank(date.valueAsString)) { + addUrlParamSeparator(b) + b.append(Constants.PARAM_LASTUPDATED) + b.append('=') + b.append(date.valueAsString) + } + } + + fun addRevInclude(theInclude: Include) { + this.revIncludes.add(theInclude) + } + + private fun addUrlIncludeParams( + b: StringBuilder, + paramName: String?, + theList: MutableSet, + ) { + val list = theList.toMutableList() + + list.sortWith(IncludeComparator()) + for (nextInclude in list) { + addUrlParamSeparator(b) + b.append(paramName) + b.append('=') + b.append(UrlUtil.escapeUrlParam(nextInclude.paramType)) + b.append(':') + b.append(UrlUtil.escapeUrlParam(nextInclude.paramName)) + if (StringUtils.isNotBlank(nextInclude.paramTargetType)) { + b.append(':') + b.append(nextInclude.paramTargetType) + } + } + } + + private fun addUrlParamSeparator(theB: StringBuilder) { + if (theB.isEmpty()) { + theB.append('?') + } else { + theB.append('&') + } + } + + var includes: MutableSet + get() { + if (myIncludes == null) { + myIncludes = mutableSetOf() + } + return myIncludes!! + } + set(theIncludes) { + myIncludes = theIncludes + } + + var lastUpdated: DateRangeParam? + get() { + if (myLastUpdated != null) { + if (myLastUpdated!!.isEmpty) { + myLastUpdated = null + } + } + return myLastUpdated + } + set(theLastUpdated) { + myLastUpdated = theLastUpdated + } + + fun setLoadSynchronousUpTo(theLoadSynchronousUpTo: Int?): SearchParameterMap { + this.loadSynchronousUpTo = theLoadSynchronousUpTo + if (this.loadSynchronousUpTo != null) { + setLoadSynchronous(true) + } + return this + } + + var revIncludes: MutableSet + get() { + if (myRevIncludes == null) { + myRevIncludes = mutableSetOf() + } + return myRevIncludes!! + } + set(theRevIncludes) { + myRevIncludes = theRevIncludes + } + + val isAllParametersHaveNoModifier: Boolean + get() { + for (nextParamName in values()) { + for (nextAnd in nextParamName) { + for (nextOr in nextAnd) { + if (StringUtils.isNotBlank(nextOr.queryParameterQualifier)) { + return false + } + } + } + } + return true + } + + fun setLoadSynchronous(theLoadSynchronous: Boolean): SearchParameterMap { + this.isLoadSynchronous = theLoadSynchronous + return this + } + + fun toNormalizedQueryString(theCtx: FhirContext): String { + val b = StringBuilder() + + val keys = keySet().sorted() + for (nextKey in keys) { + val nextValuesAndsIn = get(nextKey)!! + val nextValuesAndsOut: MutableList> = mutableListOf() + for (nextValuesAndIn in nextValuesAndsIn) { + val nextValuesOrsOut: MutableList = mutableListOf() + for (nextValueOrIn in nextValuesAndIn) { + if ( + nextValueOrIn.missing != null || + StringUtils.isNotBlank(nextValueOrIn.getValueAsQueryToken(theCtx)) + ) { + nextValuesOrsOut.add(nextValueOrIn) + } + } + + nextValuesOrsOut.sortWith(QueryParameterTypeComparator(theCtx)) + + if (nextValuesOrsOut.isNotEmpty()) { + nextValuesAndsOut.add(nextValuesOrsOut) + } + } // for AND + + nextValuesAndsOut.sortWith(QueryParameterOrComparator(theCtx)) + + for (nextValuesAnd in nextValuesAndsOut) { + addUrlParamSeparator(b) + val firstValue: IQueryParameterType = nextValuesAnd[0] + b.append(UrlUtil.escapeUrlParam(nextKey)) + + if (nextKey == Constants.PARAM_HAS) { + b.append(':') + } + + if (firstValue.missing != null) { + b.append(Constants.PARAMQUALIFIER_MISSING) + b.append('=') + if (firstValue.missing) { + b.append(Constants.PARAMQUALIFIER_MISSING_TRUE) + } else { + b.append(Constants.PARAMQUALIFIER_MISSING_FALSE) + } + continue + } + + if (StringUtils.isNotBlank(firstValue.queryParameterQualifier)) { + b.append(firstValue.queryParameterQualifier) + } + + b.append('=') + + for (i in nextValuesAnd.indices) { + val nextValueOr: IQueryParameterType = nextValuesAnd[i] + if (i > 0) { + b.append(',') + } + val valueAsQueryToken = nextValueOr.getValueAsQueryToken(theCtx) + b.append(UrlUtil.escapeUrlParam(valueAsQueryToken)) + } + } + } // for keys + + var sort = this.sort + var first = true + while (sort != null) { + if (StringUtils.isNotBlank(sort.paramName)) { + if (first) { + addUrlParamSeparator(b) + b.append(Constants.PARAM_SORT) + b.append('=') + first = false + } else { + b.append(',') + } + if (sort.order == SortOrderEnum.DESC) { + b.append('-') + } + b.append(sort.paramName) + } + + Validate.isTrue(sort !== sort.chain) // just in case, shouldn't happen + sort = sort.chain + } + + addUrlIncludeParams(b, Constants.PARAM_INCLUDE, this.includes) + addUrlIncludeParams(b, Constants.PARAM_REVINCLUDE, this.revIncludes) + + if (this.lastUpdated != null) { + val lb = this.lastUpdated!!.lowerBound + addLastUpdateParam(b, lb) + val ub = this.lastUpdated!!.upperBound + addLastUpdateParam(b, ub) + } + + if (this.count != null) { + addUrlParamSeparator(b) + b.append(Constants.PARAM_COUNT) + b.append('=') + b.append(this.count) + } + + // Summary mode (_summary) + if (this.summaryMode != null) { + addUrlParamSeparator(b) + b.append(Constants.PARAM_SUMMARY) + b.append('=') + b.append(this.summaryMode!!.code) + } + + // Search count mode (_total) + if (this.searchTotalMode != null) { + addUrlParamSeparator(b) + b.append(Constants.PARAM_SEARCH_TOTAL_MODE) + b.append('=') + b.append(this.searchTotalMode!!.code) + } + + if (b.isEmpty()) { + b.append('?') + } + + return b.toString() + } + + override fun toString(): String { + val b = ToStringBuilder(this, ToStringStyle.SHORT_PREFIX_STYLE) + if (!this.isEmpty) { + b.append("params", mySearchParameterMap) + } + if (!this.includes.isEmpty()) { + b.append("includes", this.includes) + } + return b.toString() + } + + fun clean() { + for (nextParamEntry in this.entrySet()) { + val nextParamName = nextParamEntry.key + val andOrParams: MutableList> = nextParamEntry.value + clean(nextParamName, andOrParams) + } + } + + private fun clean( + theParamName: String?, + theAndOrParams: MutableList>, + ) { + var andListIdx = 0 + while (andListIdx < theAndOrParams.size) { + val nextOrList: MutableList = theAndOrParams[andListIdx] + + var orListIdx = 0 + while (orListIdx < nextOrList.size) { + val nextOr: IQueryParameterType = nextOrList[orListIdx] + var hasNoValue = false + if (nextOr.missing != null) { + orListIdx++ + continue + } + if (nextOr is QuantityParam) { + if (StringUtils.isBlank(nextOr.valueAsString)) { + hasNoValue = true + } + } + + if (hasNoValue) { + ourLog.debug("Ignoring empty parameter: {}", theParamName) + nextOrList.removeAt(orListIdx) + orListIdx-- + } + orListIdx++ + } + + if (nextOrList.isEmpty()) { + theAndOrParams.removeAt(andListIdx) + andListIdx-- + } + andListIdx++ + } + } + + enum class EverythingModeEnum( + thePatient: Boolean, + theEncounter: Boolean, + theInstance: Boolean, + ) { + ENCOUNTER_INSTANCE(false, true, true), + ENCOUNTER_TYPE(false, true, false), + PATIENT_INSTANCE(true, false, true), + PATIENT_TYPE(true, false, false); + + val isEncounter: Boolean + + val isInstance: Boolean + + val isPatient: Boolean + + init { + assert(thePatient xor theEncounter) + this.isPatient = thePatient + this.isEncounter = theEncounter + this.isInstance = theInstance + } + } + + class IncludeComparator : Comparator { + override fun compare(theO1: Include, theO2: Include): Int { + var retVal = StringUtils.compare(theO1.paramType, theO2.paramType) + if (retVal == 0) { + retVal = StringUtils.compare(theO1.paramName, theO2.paramName) + } + if (retVal == 0) { + retVal = StringUtils.compare(theO1.paramTargetType, theO2.paramTargetType) + } + return retVal + } + } + + class QueryParameterOrComparator internal constructor(private val myCtx: FhirContext) : + Comparator> { + override fun compare( + theO1: MutableList, + theO2: MutableList, + ): Int { + // These lists will never be empty + return compare(myCtx, theO1[0], theO2[0]) + } + } + + class QueryParameterTypeComparator internal constructor(private val myCtx: FhirContext) : + Comparator { + override fun compare(theO1: IQueryParameterType, theO2: IQueryParameterType): Int { + return compare(myCtx, theO1, theO2) + } + } + + // Wrapper methods + fun get(theName: String): MutableList>? { + return mySearchParameterMap[theName] + } + + private fun put(theName: String, theParams: MutableList>) { + mySearchParameterMap[theName] = theParams + } + + fun containsKey(theName: String?): Boolean { + return mySearchParameterMap.containsKey(theName) + } + + fun keySet(): Set { + return mySearchParameterMap.keys + } + + val isEmpty: Boolean + get() = mySearchParameterMap.isEmpty() + + fun entrySet(): Set>>> { + return mySearchParameterMap.entries + } + + fun remove(theName: String): MutableList>? { + return mySearchParameterMap.remove(theName) + } + + companion object { + private val ourLog: Logger = LoggerFactory.getLogger(SearchParameterMap::class.java) + + private const val serialVersionUID = 1L + + private fun compare( + theCtx: FhirContext?, + theO1: IQueryParameterType, + theO2: IQueryParameterType, + ): Int { + var retVal: Int + retVal = + if (theO1.missing == null && theO2.missing == null) { + 0 + } else if (theO1.missing == null) { + -1 + } else if (theO2.missing == null) { + 1 + } else if (theO1.missing == theO2.missing) { + 0 + } else { + if (theO1.missing) { + 1 + } else { + -1 + } + } + + if (retVal == 0) { + val q1 = theO1.queryParameterQualifier + val q2 = theO2.queryParameterQualifier + retVal = StringUtils.compare(q1, q2) + } + + if (retVal == 0) { + val v1 = theO1.getValueAsQueryToken(theCtx) + val v2 = theO2.getValueAsQueryToken(theCtx) + retVal = StringUtils.compare(v1, v2) + } + return retVal + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterResolver.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterResolver.kt new file mode 100644 index 0000000000000000000000000000000000000000..ab6542657d3cc24f346ba50a2587c821bd45753c --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/searchparam/SearchParameterResolver.kt @@ -0,0 +1,167 @@ +package org.opencds.cqf.cql.engine.fhir.searchparam + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.RuntimeSearchParam +import ca.uhn.fhir.model.api.IQueryParameterType +import ca.uhn.fhir.rest.api.RestSearchParameterTypeEnum +import ca.uhn.fhir.rest.param.NumberParam +import ca.uhn.fhir.rest.param.QuantityParam +import ca.uhn.fhir.rest.param.ReferenceParam +import ca.uhn.fhir.rest.param.StringParam +import ca.uhn.fhir.rest.param.TokenParam +import ca.uhn.fhir.rest.param.UriParam +import org.apache.commons.lang3.tuple.Pair + +class SearchParameterResolver(val fhirContext: FhirContext) { + fun getSearchParameterDefinition(dataType: String?, path: String?): RuntimeSearchParam? { + return this.getSearchParameterDefinition( + dataType, + path, + null as RestSearchParameterTypeEnum?, + ) + } + + fun getSearchParameterDefinition( + dataType: String?, + path: String?, + paramType: RestSearchParameterTypeEnum?, + ): RuntimeSearchParam? { + var path = path + if (dataType == null || path == null) { + return null + } + + // Special case for system params. They need to be resolved by name. + // TODO: All the others like "_language" + var name: String? = null + if (path == "id") { + name = "_id" + path = "" + } + + val params = this.fhirContext.getResourceDefinition(dataType).searchParams + + for (param in params) { + // If name matches, it's the one we want. + if (name != null && param.name == name) { + return param + } + + // Filter out parameters that don't match our requested type. + if (paramType != null && param.paramType != paramType) { + continue + } + + val normalizedPath = normalizePath(param.path) + if (path == normalizedPath || path.equals(param.name, ignoreCase = true)) { + return param + } + } + + return null + } + + fun createSearchParameter( + context: String?, + dataType: String?, + path: String?, + value: String?, + ): Pair? { + val searchParam = this.getSearchParameterDefinition(dataType, path) ?: return null + + val name = searchParam.name + + when (searchParam.paramType) { + RestSearchParameterTypeEnum.TOKEN -> + return Pair.of(name, TokenParam(value)) + RestSearchParameterTypeEnum.REFERENCE -> + return Pair.of( + name, + ReferenceParam(context, null, value), + ) + + RestSearchParameterTypeEnum.QUANTITY -> + return Pair.of(name, QuantityParam(value)) + + RestSearchParameterTypeEnum.STRING -> + return Pair.of(name, StringParam(value)) + + RestSearchParameterTypeEnum.NUMBER -> + return Pair.of(name, NumberParam(value)) + + RestSearchParameterTypeEnum.URI -> + return Pair.of(name, UriParam(value)) + + RestSearchParameterTypeEnum.DATE, + RestSearchParameterTypeEnum.HAS, + RestSearchParameterTypeEnum.COMPOSITE, + RestSearchParameterTypeEnum.SPECIAL -> {} + } + + return null + } + + // This is actually a lot of processing. We should cache search parameter resolutions. + private fun normalizePath(path: String): String? { + // TODO: What we really need is FhirPath parsing to just get the path + // MedicationAdministration.medication.as(CodeableConcept) + // MedicationAdministration.medication.as(Reference) + // (MedicationAdministration.medication as CodeableConcept) + // (MedicationAdministration.medication as Reference) + // Condition.onset.as(Age) | Condition.onset.as(Range) + // Observation.code | Observation.component.code + + // Trim off outer parens + + var path = path + if (path == "(") { + path = path.substring(1, path.length - 1) + } + + val normalizedParts = mutableSetOf() + val orParts = path.split("|") + for (part in orParts) { + path = part.trim { it <= ' ' } + + // Trim off DataType + path = path.substring(path.indexOf(".") + 1, path.length) + + // Split into components + val pathSplit = path.split(".") + val newPathParts = mutableListOf() + + for (p in pathSplit) { + // Skip the "as(X)" part. + if (p.startsWith("as(")) { + continue + } + + // Skip the "[x]" part. + if (p.startsWith("[x]")) { + continue + } + + // Filter out spaces and everything after "medication as Reference" + val ps = p.split(" ") + if (ps.isNotEmpty()) { + newPathParts.add(ps[0]) + } + } + + path = newPathParts.joinToString(".") + normalizedParts.add(path) + } + + // This handles cases such as /Condition?onset-age and /Condition?onset-date + // where there are multiple underlying representations of the same property + // (e.g. Condition.onset.as(Age) | Condition.onset.as(Range)), but + // will punt on something like /Observation?combo-code where the underlying + // representation maps to multiple places in a nested hierarchy (e.g. + // Observation.code | Observation.component.code ). + return if (normalizedParts.size == 1) { + normalizedParts.iterator().next() + } else { + null + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/Dstu3FhirTerminologyProvider.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/Dstu3FhirTerminologyProvider.kt new file mode 100644 index 0000000000000000000000000000000000000000..8862587f11311192da864bfe251bbbe1ec04cb28 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/Dstu3FhirTerminologyProvider.kt @@ -0,0 +1,200 @@ +package org.opencds.cqf.cql.engine.fhir.terminology + +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException +import org.hl7.fhir.dstu3.model.BooleanType +import org.hl7.fhir.dstu3.model.Bundle +import org.hl7.fhir.dstu3.model.CodeSystem +import org.hl7.fhir.dstu3.model.CodeType +import org.hl7.fhir.dstu3.model.IdType +import org.hl7.fhir.dstu3.model.Parameters +import org.hl7.fhir.dstu3.model.StringType +import org.hl7.fhir.dstu3.model.UriType +import org.hl7.fhir.dstu3.model.ValueSet +import org.hl7.fhir.instance.model.api.IBaseBundle +import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator +import org.opencds.cqf.cql.engine.exception.TerminologyProviderException +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.toCqlString +import org.opencds.cqf.cql.engine.terminology.CodeSystemInfo +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider +import org.opencds.cqf.cql.engine.terminology.ValueSetInfo + +class Dstu3FhirTerminologyProvider(private val fhirClient: IGenericClient) : TerminologyProvider { + override fun `in`(code: Code, valueSet: ValueSetInfo): Boolean { + if (code.system == null) { + // If the system is not provided and the resolved value set contains codes from multiple + // code systems, a run-time error is thrown because the operation is ambiguous + val codes = expand(valueSet) + if (codes.distinctBy { it.system }.size > 1) { + throw TerminologyProviderException( + @Suppress("MaxLineLength") + "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" + ) + } + return codes.any { + EquivalentEvaluator.equivalent(code.code?.toCqlString(), it.code?.toCqlString()) == + org.opencds.cqf.cql.engine.runtime.Boolean.TRUE + } + } + try { + val id = resolveValueSetId(valueSet) + val respParam = + fhirClient + .operation() + .onInstance(IdType(VALUE_SET, id)) // .onType(ValueSet.class) + .named("validate-code") + .withParameter(Parameters::class.java, "code", StringType(code.code)) + .andParameter("system", StringType(code.system)) + .useHttpGet() + .execute() + return (respParam.getParameter()[0].getValue() as BooleanType).booleanValue() + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}", + e, + ) + } + } + + override fun expand(valueSet: ValueSetInfo): Iterable { + try { + val id = resolveValueSetId(valueSet) + val respParam = + fhirClient + .operation() + .onInstance(IdType(VALUE_SET, id)) + .named("expand") + .withNoParameters(Parameters::class.java) + .useHttpGet() + .execute() + + val expanded = respParam.getParameter()[0].getResource() as ValueSet + val codes = mutableListOf() + for (codeInfo in expanded.getExpansion().getContains()) { + val nextCode = + Code() + .withCode(codeInfo.getCode()) + .withSystem(codeInfo.getSystem()) + .withVersion(codeInfo.getVersion()) + .withDisplay(codeInfo.getDisplay()) + codes.add(nextCode) + } + return codes + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing expansion of ValueSet: ${valueSet.id}", + e, + ) + } + } + + override fun lookup(code: Code, codeSystem: CodeSystemInfo): Code { + try { + val respParam = + fhirClient + .operation() + .onType(CodeSystem::class.java) + .named("lookup") + .withParameter(Parameters::class.java, "code", CodeType(code.code)) + .andParameter("system", UriType(codeSystem.id)) + .execute() + + val display = + respParam + .getParameter() + .stream() + .filter { x: Parameters.ParametersParameterComponent? -> + x!!.getName() == "display" + } + .findFirst() + if (display.isPresent) { + code.withDisplay(display.get().getValue().toString()) + } + + return code.withSystem(codeSystem.id) + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing lookup of Code: $code in CodeSystem: ${codeSystem.id}", + e, + ) + } + } + + private fun searchByUrl(url: String?): Bundle { + return fhirClient + .search() + .forResource(ValueSet::class.java) + .where(ValueSet.URL.matches().value(url)) + .returnBundle(Bundle::class.java) + .execute() + } + + private fun searchByIdentifier(identifier: String?): Bundle { + return fhirClient + .search() + .forResource(ValueSet::class.java) + .where(ValueSet.IDENTIFIER.exactly().code(identifier)) + .returnBundle(Bundle::class.java) + .execute() + } + + private fun searchById(id: String): Bundle { + var id = id + if (id.startsWith(URN_OID)) { + id = id.replace(URN_OID, "") + } else if (id.startsWith(URN_UUID)) { + id = id.replace(URN_UUID, "") + } + val searchResults = Bundle() + // If we reached this point, and it looks like it might + // be a FHIR resource ID, we will try to read it. + // See https://www.hl7.org/fhir/datatypes.html#id + if (id.matches("[A-Za-z0-9\\-\\.]{1,64}".toRegex())) { + try { + val vs = fhirClient.read().resource(ValueSet::class.java).withId(id).execute() + searchResults.addEntry().setResource(vs) + } catch (rnfe: ResourceNotFoundException) { + // intentionally empty + } + } + + return searchResults + } + + fun resolveValueSetId(valueSet: ValueSetInfo): String? { + if ( + valueSet.version != null || + (valueSet.codeSystems != null && !valueSet.codeSystems!!.isEmpty()) + ) { + throw UnsupportedOperationException( + "Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time." + ) + } + + // https://github.com/DBCG/cql_engine/pull/462 - Use a search path of URL, + // identifier, and then resource id + var searchResults = searchByUrl(valueSet.id) + if (!searchResults.hasEntry()) { + searchResults = searchByIdentifier(valueSet.id) + } + + if (!searchResults.hasEntry()) { + searchResults = searchById(valueSet.id!!) + } + + require(!(!searchResults.hasEntry() || searchResults.getEntry().isEmpty())) { + "Could not resolve value set ${valueSet.id}." + } + require(searchResults.getEntry().size <= 1) { + "Found more than 1 ValueSet with url: " + valueSet.id + } + return searchResults.entryFirstRep.getResource().idElement.idPart + } + + companion object { + private const val URN_UUID = "urn:uuid:" + private const val URN_OID = "urn:oid:" + private const val VALUE_SET = "ValueSet" + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/HeaderInjectionInterceptor.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/HeaderInjectionInterceptor.kt new file mode 100644 index 0000000000000000000000000000000000000000..fb24389a779e9f89487c326fcb520ef453eb8d3b --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/HeaderInjectionInterceptor.kt @@ -0,0 +1,34 @@ +/* + * + * This code is derived from work done by Barry Cassidy from Motive Medical Intelligence + * Thank you! + * + * */ +package org.opencds.cqf.cql.engine.fhir.terminology + +import ca.uhn.fhir.rest.client.api.IClientInterceptor +import ca.uhn.fhir.rest.client.api.IHttpRequest +import ca.uhn.fhir.rest.client.api.IHttpResponse +import java.io.IOException + +class HeaderInjectionInterceptor(private val headers: Map = mapOf()) : + IClientInterceptor { + /** + * Instantiates a new header injection interception. + * + * @param headerKey the header key + * @param headerValue the header value + */ + constructor(headerKey: String, headerValue: String) : this(mapOf(headerKey to headerValue)) + + override fun interceptRequest(request: IHttpRequest) { + for (entry in this.headers.entries) { + request.addHeader(entry.key, entry.value) + } + } + + @Throws(IOException::class) + override fun interceptResponse(response: IHttpResponse?) { + // nothing + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/R4FhirTerminologyProvider.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/R4FhirTerminologyProvider.kt new file mode 100644 index 0000000000000000000000000000000000000000..018f46a8c2d7ceecbc5159b11cc0d1279b9758aa --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmMain/kotlin/org/opencds/cqf/cql/engine/fhir/terminology/R4FhirTerminologyProvider.kt @@ -0,0 +1,197 @@ +package org.opencds.cqf.cql.engine.fhir.terminology + +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException +import org.hl7.fhir.instance.model.api.IBaseBundle +import org.hl7.fhir.r4.model.BooleanType +import org.hl7.fhir.r4.model.Bundle +import org.hl7.fhir.r4.model.CodeSystem +import org.hl7.fhir.r4.model.CodeType +import org.hl7.fhir.r4.model.IdType +import org.hl7.fhir.r4.model.Parameters +import org.hl7.fhir.r4.model.StringType +import org.hl7.fhir.r4.model.UriType +import org.hl7.fhir.r4.model.ValueSet +import org.opencds.cqf.cql.engine.elm.executing.EquivalentEvaluator +import org.opencds.cqf.cql.engine.exception.TerminologyProviderException +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.toCqlString +import org.opencds.cqf.cql.engine.terminology.CodeSystemInfo +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider +import org.opencds.cqf.cql.engine.terminology.ValueSetInfo + +/** + * @param fhirClient - an IGenericClient that has endpoint and authentication already defined and + * set. + */ +class R4FhirTerminologyProvider(val fhirClient: IGenericClient) : TerminologyProvider { + override fun `in`(code: Code, valueSet: ValueSetInfo): Boolean { + if (code.system == null) { + // If the system is not provided and the resolved value set contains codes from multiple + // code systems, a run-time error is thrown because the operation is ambiguous + val codes = expand(valueSet) + if (codes.distinctBy { it.system }.size > 1) { + throw TerminologyProviderException( + @Suppress("MaxLineLength") + "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" + ) + } + return codes.any { + EquivalentEvaluator.equivalent(code.code?.toCqlString(), it.code?.toCqlString()) == + org.opencds.cqf.cql.engine.runtime.Boolean.TRUE + } + } + try { + val id = resolveValueSetId(valueSet) + val respParam = + fhirClient + .operation() + .onInstance(IdType(VALUE_SET, id)) // .onType(ValueSet.class) + .named("validate-code") + .withParameter(Parameters::class.java, "code", StringType(code.code)) + .andParameter("system", StringType(code.system)) + .useHttpGet() + .execute() + return (respParam.getParameter()[0].getValue() as BooleanType).booleanValue() + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing membership check of Code: $code in ValueSet: ${valueSet.id}", + e, + ) + } + } + + override fun expand(valueSet: ValueSetInfo): Iterable { + try { + val id = resolveValueSetId(valueSet) + val respParam = + fhirClient + .operation() + .onInstance(IdType(VALUE_SET, id)) + .named("expand") + .withNoParameters(Parameters::class.java) + .useHttpGet() + .execute() + + val expanded = respParam.getParameter()[0].getResource() as ValueSet + val codes = mutableListOf() + for (codeInfo in expanded.getExpansion().getContains()) { + val nextCode = + Code() + .withCode(codeInfo.getCode()) + .withSystem(codeInfo.getSystem()) + .withVersion(codeInfo.getVersion()) + .withDisplay(codeInfo.getDisplay()) + codes.add(nextCode) + } + return codes + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing expansion of ValueSet: ${valueSet.id}", + e, + ) + } + } + + override fun lookup(code: Code, codeSystem: CodeSystemInfo): Code { + try { + val respParam = + fhirClient + .operation() + .onType(CodeSystem::class.java) + .named("lookup") + .withParameter(Parameters::class.java, "code", CodeType(code.code)) + .andParameter("system", UriType(codeSystem.id)) + .execute() + + val display = respParam.getParameter("display").getValue() as StringType? + if (display != null) { + code.withDisplay(display.value) + } + + return code.withSystem(codeSystem.id) + } catch (e: Exception) { + throw TerminologyProviderException( + "Error performing lookup of Code: $code in CodeSystem: ${codeSystem.id}", + e, + ) + } + } + + private fun searchByUrl(url: String?): Bundle { + return fhirClient + .search() + .forResource(ValueSet::class.java) + .where(ValueSet.URL.matches().value(url)) + .returnBundle(Bundle::class.java) + .execute() + } + + private fun searchByIdentifier(identifier: String?): Bundle { + return fhirClient + .search() + .forResource(ValueSet::class.java) + .where(ValueSet.IDENTIFIER.exactly().code(identifier)) + .returnBundle(Bundle::class.java) + .execute() + } + + private fun searchById(id: String): Bundle { + var id = id + if (id.startsWith(URN_OID)) { + id = id.replace(URN_OID, "") + } else if (id.startsWith(URN_UUID)) { + id = id.replace(URN_UUID, "") + } + val searchResults = Bundle() + // If we reached this point and it looks like it might + // be a FHIR resource ID, we will try to read it. + // See https://www.hl7.org/fhir/datatypes.html#id + if (id.matches("[A-Za-z0-9\\-\\.]{1,64}".toRegex())) { + try { + val vs = fhirClient.read().resource(ValueSet::class.java).withId(id).execute() + searchResults.addEntry().setResource(vs) + } catch (rnfe: ResourceNotFoundException) { + // intentionally empty + } + } + + return searchResults + } + + fun resolveValueSetId(valueSet: ValueSetInfo): String? { + if ( + valueSet.version != null || + (valueSet.codeSystems != null && !valueSet.codeSystems!!.isEmpty()) + ) { + throw UnsupportedOperationException( + "Could not expand value set ${valueSet.id}; version and code system bindings are not supported at this time." + ) + } + + // https://github.com/DBCG/cql_engine/pull/462 - Use a search path of URL, + // identifier, and then resource id + var searchResults = searchByUrl(valueSet.id) + if (!searchResults.hasEntry()) { + searchResults = searchByIdentifier(valueSet.id) + } + + if (!searchResults.hasEntry()) { + searchResults = searchById(valueSet.id!!) + } + + require(!(!searchResults.hasEntry() || searchResults.getEntry().isEmpty())) { + "Could not resolve value set ${valueSet.id}." + } + require(searchResults.getEntry().size <= 1) { + "Found more than 1 ValueSet with url: " + valueSet.id + } + return searchResults.entryFirstRep.getResource().idElement.idPart + } + + companion object { + private const val URN_UUID = "urn:uuid:" + private const val URN_OID = "urn:oid:" + private const val VALUE_SET = "ValueSet" + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsDstu3Test.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsDstu3Test.kt new file mode 100644 index 0000000000000000000000000000000000000000..4e94f4c4242e08d3f9dc406c860fb35422c966c4 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsDstu3Test.kt @@ -0,0 +1,166 @@ +package org.hl7.fhirpath + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import com.google.common.collect.Sets +import org.hl7.fhirpath.tests.Group +import org.hl7.fhirpath.tests.Test +import org.junit.jupiter.api.Assumptions +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource +import org.opencds.cqf.cql.engine.data.CompositeDataProvider +import org.opencds.cqf.cql.engine.fhir.model.CachedDstu3FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.model.Dstu3FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver + +class CQLOperationsDstu3Test : TestFhirPath() { + @ParameterizedTest(name = "{0}") + @MethodSource("dataMethod") + fun test(name: String, test: Test) { + Assumptions.assumeFalse(SKIP.contains(name), "Skipping $name") + runTest(test, "stu3/input/", fhirContext, provider, fhirModelResolver) + runTest(test, "stu3/input/", fhirContext, provider, fhirModelResolver) + } + + companion object { + private val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.DSTU3) + private val fhirModelResolver: Dstu3FhirModelResolver = CachedDstu3FhirModelResolver() + private val retrieveProvider = + RestFhirRetrieveProvider( + SearchParameterResolver(fhirContext), + fhirModelResolver, + fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"), + ) + private val provider = CompositeDataProvider(fhirModelResolver, retrieveProvider) + + @JvmStatic + fun dataMethod(): Array> { + val listOfFiles = arrayOf("stu3/tests-fhir-r3.xml") + + val testsToRun: MutableList> = ArrayList() + for (file in listOfFiles) { + for (group in loadTestsFile(file)!!.getGroup()) { + for (test in group.getTest()) { + if ("2.1.0" != test.getVersion()) { // unsupported version + val name: String = getTestName(file, group, test) + testsToRun.add(arrayOf(name, test)) + } + } + } + } + return testsToRun.toTypedArray() + } + + var SKIP: MutableSet = + Sets.newHashSet( + "stu3/tests-fhir-r3/Dollar/testDollarOrderNotAllowed(Patient.children().skip(1))", + $$"stu3/tests-fhir-r3/Dollar/testDollarThis1(Patient.name.given.where(substring($this.length()-3) = 'out'))", + $$"stu3/tests-fhir-r3/Dollar/testDollarThis2(Patient.name.given.where(substring($this.length()-3) = 'ter'))", + "stu3/tests-fhir-r3/Literals/testLiteralDate((0).not() = false)", + "stu3/tests-fhir-r3/Literals/testLiteralDate((1).not() = false)", + "stu3/tests-fhir-r3/Literals/testLiteralDate((1|2).not() = false)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00+10:00)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00-10:00)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @1974-12-25T12:34:00Z)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @T12:14)", + "stu3/tests-fhir-r3/Literals/testLiteralDate(Patient.birthDate != @T12:14:15)", + "stu3/tests-fhir-r3/Literals/testLiteralDecimal(Observation.value.value < 190)", + "stu3/tests-fhir-r3/Literals/testLiteralDecimal(Observation.value.value > 0)", + "stu3/tests-fhir-r3/Literals/testLiteralString(Patient.name.given.first() = 'Peter')", + "stu3/tests-fhir-r3/Literals/testLiteralUnicode(Patient.name.given.first() = 'P\\u0065ter')", + "stu3/tests-fhir-r3/testAll(Patient.name.select(family.exists()).all())", + "stu3/tests-fhir-r3/testAll(Patient.name.select(given.exists()).all())", + "stu3/tests-fhir-r3/testBooleanImplies((true implies {}) = {})", + "stu3/tests-fhir-r3/testBooleanImplies(({} implies false) = true)", + "stu3/tests-fhir-r3/testBooleanImplies(({} implies {}) = true)", + "stu3/tests-fhir-r3/testBooleanLogicAnd((true and {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicAnd(({} and true) = {})", + "stu3/tests-fhir-r3/testBooleanLogicAnd(({} and {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicOr((false or {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicOr(({} or false) = {})", + "stu3/tests-fhir-r3/testBooleanLogicOr(({} or {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicXOr((false xor {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicXOr((true xor {}) = {})", + "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor false) = {})", + "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor true) = {})", + "stu3/tests-fhir-r3/testBooleanLogicXOr(({} xor {}) = {})", + "stu3/tests-fhir-r3/testConcatenate((1 | 2 | 3) & 'b' = '1,2,3b')", + "stu3/tests-fhir-r3/testConcatenate(1 & 'a' = '1a')", + "stu3/tests-fhir-r3/testConcatenate(1 & 1 = '11')", + "stu3/tests-fhir-r3/testContainsString('12345'.contains('') = false)", + "stu3/tests-fhir-r3/testDistinct((1 | 2 | 3).isDistinct())", + "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.distinct())", + "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.isDistinct())", + "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).distinct())", + "stu3/tests-fhir-r3/testDistinct(Questionnaire.descendants().linkId.select(substring(0,1)).isDistinct().not())", + "stu3/tests-fhir-r3/testDivide(1.2 / 1.8 = 0.67)", + "stu3/tests-fhir-r3/testEndsWith('12345'.endsWith('') = false)", + "stu3/tests-fhir-r3/testEquality(0.0 = 0)", + "stu3/tests-fhir-r3/testEquality(1.10 = 1.1)", + "stu3/tests-fhir-r3/testEquality(name = name.first() | name.last())", + "stu3/tests-fhir-r3/testEquality(name = name.last() | name.first())", + "stu3/tests-fhir-r3/testEquivalent(@2012-04-15 ~ @2012-04-15T10:00:00)", + "stu3/tests-fhir-r3/testEquivalent(name.given ~ name.first().given | name.last().given)", + "stu3/tests-fhir-r3/testEquivalent(name.given ~ name.last().given | name.first().given)", + "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension(%\"ext-patient-birthTime\").exists())", + "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime').exists())", + "stu3/tests-fhir-r3/testExtension(Patient.birthDate.extension('http://hl7.org/fhir/StructureDefinition/patient-birthTime1').empty())", + "stu3/tests-fhir-r3/testFirstLast(Patient.name.first().given = 'Peter' | 'James')", + "stu3/tests-fhir-r3/testFirstLast(Patient.name.last().given = 'Jim')", + "stu3/tests-fhir-r3/testIif(iif(Patient.name.empty(), 'unnamed', 'named') = 'named')", + "stu3/tests-fhir-r3/testIif(iif(Patient.name.exists(), 'named', 'unnamed') = 'named')", + "stu3/tests-fhir-r3/testIndexer(Patient.name[0].given = 'Peter' | 'James')", + "stu3/tests-fhir-r3/testIndexer(Patient.name[1].given = 'Jim')", + "stu3/tests-fhir-r3/testNEquality(0.0 != 0)", + "stu3/tests-fhir-r3/testNEquality(1.10 != 1.1)", + "stu3/tests-fhir-r3/testNEquality(name != name.first() | name.last())", + "stu3/tests-fhir-r3/testNEquality(name != name.last() | name.first())", + "stu3/tests-fhir-r3/testNotEquivalent(@2012-04-15 !~ @2012-04-15T10:00:00)", + "stu3/tests-fhir-r3/testNotEquivalent(name.given !~ name.first().given | name.last().given)", + "stu3/tests-fhir-r3/testNotEquivalent(name.given !~ name.last().given | name.first().given)", + "stu3/tests-fhir-r3/testNow(now().toString().length() > 10)", + "stu3/tests-fhir-r3/testNow(Patient.birthDate < now())", + "stu3/tests-fhir-r3/testRepeat(Questionnaire.children().concept.count() = 2)", + "stu3/tests-fhir-r3/testRepeat(Questionnaire.descendants().concept.count() = 10)", + "stu3/tests-fhir-r3/testRepeat(Questionnaire.repeat(item).concept.count() = 10)", + "stu3/tests-fhir-r3/testRepeat(ValueSet.expansion.repeat(contains).count() = 10)", + "stu3/tests-fhir-r3/testSelect(Patient.name.select(given) = 'Peter' | 'James' | 'Jim')", + "stu3/tests-fhir-r3/testSelect(Patient.name.select(given | family) = 'Peter' | 'James' | 'Chalmers' | 'Jim')", + "stu3/tests-fhir-r3/testSkip((0 | 1 | 2).skip(1) = 1 | 2)", + "stu3/tests-fhir-r3/testSkip(Patient.name.skip(1).given = 'Jim')", + "stu3/tests-fhir-r3/testStartsWith('12345'.startsWith('') = false)", + $$"stu3/tests-fhir-r3/testSubSetOf(Patient.name.first().subsetOf($this.name))", + $$"stu3/tests-fhir-r3/testSubSetOf(Patient.name.subsetOf($this.name.first()).not())", + $$"stu3/tests-fhir-r3/testSuperSetOf(Patient.name.first().supersetOf($this.name).not())", + $$"stu3/tests-fhir-r3/testSuperSetOf(Patient.name.supersetOf($this.name.first()))", + "stu3/tests-fhir-r3/testTail((0 | 1 | 2).tail() = 1 | 2)", + "stu3/tests-fhir-r3/testTail(Patient.name.tail().given = 'Jim')", + "stu3/tests-fhir-r3/testTake((0 | 1 | 2).take(2) = 0 | 1)", + "stu3/tests-fhir-r3/testTake(Patient.name.take(1).given = 'Peter' | 'James')", + "stu3/tests-fhir-r3/testTake(Patient.name.take(2).given = 'Peter' | 'James' | 'Jim')", + "stu3/tests-fhir-r3/testTake(Patient.name.take(3).given = 'Peter' | 'James' | 'Jim')", + "stu3/tests-fhir-r3/testToday(Patient.birthDate < today())", + "stu3/tests-fhir-r3/testToday(today().toString().length() = 10)", + "stu3/tests-fhir-r3/testToInteger('0.0'.toInteger().empty())", + "stu3/tests-fhir-r3/testVariables(%\"vs-administrative-gender\" = 'http://hl7.org/fhir/ValueSet/administrative-gender')", + "stu3/tests-fhir-r3/testVariables(%loinc = 'http://loinc.org')", + "stu3/tests-fhir-r3/testVariables(%sct = 'http://snomed.info/sct')", + "stu3/tests-fhir-r3/testVariables(%ucum = 'http://unitsofmeasure.org')", + $$"stu3/tests-fhir-r3/testWhere(Patient.name.where($this.given = 'Jim').count() = 1)", + "stu3/tests-fhir-r3/testWhere(Patient.name.where(given = 'Jim').count() = 1)", + "stu3/tests-fhir-r3/testWhere(Patient.name.where(given = 'X').count() = 0)", + ) + + fun getTestName(file: String, group: Group, test: Test): String { + return (file.replace(".xml", "") + + "/" + + group.getName() + + (if (test.getName() != null) "/" + test.getName() else "") + + "(" + + test.getExpression().getValue() + + ")") + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsR4Test.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsR4Test.kt new file mode 100644 index 0000000000000000000000000000000000000000..7297c5c365e25a27626d6e199a8dcf605efb1d8b --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/CQLOperationsR4Test.kt @@ -0,0 +1,253 @@ +package org.hl7.fhirpath + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import com.google.common.collect.Sets +import org.hl7.fhirpath.tests.Group +import org.hl7.fhirpath.tests.Test +import org.junit.jupiter.api.Assumptions +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource +import org.opencds.cqf.cql.engine.data.CompositeDataProvider +import org.opencds.cqf.cql.engine.fhir.model.CachedR4FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.model.R4FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver + +class CQLOperationsR4Test : TestFhirPath() { + @ParameterizedTest(name = "{0}") + @MethodSource("dataMethod") + fun test(name: String, test: Test) { + Assumptions.assumeFalse(SKIP.contains(name), "Skipping $name") + runTest(test, "r4/input/", fhirContext, provider, fhirModelResolver) + } + + companion object { + private val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.R4) + private val fhirModelResolver: R4FhirModelResolver = CachedR4FhirModelResolver() + private val retrieveProvider = + RestFhirRetrieveProvider( + SearchParameterResolver(fhirContext), + fhirModelResolver, + fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseR4"), + ) + private val provider = CompositeDataProvider(fhirModelResolver, retrieveProvider) + + @JvmStatic + fun dataMethod(): Array> { + val listOfFiles = + arrayOf( + "r4/tests-fhir-r4.xml", + "cql/CqlAggregateFunctionsTest.xml", + "cql/CqlAggregateTest.xml", + "cql/CqlArithmeticFunctionsTest.xml", + "cql/CqlComparisonOperatorsTest.xml", + "cql/CqlConditionalOperatorsTest.xml", + "cql/CqlDateTimeOperatorsTest.xml", + "cql/CqlErrorsAndMessagingOperatorsTest.xml", + "cql/CqlIntervalOperatorsTest.xml", + "cql/CqlListOperatorsTest.xml", + "cql/CqlLogicalOperatorsTest.xml", + "cql/CqlNullologicalOperatorsTest.xml", + "cql/CqlStringOperatorsTest.xml", + "cql/CqlTypeOperatorsTest.xml", + "cql/CqlTypesTest.xml", + "cql/ValueLiteralsAndSelectors.xml", + ) + + val testsToRun: MutableList> = ArrayList() + for (file in listOfFiles) { + for (group in loadTestsFile(file)!!.getGroup()) { + for (test in group.getTest()) { + if ("2.1.0" != test.getVersion()) { // unsupported version + val name: String = getTestName(file, group, test) + testsToRun.add(arrayOf(name, test)) + } + } + } + } + return testsToRun.toTypedArray() + } + + var SKIP: MutableSet = + Sets.newHashSet( + "cql/CqlAggregateTest/AggregateTests/RolledOutIntervals", + "cql/CqlArithmeticFunctionsTest/Ln/Ln1000D", + "cql/CqlArithmeticFunctionsTest/Ln/Ln1000", + "cql/CqlDateTimeOperatorsTest/Duration/DateTimeDurationBetweenYear", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainAdd", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainInterval", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainInterval2", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainMultiply", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DateTimeDurationBetweenUncertainSubtract", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DurationInDaysA", + "cql/CqlDateTimeOperatorsTest/Uncertainty tests/DurationInDaysAA", + "cql/CqlIntervalOperatorsTest/Intersect/TestIntersectNull", + "cql/CqlIntervalOperatorsTest/Expand/ExpandPer0D1", + "cql/CqlIntervalOperatorsTest/Expand/ExpandPer0D1IntervalOverload", + "cql/CqlListOperatorsTest/Equal/EqualABCAnd123", + "cql/CqlListOperatorsTest/Equal/Equal123AndABC", + "cql/CqlListOperatorsTest/Equal/Equal123AndString123", + "cql/CqlListOperatorsTest/Equivalent/Equivalent123AndABC", + "cql/CqlListOperatorsTest/Equivalent/Equivalent123AndString123", + "cql/CqlListOperatorsTest/Equivalent/EquivalentABCAnd123", + "cql/CqlListOperatorsTest/NotEqual/NotEqual123AndABC", + "cql/CqlListOperatorsTest/NotEqual/NotEqual123AndString123", + "cql/CqlListOperatorsTest/NotEqual/NotEqualABCAnd123", + "cql/CqlListOperatorsTest/ProperlyIncludedIn/ProperlyIncludedInNulRight", + "cql/CqlListOperatorsTest/ProperlyIncludes/ProperlyIncludesNullLeft", + "cql/CqlListOperatorsTest/Union/UnionListNullAndListNull", + "cql/CqlStringOperatorsTest/toString tests/DateTimeToString3", + "cql/CqlTypeOperatorsTest/As/AsQuantity", + "cql/CqlTypeOperatorsTest/As/CastAsQuantity", + "cql/CqlTypeOperatorsTest/ToTime/ToTime2", + "cql/CqlTypeOperatorsTest/ToTime/ToTime3", + "cql/CqlTypeOperatorsTest/ToTime/ToTime4", + "cql/CqlTypesTest/DateTime/DateTimeUncertain", + "cql/CqlTypesTest/Time/TimeUpperBoundMillis", + "cql/ValueLiteralsAndSelectors/Decimal/Decimal10Pow20", + "cql/ValueLiteralsAndSelectors/Decimal/DecimalNeg10Pow20", + "cql/ValueLiteralsAndSelectors/Decimal/DecimalNegTenthStep", + "cql/ValueLiteralsAndSelectors/Decimal/DecimalPos10Pow20", + "cql/ValueLiteralsAndSelectors/Decimal/DecimalPosTenthStep", + "cql/ValueLiteralsAndSelectors/Decimal/DecimalTenthStep", + "r4/tests-fhir-r4/from-Zulip/(true and 'foo').empty()", + "r4/tests-fhir-r4/from-Zulip/(true | 'foo').allTrue()", + "r4/tests-fhir-r4/testAggregate/testAggregate1", + "r4/tests-fhir-r4/testAggregate/testAggregate2", + "r4/tests-fhir-r4/testAggregate/testAggregate3", + "r4/tests-fhir-r4/testAggregate/testAggregate4", + "r4/tests-fhir-r4/testAll/testAllTrue4", + "r4/tests-fhir-r4/testBasics/testIdentifierContext", + "r4/tests-fhir-r4/testBasics/testIdentifierContextIsNotResource", + "r4/tests-fhir-r4/testBasics/testContainerAccess", + "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean2", + "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean3", + "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean4", + "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean5", + "r4/tests-fhir-r4/testCollectionBoolean/testCollectionBoolean6", + "r4/tests-fhir-r4/testConformsTo/testConformsTo1", + "r4/tests-fhir-r4/testConformsTo/testConformsTo2", + "r4/tests-fhir-r4/testDistinct/testDistinct1", + "r4/tests-fhir-r4/testDistinct/testDistinct2", + "r4/tests-fhir-r4/testDistinct/testDistinct3", + "r4/tests-fhir-r4/testDistinct/testDistinct5", + "r4/tests-fhir-r4/testDistinct/testDistinct6", + "r4/tests-fhir-r4/testDollar/testDollarOrderNotAllowed", + "r4/tests-fhir-r4/testEquality/testEquality19", + "r4/tests-fhir-r4/testEquality/testEquality21", + "r4/tests-fhir-r4/testEquality/testEquality22", + "r4/tests-fhir-r4/testEquality/testEquality23", + "r4/tests-fhir-r4/testEquivalent/testEquivalent11", + "r4/tests-fhir-r4/testEquivalent/testEquivalent17", + "r4/tests-fhir-r4/testEquivalent/testEquivalent21", + "r4/tests-fhir-r4/testExclude/testExclude4", + "r4/tests-fhir-r4/testExtension/testExtension1", + "r4/tests-fhir-r4/testExtension/testExtension2", + "r4/tests-fhir-r4/testExtension/testExtension3", + "r4/tests-fhir-r4/testGreaterThan/testGreaterThan26", + "r4/tests-fhir-r4/testGreaterThan/testGreaterThan27", + "r4/tests-fhir-r4/testGreatorOrEqual/testGreatorOrEqual26", + "r4/tests-fhir-r4/testGreatorOrEqual/testGreatorOrEqual27", + "r4/tests-fhir-r4/testIif/testIif1", + "r4/tests-fhir-r4/testIif/testIif2", + "r4/tests-fhir-r4/testIif/testIif3", + "r4/tests-fhir-r4/testIif/testIif4", + "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)", + "r4/tests-fhir-r4/testLessOrEqual/testLessOrEqual26", + "r4/tests-fhir-r4/testLessOrEqual/testLessOrEqual27", + "r4/tests-fhir-r4/testLessThan/testLessThan26", + "r4/tests-fhir-r4/testLessThan/testLessThan27", + "r4/tests-fhir-r4/testLiterals/testDateGreaterThanDate", + "r4/tests-fhir-r4/testLiterals/testDateNotEqual", + "r4/tests-fhir-r4/testLiterals/testDateNotEqualTimeMinute", + "r4/tests-fhir-r4/testLiterals/testDateNotEqualTimeSecond", + "r4/tests-fhir-r4/testLiterals/testDateNotEqualToday", + "r4/tests-fhir-r4/testLiterals/testDateTimeGreaterThanDate1", + "r4/tests-fhir-r4/testLiterals/testDateTimeGreaterThanDate2", + "r4/tests-fhir-r4/testLiterals/testLiteralDateTimeTZGreater", + "r4/tests-fhir-r4/testLiterals/testLiteralDateTimeTZLess", + "r4/tests-fhir-r4/testLiterals/testLiteralDecimalGreaterThanIntegerTrue", + "r4/tests-fhir-r4/testLiterals/testLiteralDecimalLessThanInteger", + "r4/tests-fhir-r4/testLiterals/testLiteralDecimalLessThanInvalid", + "r4/tests-fhir-r4/testMatches/testMatchesSingleLineMode1", + "r4/tests-fhir-r4/testMatches/testMatchesWithinUrl1", + "r4/tests-fhir-r4/testNEquality/testNEquality13", + "r4/tests-fhir-r4/testNEquality/testNEquality15", + "r4/tests-fhir-r4/testNEquality/testNEquality16", + "r4/tests-fhir-r4/testNEquality/testNEquality17", + "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent13", + "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent17", + "r4/tests-fhir-r4/testNotEquivalent/testNotEquivalent21", + "r4/tests-fhir-r4/testObservations/testPolymorphismIsA3", // The engine returns + // false but the test + // expects null. + "r4/tests-fhir-r4/testPower/testPower3", + "r4/tests-fhir-r4/testPrecedence/testPrecedence3", + "r4/tests-fhir-r4/testPrecedence/testPrecedence4", + "r4/tests-fhir-r4/testQuantity/testQuantity5", + "r4/tests-fhir-r4/testQuantity/testQuantity6", + "r4/tests-fhir-r4/testQuantity/testQuantity7", + "r4/tests-fhir-r4/testQuantity/testQuantity8", + "r4/tests-fhir-r4/testRepeat/testRepeat1", + "r4/tests-fhir-r4/testRepeat/testRepeat2", + "r4/tests-fhir-r4/testRepeat/testRepeat3", + "r4/tests-fhir-r4/testRepeat/testRepeat4", + "r4/tests-fhir-r4/testSelect/testSelect1", + "r4/tests-fhir-r4/testSingle/testSingle2", + "r4/tests-fhir-r4/testSqrt/testSqrt2", + "r4/tests-fhir-r4/testSubSetOf/testSubSetOf1", + "r4/tests-fhir-r4/testSubSetOf/testSubSetOf2", + "r4/tests-fhir-r4/testSuperSetOf/testSuperSetOf1", + "r4/tests-fhir-r4/testSuperSetOf/testSuperSetOf2", + "r4/tests-fhir-r4/testTimeOfDay/testTimeOfDay1", + "r4/tests-fhir-r4/testToChars/testToChars1", + "r4/tests-fhir-r4/testToInteger/testToInteger4", + "r4/tests-fhir-r4/testTrace/testTrace2", + "r4/tests-fhir-r4/testType/testType1", + "r4/tests-fhir-r4/testType/testType2", + "r4/tests-fhir-r4/testType/testType3", + "r4/tests-fhir-r4/testType/testType4", + "r4/tests-fhir-r4/testType/testType6", + "r4/tests-fhir-r4/testType/testType9", + "r4/tests-fhir-r4/testType/testType10", + "r4/tests-fhir-r4/testType/testType13", + "r4/tests-fhir-r4/testType/testType14", + "r4/tests-fhir-r4/testType/testType15", + "r4/tests-fhir-r4/testType/testType16", + "r4/tests-fhir-r4/testType/testType18", + "r4/tests-fhir-r4/testType/testType19", + "r4/tests-fhir-r4/testType/testType20", + "r4/tests-fhir-r4/testType/testType21", + "r4/tests-fhir-r4/testType/testType22", + "r4/tests-fhir-r4/testType/testType23", + "r4/tests-fhir-r4/testTypes/testBooleanLiteralConvertsToQuantity", + "r4/tests-fhir-r4/testTypes/testBooleanLiteralIsNotSystemQuantity", + "r4/tests-fhir-r4/testTypes/testDecimalLiteralIsNotQuantity", + "r4/tests-fhir-r4/testTypes/testDecimalLiteralToDecimal", + "r4/tests-fhir-r4/testTypes/testDecimalLiteralToIntegerIsEmpty", + "r4/tests-fhir-r4/testTypes/testIntegerLiteralIsSystemInteger", + "r4/tests-fhir-r4/testTypes/testIntegerLiteralToInteger", + "r4/tests-fhir-r4/testTypes/testQuantityLiteralWeekToString", + "r4/tests-fhir-r4/testTypes/testStringDecimalLiteralIsNotSystemQuantity", + "r4/tests-fhir-r4/testTypes/testStringIntegerLiteralIsNotQuantity", + "r4/tests-fhir-r4/testTypes/testStringLiteralToString", + "r4/tests-fhir-r4/testTypes/testStringQuantityWeekConvertsToQuantityFalse", + "r4/tests-fhir-r4/testVariables/testVariables1", + "r4/tests-fhir-r4/testVariables/testVariables2", + "r4/tests-fhir-r4/testVariables/testVariables3", + "r4/tests-fhir-r4/testVariables/testVariables4", + "r4/tests-fhir-r4/testWhere/testWhere2", + "r4/tests-fhir-r4/testWhere/testWhere3", + "r4/tests-fhir-r4/testWhere/testWhere4", + ) + + fun getTestName(file: String, group: Group, test: Test): String { + return (file.replace(".xml", "") + + "/" + + group.getName() + + "/" + + (if (test.getName() != null) test.getName() else test.getExpression().getValue())) + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/DateTypeTest.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/DateTypeTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..dcb19280a7920379ab0ce35c045a7fae1f11f494 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/DateTypeTest.kt @@ -0,0 +1,29 @@ +package org.hl7.fhirpath + +import java.util.* +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.hl7.fhir.r4.model.DateType +import org.junit.jupiter.api.Test + +internal class DateTypeTest { + @Test + fun dateType() { + // DateType Month is zero-based (11 == December) + val birthDate = DateType(1974, 11, 25) + MatcherAssert.assertThat(birthDate.year, Matchers.`is`(1974)) + MatcherAssert.assertThat(birthDate.month, Matchers.`is`(11)) + MatcherAssert.assertThat(birthDate.day, Matchers.`is`(25)) + } + + @Test + fun date() { + // NOTE: DateType uses default GMT + val birthDate = DateType(1974, 11, 25).value + val calendar = GregorianCalendar(TimeZone.getTimeZone("GMT")) + calendar.setTime(birthDate) + MatcherAssert.assertThat(calendar.get(Calendar.YEAR), Matchers.`is`(1974)) + MatcherAssert.assertThat(calendar.get(Calendar.MONTH), Matchers.`is`(11)) + MatcherAssert.assertThat(calendar.get(Calendar.DAY_OF_MONTH), Matchers.`is`(25)) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu2Test.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu2Test.kt new file mode 100644 index 0000000000000000000000000000000000000000..65107fb3a1df2233d49f37c815867738d37cfa4c --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu2Test.kt @@ -0,0 +1,75 @@ +package org.hl7.fhirpath + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import org.fhir.ucum.UcumException +import org.opencds.cqf.cql.engine.data.CompositeDataProvider +import org.opencds.cqf.cql.engine.fhir.model.Dstu2FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver + +class FhirHelpersDstu2Test { + private fun getStringFromResourceStream(resourceName: String): String? { + val input = TestFhirPath::class.java.getResourceAsStream(resourceName) + try { + BufferedReader(InputStreamReader(input)).use { stringReader -> + var line: String? = null + val source = StringBuilder() + while ((stringReader.readLine().also { line = it }) != null) { + source.append(line) + source.append("\n") + } + return source.toString() + } + } catch (e: IOException) { + e.printStackTrace() + } + + return null + } + + // @Test + @Throws(UcumException::class) + fun testFhirHelpersDstu2() { + val cql = getStringFromResourceStream("Dstu2/TestFHIRHelpersDstu2.cql") + val env = TranslatorHelper.environment + TranslatorHelper.translate(cql, env.libraryManager!!) + val engine = TranslatorHelper.getEngine(env) + + val libraryId = TranslatorHelper.toElmIdentifier("TestFHIRHelpersDstu2", "0.1.0") + + val modelResolver = Dstu2FhirModelResolver() + val retrieveProvider = + RestFhirRetrieveProvider( + SearchParameterResolver(modelResolver.fhirContext), + modelResolver, + FhirContext.forCached(FhirVersionEnum.DSTU2).newRestfulGenericClient(""), + ) + val provider = CompositeDataProvider(modelResolver, retrieveProvider) + // BaseFhirDataProvider provider = new FhirDataProviderDstu2(); + engine.environment.registerDataProvider("http://hl7.org/fhir", provider) + val results = engine.evaluate { library(libraryId) }.onlyResultOrThrow + + // TODO - millis shouldn't be populated - issue with DateTime.fromJavaDate(Date date) + var value = results["TestPeriodToInterval"]!!.value + // Assertions.assertEquals(((DateTime)((Interval) value).getStart()).getPartial(), + // new + // Partial(DateTime.getFields(7), new int[] {2017, 5, 6, 18, 8, 0, 0})); + // Assertions.assertEquals(((DateTime)((Interval) value).getEnd()).getPartial(), new + // Partial(DateTime.getFields(7), new int[] {2017, 5, 6, 19, 8, 0, 0})); + value = results["TestToQuantity"]!!.value + value = results["TestRangeToInterval"]!!.value + value = results["TestToCode"]!!.value + value = results["TestToConcept"]!!.value + value = results["TestToString"]!!.value + value = results["TestRequestStatusToString"]!!.value + value = results["TestToDateTime"]!!.value + value = results["TestToTime"]!!.value + value = results["TestToInteger"]!!.value + value = results["TestToDecimal"]!!.value + value = results["TestToBoolean"]!!.value + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu3Test.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu3Test.kt new file mode 100644 index 0000000000000000000000000000000000000000..67dd0426f3ea29d71144435a6ee743e4823a8f23 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/FhirHelpersDstu3Test.kt @@ -0,0 +1,79 @@ +package org.hl7.fhirpath + +import java.io.BufferedReader +import java.io.IOException +import java.io.InputStreamReader +import org.fhir.ucum.UcumException +import org.opencds.cqf.cql.engine.data.CompositeDataProvider +import org.opencds.cqf.cql.engine.fhir.model.Dstu3FhirModelResolver +import org.opencds.cqf.cql.engine.fhir.retrieve.RestFhirRetrieveProvider +import org.opencds.cqf.cql.engine.fhir.searchparam.SearchParameterResolver + +class FhirHelpersDstu3Test { + private fun getStringFromResourceStream(resourceName: String): String? { + val input = TestFhirPath::class.java.getResourceAsStream(resourceName) + try { + BufferedReader(InputStreamReader(input)).use { stringReader -> + var line: String? = null + val source = StringBuilder() + while ((stringReader.readLine().also { line = it }) != null) { + source.append(line) + source.append("\n") + } + return source.toString() + } + } catch (e: IOException) { + e.printStackTrace() + } + + return null + } + + // @Test + // TODO: Resolve Error: Could not load model information for model FHIR, version + // 3.0.0 because version 1.0.2 is already loaded + // @Test + @Throws(UcumException::class) + fun testFhirHelpersStu3() { + val cql = getStringFromResourceStream("stu3/TestFHIRHelpers.cql") + val env = TranslatorHelper.environment + TranslatorHelper.translate(cql, env.libraryManager!!) + + val engine = TranslatorHelper.getEngine(env) + + val libraryId = TranslatorHelper.toElmIdentifier("TestFHIRHelpers", "0.1.0") + + val modelResolver = Dstu3FhirModelResolver() + val fhirContext = modelResolver.fhirContext + val retrieveProvider = + RestFhirRetrieveProvider( + SearchParameterResolver(fhirContext), + modelResolver, + fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"), + ) + val provider = CompositeDataProvider(modelResolver, retrieveProvider) + // BaseFhirDataProvider provider = new + // FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3"); + engine.environment.registerDataProvider("http://hl7.org/fhir", provider) + val results = engine.evaluate { library(libraryId) }.onlyResultOrThrow + + // TODO - fix + var value = results["TestPeriodToInterval"]!!.value + // Assertions.assertEquals(((DateTime)((Interval) value).getStart()).getPartial(), + // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 18, 8, 0})); + // Assertions.assertEquals(((DateTime)((Interval) value).getEnd()).getPartial(), + // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 19, 8, 0})); + value = results["TestToQuantity"]!!.value + // TODO: ModelInfo bug. Not aware of SimpleQuantity + value = results["TestRangeToInterval"]!!.value + value = results["TestToCode"]!!.value + value = results["TestToConcept"]!!.value + value = results["TestToString"]!!.value + value = results["TestRequestStatusToString"]!!.value + value = results["TestToDateTime"]!!.value + value = results["TestToTime"]!!.value + value = results["TestToInteger"]!!.value + value = results["TestToDecimal"]!!.value + value = results["TestToBoolean"]!!.value + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestFhirPath.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestFhirPath.kt new file mode 100644 index 0000000000000000000000000000000000000000..d713e6b4f61200b691ae3d3864d497084117dac4 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestFhirPath.kt @@ -0,0 +1,367 @@ +package org.hl7.fhirpath + +import ca.uhn.fhir.context.FhirContext +import jakarta.xml.bind.JAXB +import java.io.InputStreamReader +import java.math.BigDecimal +import java.time.Instant +import java.time.ZoneOffset +import java.util.* +import java.util.function.Function +import org.cqframework.cql.cql2elm.CqlCompilerException +import org.hl7.fhir.instance.model.api.IBaseResource +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.hl7.fhirpath.TranslatorHelper.toElmIdentifier +import org.hl7.fhirpath.tests.InvalidType +import org.hl7.fhirpath.tests.Output +import org.hl7.fhirpath.tests.OutputType +import org.hl7.fhirpath.tests.Test +import org.hl7.fhirpath.tests.Tests +import org.opencds.cqf.cql.engine.data.CompositeDataProvider +import org.opencds.cqf.cql.engine.elm.executing.EqualEvaluator +import org.opencds.cqf.cql.engine.elm.executing.ToQuantityEvaluator +import org.opencds.cqf.cql.engine.elm.executing.ToStringEvaluator +import org.opencds.cqf.cql.engine.exception.CqlException +import org.opencds.cqf.cql.engine.execution.EvaluationResult +import org.opencds.cqf.cql.engine.execution.State +import org.opencds.cqf.cql.engine.fhir.fhirModelNamespaceUri +import org.opencds.cqf.cql.engine.fhir.model.FhirModelResolver +import org.opencds.cqf.cql.engine.runtime.ClassInstance +import org.opencds.cqf.cql.engine.runtime.Date +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.toCqlBoolean +import org.opencds.cqf.cql.engine.runtime.toCqlDecimal +import org.opencds.cqf.cql.engine.runtime.toCqlInteger +import org.opencds.cqf.cql.engine.runtime.toCqlList +import org.opencds.cqf.cql.engine.runtime.toCqlString +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +abstract class TestFhirPath { + open class TestCase(val name: String?, val cql: String?) + + class Error(name: String?, cql: String?) : TestCase(name, cql) // Compile time (Semantic) error + + class Invalid(name: String?, cql: String?) : TestCase(name, cql) // Runtime (Invalid) error + + class Pass( + name: String?, + cql: String?, + val resource: IBaseResource?, + val results: MutableList?, + ) : TestCase(name, cql) // Successful execution + + private val libraryId = toElmIdentifier("TestFHIRPath") + private val header = + """ + library TestFHIRPath + using FHIR version '4.0.1' + include FHIRHelpers version '4.0.1' called FHIRHelpers + + + + """ + .trimIndent() + + private val parametersTemplate = + """ + parameter %s %s + parameter "%%context" %s + parameter "%%resource" %s + parameter "%%rootResource" %s context %s + + + + """ + .trimIndent() + + private val definesTemplate = + """ + define Test: %s + + """ + .trimIndent() + + fun compareResults( + expectedResult: Value?, + actualResult: Value?, + state: State?, + resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, + ): Boolean? { + // Perform FHIR system-defined type conversions + var actualResult = actualResult + + if ( + actualResult is ClassInstance && actualResult.type.namespaceURI == fhirModelNamespaceUri + ) { + val actualResultClass = resolver.resolveType(actualResult.type.localPart)!! + if ( + actualResultClass.isEnum || + IPrimitiveType::class.java.isAssignableFrom(actualResultClass) + ) { + actualResult = actualResult.elements["value"] + } + } + + return EqualEvaluator.equal(expectedResult, actualResult, state)?.value + } + + protected fun runTest( + test: Test, + basePathInput: String?, + fhirContext: FhirContext, + provider: CompositeDataProvider?, + resolver: FhirModelResolver<*, *, *, *, *, *, *, *>, + ) { + val testCase = buildTestCase(test, basePathInput, fhirContext) + val engine = TranslatorHelper.getEngine(testCase.cql!!) + engine.state.environment.registerDataProvider("http://hl7.org/fhir", provider) + if (testCase is Pass && testCase.resource != null) { + val resource = testCase.resource + val resourceAsCqlValue = resolver.toCqlValue(resource) + engine.state.setParameter(null, resource.fhirType(), resourceAsCqlValue) + engine.state.setParameter(null, "%context", resourceAsCqlValue) + engine.state.setParameter(null, "%resource", resourceAsCqlValue) + engine.state.setParameter(null, "%rootResource", resourceAsCqlValue) + } + + var result: EvaluationResult? + try { + result = + engine + .evaluate { + library(libraryId) + parameters = engine.state.parameters + } + .onlyResultOrThrow + } catch (e: CqlException) { + if (testCase is Pass) { + throw failWithContext( + "Runtime error and was expecting a result", + testCase, + "N/A".toCqlString(), + e, + ) + } + + if (testCase is Error && e.cause is CqlCompilerException) { + return // Expected a compile time error. + } + + if (testCase is Invalid) { + return // Expected a runtime error + } + + log.warn( + "%s failed as expected, but unable to determine the cause of the failure. Possible bug in engine. Skipping." + .format(testCase.name) + ) + return + } + + if (testCase is Invalid) { + log.warn( + "%s was marked as Invalid, but it got a result. Possible bug in test suite. Skipping." + .format(testCase.name) + ) + return + } + + val testValue = result["Test"]!!.value + val actualList = + if (testValue == null) List.EMPTY_LIST + else if (testValue is List) testValue else listOf(testValue).toCqlList() + + // Catch-all to prevent ClassCastException + if (testCase !is Pass) { + throw failWithContext( + "expected a non-Pass test case for %s, but got %s" + .format(testCase.name, testCase.javaClass.getSimpleName()), + testCase, + actualList, + null, + ) + } + + // Invalid and Semantic errors have been handled above, so we can assume Pass here + if (actualList.count() != testCase.results!!.size) { + throw failWithContext( + "Incorrect number of results. Expected %d, Actual %d" + .format(testCase.results.size, actualList.count()), + testCase, + actualList, + null, + ) + } + + for (i in actualList.toList().indices) { + val expected = testCase.results[i] + val actual = actualList.elementAt(i) + val comparison = compareResults(expected, actual, engine.state, resolver) + if (true != comparison) { + throw failWithContext( + "Result mismatch at index %d".format(i), + testCase, + actual, + null, + ) + } + } + } + + private fun buildTestCase( + test: Test, + basePathInput: String?, + fhirContext: FhirContext, + ): TestCase { + val resource = + Optional.ofNullable(test.getInputfile()) + .map( + Function { inputFile: String? -> + loadResourceFile(basePathInput + inputFile, fhirContext) + } + ) + .orElse(null) + + val cql = buildCql(test, resource) + val invalid = + Optional.ofNullable(test.getExpression().getInvalid()) + .orElse(InvalidType.FALSE) + val expectedResults = loadExpectedResults(test) + return when (invalid) { + InvalidType.TRUE -> Invalid(test.getName(), cql) + InvalidType.SEMANTIC -> Error(test.getName(), cql) + InvalidType.FALSE -> Pass(test.getName(), cql, resource, expectedResults) + } + } + + private fun buildCql(test: Test, resource: IBaseResource?): String { + val inputExpression = test.getExpression().getValue() + val predicate = Optional.ofNullable(test.isPredicate).orElse(false) + val expressionOutput = test.getOutput().size == 1 && test.getOutput()[0].getType() == null + + var testExpression = inputExpression + if (predicate) { + testExpression = "exists { %s }".format(inputExpression) + } else if (expressionOutput) { + val outputExpression = test.getOutput()[0].getValue() + testExpression = + if ("null" == outputExpression) { + "(%s) is %s".format(inputExpression, outputExpression) + } else if ("{ }" == outputExpression) { + "not exists (%s)".format(inputExpression) + } else if ("null" == inputExpression) { + "(%s) is %s".format(outputExpression, inputExpression) + } else { + "(%s) = (%s)".format(inputExpression, outputExpression) + } + } + + // if have a resource, add the CQL parameters. + val params = + Optional.ofNullable(resource) + .map( + Function { res: IBaseResource? -> + parametersTemplate.format( + *Collections.nCopies(6, res!!.fhirType()).toTypedArray() + ) + } + ) + .orElse("") + + val defines: String = definesTemplate.format(testExpression) + return header + params + defines + } + + private fun failWithContext( + message: String?, + test: TestCase, + actual: Value?, + e: Exception?, + ): RuntimeException { + val expectedString = + if (test is Pass) ToStringEvaluator.toString(test.results?.toCqlList()) else "N/A" + val actualString = ToStringEvaluator.toString(actual) + val error = + """ + Failed Test: %s + - Message: %s + - Expected: %s + - Actual: %s + - CQL:%n%n%s + + """ + .trimIndent() + return RuntimeException( + error.format(test.name, message, expectedString, actualString, test.cql), + e, + ) + } + + private fun loadResourceFile(resourceFilePath: String, context: FhirContext): IBaseResource? { + return context + .newXmlParser() + .parseResource( + InputStreamReader(TestFhirPath::class.java.getResourceAsStream(resourceFilePath)!!) + ) + } + + private fun readOutput(output: Output): Value? { + if (output.getType() == null) { + return null + } + + return when (output.getType()) { + OutputType.BOOLEAN -> output.getValue().toBoolean().toCqlBoolean() + OutputType.DECIMAL -> BigDecimal(output.getValue()).toCqlDecimal() + OutputType.DATE -> Date(output.getValue()) + OutputType.DATE_TIME -> + DateTime( + output.getValue(), + ZoneOffset.systemDefault().rules.getOffset(Instant.now()), + ) + + OutputType.TIME -> Time(output.getValue()) + OutputType.INTEGER -> output.getValue().toInt().toCqlInteger() + OutputType.STRING, + OutputType.CODE -> output.getValue().toCqlString() + OutputType.QUANTITY -> ToQuantityEvaluator.toQuantity(output.getValue()) + else -> + throw IllegalArgumentException( + "Output type [ %s ] is not supported in tests" + .format(if (output.getType() == null) "null" else output.getType()) + ) + } + } + + private fun loadExpectedResults(test: Test): MutableList { + // Special case for tests are "expression output" tests, which have a single output with no + // type + if (test.getOutput().size == 1 && test.getOutput()[0].getType() == null) { + return mutableListOf(org.opencds.cqf.cql.engine.runtime.Boolean.TRUE) + } + + return test.getOutput()!!.map { this.readOutput(it) }.toMutableList() + } + + companion object { + private val log: Logger = LoggerFactory.getLogger(TestFhirPath::class.java) + + @JvmStatic + protected fun loadTestsFile(testsFilePath: String): Tests? { + try { + val testsFileRaw = TestFhirPath::class.java.getResourceAsStream(testsFilePath) + return JAXB.unmarshal(testsFileRaw, Tests::class.java) + } catch (e: Exception) { + // e.printStackTrace(); + throw IllegalArgumentException( + "Couldn't load tests file [ %s ]".format(testsFilePath), + e, + ) + } + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestLibrarySourceProvider.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestLibrarySourceProvider.kt new file mode 100644 index 0000000000000000000000000000000000000000..433d6ade6aa142b7863cacd0576ce9a050447f14 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TestLibrarySourceProvider.kt @@ -0,0 +1,28 @@ +package org.hl7.fhirpath + +import kotlinx.io.Source +import kotlinx.io.asSource +import kotlinx.io.buffered +import org.cqframework.cql.cql2elm.LibraryContentType +import org.cqframework.cql.cql2elm.LibrarySourceProvider +import org.hl7.elm.r1.VersionedIdentifier + +class TestLibrarySourceProvider : LibrarySourceProvider { + override fun getLibrarySource(libraryIdentifier: VersionedIdentifier): Source? { + val libraryFileName = + "stu3/${libraryIdentifier.id}${if (libraryIdentifier.version != null) "-${libraryIdentifier.version}" else ""}.cql" + val inputStream = TestLibrarySourceProvider::class.java.getResourceAsStream(libraryFileName) + return inputStream?.asSource()?.buffered() + } + + override fun getLibraryContent( + libraryIdentifier: VersionedIdentifier, + type: LibraryContentType, + ): Source? { + if (LibraryContentType.CQL == type) { + return getLibrarySource(libraryIdentifier) + } + + return null + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TranslatorHelper.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TranslatorHelper.kt new file mode 100644 index 0000000000000000000000000000000000000000..373bccf8a4e2159c7166b47794ed59a8fc4fe439 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/hl7/fhirpath/TranslatorHelper.kt @@ -0,0 +1,136 @@ +package org.hl7.fhirpath + +import org.cqframework.cql.cql2elm.CqlCompiler +import org.cqframework.cql.cql2elm.CqlCompilerException.ErrorSeverity +import org.cqframework.cql.cql2elm.CqlCompilerOptions +import org.cqframework.cql.cql2elm.CqlCompilerOptions.Companion.defaultOptions +import org.cqframework.cql.cql2elm.LibraryManager +import org.cqframework.cql.cql2elm.ModelManager +import org.cqframework.cql.cql2elm.StringLibrarySourceProvider +import org.cqframework.cql.cql2elm.quick.FhirLibrarySourceProvider +import org.fhir.ucum.UcumException +import org.hl7.elm.r1.Library +import org.hl7.elm.r1.VersionedIdentifier +import org.opencds.cqf.cql.engine.execution.CqlEngine +import org.opencds.cqf.cql.engine.execution.Environment +import org.opencds.cqf.cql.engine.terminology.TerminologyProvider + +object TranslatorHelper { + // Shared model cache — thread-safe (ConcurrentHashMap) + private val globalModelCache = + org.cqframework.cql.cql2elm.utils.createConcurrentHashMap< + org.hl7.cql.model.ModelIdentifier, + org.cqframework.cql.cql2elm.model.Model, + >() + + private fun defaultCompilerOptions(): CqlCompilerOptions { + val options = defaultOptions() + options.options.remove(CqlCompilerOptions.Options.DisableListDemotion) + options.options.remove(CqlCompilerOptions.Options.DisableListPromotion) + options.options.add(CqlCompilerOptions.Options.EnableDateRangeOptimization) + options.options.add(CqlCompilerOptions.Options.EnableResultTypes) + return options + } + + // Pre-compile FHIRHelpers and other shared libraries once, then reuse the cache. + private val sharedLibraryCache: + Map by lazy { + val warmupManager = newLibraryManagerInternal(defaultCompilerOptions(), emptyMap()) + warmupManager.librarySourceLoader.registerProvider( + StringLibrarySourceProvider( + listOf( + "library Warmup using FHIR version '4.0.1' include FHIRHelpers version '4.0.1' define X: 1" + ) + ) + ) + val compiler = CqlCompiler(libraryManager = warmupManager) + compiler.run( + "library Warmup using FHIR version '4.0.1' include FHIRHelpers version '4.0.1' define X: 1" + ) + // Return only the shared dependency libraries (not the warmup library itself) + warmupManager.compiledLibraries.filter { it.key.id != "Warmup" } + } + + private fun newLibraryManagerInternal( + cqlCompilerOptions: CqlCompilerOptions, + precompiledLibraries: + Map, + ): LibraryManager { + val modelManager = ModelManager(globalCache = globalModelCache) + val libraryCache = HashMap(precompiledLibraries) + val libraryManager = + LibraryManager(modelManager, cqlCompilerOptions, libraryCache = libraryCache) + libraryManager.librarySourceLoader.clearProviders() + libraryManager.librarySourceLoader.registerProvider(TestLibrarySourceProvider()) + libraryManager.librarySourceLoader.registerProvider(FhirLibrarySourceProvider()) + return libraryManager + } + + private fun newLibraryManager(): LibraryManager { + return newLibraryManagerInternal(defaultCompilerOptions(), sharedLibraryCache) + } + + @JvmStatic + fun getEngine(cql: String): CqlEngine { + return getEngine(getEnvironment(cql)) + } + + fun getEnvironment(cql: String): Environment { + val env = getEnvironment(null as TerminologyProvider?) + env.libraryManager!! + .librarySourceLoader + .registerProvider(StringLibrarySourceProvider(listOf(cql))) + return env + } + + val environment: Environment + get() = getEnvironment(null as TerminologyProvider?) + + fun getEnvironment(terminologyProvider: TerminologyProvider?): Environment { + return Environment(newLibraryManager(), null, terminologyProvider) + } + + fun getEngine(environment: Environment?): CqlEngine { + return CqlEngine(environment!!, mutableSetOf(CqlEngine.Options.EnableTypeChecking)) + } + + @JvmStatic + fun toElmIdentifier(name: String?): VersionedIdentifier { + return VersionedIdentifier().withId(name) + } + + @JvmStatic + fun toElmIdentifier(name: String?, version: String?): VersionedIdentifier { + return VersionedIdentifier().withId(name).withVersion(version) + } + + @Throws(UcumException::class) + fun translate(cql: String?, libraryManager: LibraryManager): Library { + val compiler = CqlCompiler(libraryManager = libraryManager) + val lib = compiler.run(cql!!) + + libraryManager.compiledLibraries[lib.identifier!!] = compiler.compiledLibrary!! + + val errors = compiler.exceptions.filter { it.severity == ErrorSeverity.Error } + if (errors.isNotEmpty()) { + val messages = mutableListOf() + for (error in compiler.exceptions) { + val tb = error.locator + val lines = + if (tb == null) "[n/a]" + else + String.format( + "[%d:%d, %d:%d]", + tb.startLine, + tb.startChar, + tb.endLine, + tb.endChar, + ) + messages.add(lines + error.message) + } + throw IllegalArgumentException(messages.toString()) + } + + return lib + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/Dstu3FhirTest.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/Dstu3FhirTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..193f1245e041829312a0fbc0523c94989e3edf90 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/Dstu3FhirTest.kt @@ -0,0 +1,143 @@ +package org.opencds.cqf.cql.engine.fhir + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import ca.uhn.fhir.parser.IParser +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor +import com.github.tomakehurst.wiremock.WireMockServer +import com.github.tomakehurst.wiremock.client.MappingBuilder +import com.github.tomakehurst.wiremock.client.WireMock +import java.net.ServerSocket +import org.hl7.fhir.dstu3.model.Bundle +import org.hl7.fhir.dstu3.model.CapabilityStatement +import org.hl7.fhir.dstu3.model.OperationOutcome +import org.hl7.fhir.dstu3.model.Resource +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +open class Dstu3FhirTest { + var wireMockServer: WireMockServer? = null + var wireMock: WireMock? = null + + @BeforeEach + fun start() { + wireMockServer = WireMockServer(httpPort) + wireMockServer!!.start() + WireMock.configureFor("localhost", httpPort) + wireMock = WireMock("localhost", httpPort) + + mockFhirRead("/metadata", this.capabilityStatement) + } + + @AfterEach + fun stop() { + wireMockServer!!.stop() + } + + fun mockNotFound(resource: String?) { + val outcome = OperationOutcome() + outcome.getText().statusAsString = "generated" + outcome.issueFirstRep + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.PROCESSING) + .setDiagnostics(resource) + + mockFhirRead(resource, outcome, 404) + } + + fun mockFhirRead(resource: Resource) { + val resourcePath = "/" + resource.fhirType() + "/" + resource.getId() + mockFhirInteraction(resourcePath, resource) + } + + @JvmOverloads + fun mockFhirRead(path: String?, resource: Resource?, statusCode: Int = 200) { + val builder = WireMock.get(WireMock.urlEqualTo(path)) + mockFhirInteraction(builder, resource, statusCode) + } + + fun mockFhirSearch(path: String?, vararg resources: Resource) { + val builder = WireMock.get(WireMock.urlEqualTo(path)) + mockFhirInteraction(builder, makeBundle(*resources)) + } + + fun mockFhirPost(path: String?, resource: Resource?) { + mockFhirInteraction(WireMock.post(WireMock.urlEqualTo(path)), resource, 200) + } + + fun mockFhirInteraction(path: String?, resource: Resource?) { + mockFhirRead(path, resource, 200) + } + + @JvmOverloads + fun mockFhirInteraction(builder: MappingBuilder, resource: Resource?, statusCode: Int = 200) { + var body: String? = null + if (resource != null) { + body = fhirParser!!.encodeResourceToString(resource) + } + + WireMock.stubFor( + builder.willReturn( + WireMock.aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json") + .withBody(body) + ) + ) + } + + val capabilityStatement: CapabilityStatement + get() { + val metadata = CapabilityStatement() + metadata.setFhirVersion("3.0.2") + return metadata + } + + fun makeBundle(resources: MutableList): Bundle { + return makeBundle(*resources.toTypedArray()) + } + + fun makeBundle(vararg resources: Resource): Bundle { + val bundle = Bundle() + bundle.setType(Bundle.BundleType.SEARCHSET) + bundle.setTotal(resources.size) + for (l in resources) { + bundle.addEntry().setResource(l).setFullUrl("/" + l.fhirType() + "/" + l.getId()) + } + return bundle + } + + companion object { + val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.DSTU3) + val fhirParser: IParser? = fhirContext.newJsonParser().setPrettyPrint(true) + private var HTTP_PORT = 0 + + val httpPort: Int + get() { + if (HTTP_PORT == 0) { + try { + ServerSocket(0).use { socket -> HTTP_PORT = socket.getLocalPort() } + } catch (ex: Exception) { + throw RuntimeException( + "Failed to determine a port for the wiremock server", + ex, + ) + } + } + return HTTP_PORT + } + + fun newClient(): IGenericClient { + val client: IGenericClient = + fhirContext.newRestfulGenericClient("http://localhost:$httpPort/") + + val logger = LoggingInterceptor() + logger.setLogRequestSummary(true) + logger.setLogResponseBody(true) + client.registerInterceptor(logger) + + return client + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/R4FhirTest.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/R4FhirTest.kt new file mode 100644 index 0000000000000000000000000000000000000000..f6d408b79cbb44252e0e7158fdf04a910b9c816d --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/R4FhirTest.kt @@ -0,0 +1,143 @@ +package org.opencds.cqf.cql.engine.fhir + +import ca.uhn.fhir.context.FhirContext +import ca.uhn.fhir.context.FhirVersionEnum +import ca.uhn.fhir.parser.IParser +import ca.uhn.fhir.rest.client.api.IGenericClient +import ca.uhn.fhir.rest.client.interceptor.LoggingInterceptor +import com.github.tomakehurst.wiremock.WireMockServer +import com.github.tomakehurst.wiremock.client.MappingBuilder +import com.github.tomakehurst.wiremock.client.WireMock +import java.net.ServerSocket +import org.hl7.fhir.r4.model.Bundle +import org.hl7.fhir.r4.model.CapabilityStatement +import org.hl7.fhir.r4.model.Enumerations +import org.hl7.fhir.r4.model.OperationOutcome +import org.hl7.fhir.r4.model.Resource +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.BeforeEach + +abstract class R4FhirTest { + var wireMockServer: WireMockServer? = null + var wireMock: WireMock? = null + + @BeforeEach + fun start() { + wireMockServer = WireMockServer(httpPort) + wireMockServer!!.start() + WireMock.configureFor("localhost", httpPort) + wireMock = WireMock("localhost", httpPort) + + mockFhirRead("/metadata", this.capabilityStatement) + } + + @AfterEach + fun stop() { + wireMockServer!!.stop() + } + + fun mockNotFound(resource: String?) { + val outcome = OperationOutcome() + outcome.getText().statusAsString = "generated" + outcome.issueFirstRep + .setSeverity(OperationOutcome.IssueSeverity.ERROR) + .setCode(OperationOutcome.IssueType.PROCESSING) + .setDiagnostics(resource) + + mockFhirRead(resource, outcome, 404) + } + + fun mockFhirRead(resource: Resource) { + val resourcePath = "/" + resource.fhirType() + "/" + resource.getId() + mockFhirInteraction(resourcePath, resource) + } + + @JvmOverloads + fun mockFhirRead(path: String?, resource: Resource?, statusCode: Int = 200) { + val builder = WireMock.get(WireMock.urlEqualTo(path)) + mockFhirInteraction(builder, resource, statusCode) + } + + fun mockFhirSearch(path: String?, vararg resources: Resource) { + val builder = WireMock.get(WireMock.urlEqualTo(path)) + mockFhirInteraction(builder, makeBundle(*resources)) + } + + fun mockFhirPost(path: String?, resource: Resource?) { + mockFhirInteraction(WireMock.post(WireMock.urlEqualTo(path)), resource, 200) + } + + fun mockFhirInteraction(path: String?, resource: Resource?) { + mockFhirRead(path, resource, 200) + } + + @JvmOverloads + fun mockFhirInteraction(builder: MappingBuilder, resource: Resource?, statusCode: Int = 200) { + var body: String? = null + if (resource != null) { + body = fhirParser.encodeResourceToString(resource) + } + + WireMock.stubFor( + builder.willReturn( + WireMock.aResponse() + .withStatus(statusCode) + .withHeader("Content-Type", "application/json") + .withBody(body) + ) + ) + } + + val capabilityStatement: CapabilityStatement + get() { + val metadata = CapabilityStatement() + metadata.setFhirVersion(Enumerations.FHIRVersion._4_0_1) + return metadata + } + + fun makeBundle(resources: MutableList): Bundle { + return makeBundle(*resources.toTypedArray()) + } + + fun makeBundle(vararg resources: Resource): Bundle { + val bundle = Bundle() + bundle.setType(Bundle.BundleType.SEARCHSET) + bundle.setTotal(resources.size) + for (l in resources) { + bundle.addEntry().setResource(l).setFullUrl("/" + l.fhirType() + "/" + l.getId()) + } + return bundle + } + + companion object { + val fhirContext: FhirContext = FhirContext.forCached(FhirVersionEnum.R4) + val fhirParser: IParser = fhirContext.newJsonParser().setPrettyPrint(true) + private var HTTP_PORT = 0 + + val httpPort: Int + get() { + if (HTTP_PORT == 0) { + try { + ServerSocket(0).use { socket -> HTTP_PORT = socket.getLocalPort() } + } catch (ex: Exception) { + throw RuntimeException( + "Failed to determine a port for the wiremock server", + ex, + ) + } + } + return HTTP_PORT + } + + fun newClient(): IGenericClient { + val client: IGenericClient = + fhirContext.newRestfulGenericClient("http://localhost:$httpPort/") + + val logger = LoggingInterceptor() + logger.setLogRequestSummary(true) + logger.setLogResponseBody(true) + client.registerInterceptor(logger) + return client + } + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/ConverterTestUtils.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/ConverterTestUtils.kt new file mode 100644 index 0000000000000000000000000000000000000000..999d71e48d85219b05b265783c1440d681254a20 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/ConverterTestUtils.kt @@ -0,0 +1,59 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import java.time.LocalDateTime +import java.time.Month +import java.time.format.DateTimeFormatter + +object ConverterTestUtils { + val DST_2022_11_01: LocalDateTime = LocalDateTime.of(2022, Month.NOVEMBER, 1, 0, 0, 0) + val DST_2023_11_01: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 1, 0, 0, 0) + val DST_2023_11_03: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 3, 0, 0, 0) + val NON_DST_2022_01_01: LocalDateTime = LocalDateTime.of(2022, Month.JANUARY, 1, 0, 0, 0) + val NON_DST_2023_01_01: LocalDateTime = LocalDateTime.of(2023, Month.JANUARY, 1, 0, 0, 0) + val NON_DST_2022_11_10: LocalDateTime = LocalDateTime.of(2022, Month.NOVEMBER, 10, 0, 0, 0) + val NON_DST_2023_11_10: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 10, 0, 0, 0) + val NON_DST_2023_11_14: LocalDateTime = LocalDateTime.of(2023, Month.NOVEMBER, 14, 0, 0, 0) + @JvmField val YYYY_MM_DD: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd") + + @JvmStatic + fun dateTimes(): Array?> { + return arrayOf( + arrayOf(DST_2023_11_01, DST_2023_11_01, DST_2023_11_03), + arrayOf(NON_DST_2023_11_14, NON_DST_2023_11_10, NON_DST_2023_11_14), + arrayOf(NON_DST_2023_11_14, DST_2023_11_01, DST_2023_11_03), + arrayOf(DST_2023_11_01, NON_DST_2023_11_10, NON_DST_2023_11_14), + ) + } + + @JvmStatic + fun startAndEndTimes(): Array?> { + return arrayOf( + arrayOf(DST_2023_11_01, DST_2023_11_03), + arrayOf(NON_DST_2023_11_10, NON_DST_2023_11_14), + arrayOf(DST_2023_11_01, DST_2023_11_03), + arrayOf(NON_DST_2023_11_10, NON_DST_2023_11_14), + arrayOf(DST_2022_11_01, DST_2023_11_03), + arrayOf(NON_DST_2022_11_10, NON_DST_2023_11_10), + arrayOf(NON_DST_2022_01_01, NON_DST_2023_01_01), + ) + } + + @JvmStatic + fun startAndEndYears(): Array?> { + return arrayOf( + arrayOf(DST_2022_11_01, 2019, 2020), + arrayOf(NON_DST_2023_11_14, 2019, 2020), + arrayOf(DST_2022_11_01, 2018, 2022), + arrayOf(NON_DST_2023_11_14, 2018, 2022), + ) + } + + @JvmStatic + fun nowsAndEvaluationTimes(): Array?> { + return arrayOf( + arrayOf(NON_DST_2022_01_01, NON_DST_2023_01_01), + arrayOf(DST_2022_11_01, NON_DST_2023_01_01), + arrayOf(NON_DST_2022_11_10, NON_DST_2023_01_01), + ) + } +} diff --git a/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2TypeConverterTests.kt b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2TypeConverterTests.kt new file mode 100644 index 0000000000000000000000000000000000000000..4a4a78171b2fc637905118260b9bf36f944bf1f4 --- /dev/null +++ b/source_data/pinned/cql-clinical/clinical_quality_language/commit-bc0c795e4f2a/engine-fhir/src/jvmTest/kotlin/org/opencds/cqf/cql/engine/fhir/converter/Dstu2TypeConverterTests.kt @@ -0,0 +1,1152 @@ +package org.opencds.cqf.cql.engine.fhir.converter + +import ca.uhn.fhir.model.api.TemporalPrecisionEnum +import java.math.BigDecimal +import java.time.LocalDateTime +import java.time.ZoneId +import java.time.ZoneOffset +import java.time.ZonedDateTime +import java.time.format.DateTimeFormatter +import java.util.* +import java.util.stream.Collectors +import kotlin.test.assertIs +import org.apache.commons.lang3.NotImplementedException +import org.hamcrest.MatcherAssert +import org.hamcrest.Matchers +import org.hl7.fhir.dstu2.model.Attachment +import org.hl7.fhir.dstu2.model.Base +import org.hl7.fhir.dstu2.model.BooleanType +import org.hl7.fhir.dstu2.model.CodeableConcept +import org.hl7.fhir.dstu2.model.Coding +import org.hl7.fhir.dstu2.model.DateTimeType +import org.hl7.fhir.dstu2.model.DateType +import org.hl7.fhir.dstu2.model.DecimalType +import org.hl7.fhir.dstu2.model.Extension +import org.hl7.fhir.dstu2.model.IdType +import org.hl7.fhir.dstu2.model.InstantType +import org.hl7.fhir.dstu2.model.IntegerType +import org.hl7.fhir.dstu2.model.OperationOutcome +import org.hl7.fhir.dstu2.model.Parameters +import org.hl7.fhir.dstu2.model.Patient +import org.hl7.fhir.dstu2.model.Period +import org.hl7.fhir.dstu2.model.Quantity +import org.hl7.fhir.dstu2.model.Range +import org.hl7.fhir.dstu2.model.Ratio +import org.hl7.fhir.dstu2.model.SimpleQuantity +import org.hl7.fhir.dstu2.model.StringType +import org.hl7.fhir.dstu2.model.TimeType +import org.hl7.fhir.instance.model.api.IBase +import org.hl7.fhir.instance.model.api.IBaseOperationOutcome +import org.hl7.fhir.instance.model.api.IPrimitiveType +import org.junit.jupiter.api.Assertions +import org.junit.jupiter.api.Test +import org.junit.jupiter.params.ParameterizedTest +import org.junit.jupiter.params.provider.MethodSource +import org.opencds.cqf.cql.engine.elm.executing.EqualEvaluator.equal +import org.opencds.cqf.cql.engine.fhir.converter.ConverterTestUtils.YYYY_MM_DD +import org.opencds.cqf.cql.engine.runtime.Code +import org.opencds.cqf.cql.engine.runtime.Concept +import org.opencds.cqf.cql.engine.runtime.DateTime +import org.opencds.cqf.cql.engine.runtime.Decimal +import org.opencds.cqf.cql.engine.runtime.Integer +import org.opencds.cqf.cql.engine.runtime.Interval +import org.opencds.cqf.cql.engine.runtime.List +import org.opencds.cqf.cql.engine.runtime.Precision +import org.opencds.cqf.cql.engine.runtime.Time +import org.opencds.cqf.cql.engine.runtime.Tuple +import org.opencds.cqf.cql.engine.runtime.Value +import org.opencds.cqf.cql.engine.runtime.toCqlBoolean +import org.opencds.cqf.cql.engine.runtime.toCqlDecimal +import org.opencds.cqf.cql.engine.runtime.toCqlInteger +import org.opencds.cqf.cql.engine.runtime.toCqlList +import org.opencds.cqf.cql.engine.runtime.toCqlLong +import org.opencds.cqf.cql.engine.runtime.toCqlString + +internal class Dstu2TypeConverterTests { + private fun compareIterables(left: Iterable, right: Iterable): Boolean { + val leftIterator = left.iterator() + val rightIterator = right.iterator() + + while (leftIterator.hasNext() && rightIterator.hasNext()) { + val currentL = leftIterator.next() + val currentR = rightIterator.next() + + val result = compareObjects(currentL, currentR) + if (!result) { + return false + } + } + + return !leftIterator.hasNext() && !rightIterator.hasNext() + } + + private fun compareObjects(left: Any?, right: Any?): Boolean { + if ((left == null) xor (right == null)) { + return false + } + + if (left == null && right == null) { + return true + } + + if (left!!.javaClass != right!!.javaClass) { + return false + } + + if (left is Iterable<*>) { + return compareIterables(left, right as Iterable) + } + + if (left is Value) { + return left == right as Value + } + + if (left is Base) { + return left.equalsDeep(right as Base) + } + + return left == right + } + + // CQL-to-FHIR + @Test + fun isFhirType() { + Assertions.assertTrue(typeConverter.isFhirType(Patient())) + Assertions.assertTrue(typeConverter.isFhirType(IdType())) + Assertions.assertTrue(typeConverter.isFhirType(Quantity())) + Assertions.assertTrue(typeConverter.isFhirType(Ratio())) + Assertions.assertTrue(typeConverter.isFhirType(BooleanType())) + Assertions.assertTrue(typeConverter.isFhirType(IntegerType())) + Assertions.assertTrue(typeConverter.isFhirType(DecimalType())) + Assertions.assertTrue(typeConverter.isFhirType(DateType())) + Assertions.assertTrue(typeConverter.isFhirType(InstantType())) + Assertions.assertTrue(typeConverter.isFhirType(DateTimeType())) + Assertions.assertTrue(typeConverter.isFhirType(TimeType())) + Assertions.assertTrue(typeConverter.isFhirType(StringType())) + Assertions.assertTrue(typeConverter.isFhirType(Coding())) + Assertions.assertTrue(typeConverter.isFhirType(CodeableConcept())) + Assertions.assertTrue(typeConverter.isFhirType(Period())) + Assertions.assertTrue(typeConverter.isFhirType(Range())) + + Assertions.assertFalse(typeConverter.isFhirType(5)) + Assertions.assertFalse(typeConverter.isFhirType(BigDecimal(0))) + Assertions.assertFalse(typeConverter.isFhirType(Code())) + } + + @Test + fun iterableIsFhirType() { + val value = ArrayList() + Assertions.assertThrows(IllegalArgumentException::class.java) { + typeConverter.isFhirType(value) + } + } + + @Test + fun toFhirType() { + var actual: IBase? = typeConverter.toFhirType(Code()) + MatcherAssert.assertThat(actual, Matchers.instanceOf(Coding::class.java)) + + actual = typeConverter.toFhirType(5.toCqlInteger()) + MatcherAssert.assertThat(actual, Matchers.instanceOf(IntegerType::class.java)) + + actual = typeConverter.toFhirType(null) + Assertions.assertNull(actual) + } + + @Test + fun toFhirTypeIterable() { + val value = List(emptyList()) + Assertions.assertThrows(IllegalArgumentException::class.java) { + typeConverter.toFhirType(value) + } + } + + @Test + fun toFhirTypes() { + val innerExpected: MutableList = ArrayList() + innerExpected.add(StringType("123")) + innerExpected.add(null) + val expected: MutableList = ArrayList() + expected.add(innerExpected) + expected.add(null) + expected.add(IntegerType(5)) + + val test = + listOf(listOf("123".toCqlString(), null).toCqlList(), null, 5.toCqlInteger()) + .toCqlList() + + val actual = typeConverter.toFhirTypes(test) + + Assertions.assertTrue(compareIterables(expected, actual)) + } + + @Test + fun stringToFhirId() { + val expected = IdType("123") + var actual = typeConverter.toFhirId("123".toCqlString()) + Assertions.assertEquals(expected.value, actual!!.value) + + actual = typeConverter.toFhirId(null) + Assertions.assertNull(actual) + } + + @Test + fun primitiveCqlTypeToFhirType() { + val expectedBoolean = BooleanType(false) + var actualBoolean = typeConverter.toFhirBoolean(false.toCqlBoolean()) + Assertions.assertEquals(expectedBoolean.getValue(), actualBoolean!!.getValue()) + + actualBoolean = typeConverter.toFhirBoolean(null) + Assertions.assertNull(actualBoolean) + + val expectedInteger = IntegerType(5) + var actualInteger = typeConverter.toFhirInteger(5.toCqlInteger()) + Assertions.assertEquals(expectedInteger.getValue(), actualInteger!!.getValue()) + + actualInteger = typeConverter.toFhirInteger(null) + Assertions.assertNull(actualInteger) + + val expectedString = StringType("5") + var actualString = typeConverter.toFhirString("5".toCqlString()) + Assertions.assertEquals(expectedString.getValue(), actualString!!.getValue()) + + actualString = typeConverter.toFhirString(null) + Assertions.assertNull(actualString) + + val expectedDecimal = DecimalType(BigDecimal("2.0")) + var actualDecimal = typeConverter.toFhirDecimal(BigDecimal("2.0").toCqlDecimal()) + Assertions.assertEquals(expectedDecimal.getValue(), actualDecimal!!.getValue()) + + actualDecimal = typeConverter.toFhirDecimal(null) + Assertions.assertNull(actualDecimal) + } + + @Test + fun dateToFhirDate() { + var expectedDate: IPrimitiveType = DateType("2019-02-03") + var actualDate: IPrimitiveType? = + typeConverter.toFhirDate(org.opencds.cqf.cql.engine.runtime.Date("2019-02-03")) + Assertions.assertEquals(expectedDate.getValue(), actualDate!!.getValue()) + + expectedDate = DateType("2019") + actualDate = typeConverter.toFhirDate(org.opencds.cqf.cql.engine.runtime.Date("2019")) + Assertions.assertEquals(expectedDate.value, actualDate!!.getValue()) + } + + @ParameterizedTest + @MethodSource("nowsAndEvaluationTimes") + fun dateTimeToFhirDateTime(now: LocalDateTime, evaluationTime: LocalDateTime) { + val zonedDateTime = ZonedDateTime.of(now, ZoneId.systemDefault()) + val defaultOffset = zonedDateTime.offset + + val evalTimeWithOffset = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(evaluationTime.atOffset(defaultOffset)) + val evalDate = DateTimeFormatter.ISO_DATE.format(evaluationTime) + + var expectedDate = DateTimeType(evalTimeWithOffset) + var actualDate: IPrimitiveType? = + typeConverter.toFhirDateTime(DateTime(evalDate, defaultOffset)) + Assertions.assertEquals(expectedDate.value, actualDate!!.getValue()) + + expectedDate = DateTimeType(evalTimeWithOffset) + actualDate = typeConverter.toFhirDateTime(DateTime("" + evaluationTime.year, defaultOffset)) + expectedDate.precision = TemporalPrecisionEnum.YEAR + Assertions.assertEquals(expectedDate.value, actualDate!!.getValue()) + Assertions.assertEquals(expectedDate.valueAsString, actualDate.valueAsString) + } + + @Test + fun dateTimeToFhirDateTimeTimezones() { + var expectedDate = DateTimeType("2019-10-10T01:00:00-06:00") + expectedDate.timeZone = TimeZone.getTimeZone("MST") + var actualDate: IPrimitiveType? = + typeConverter.toFhirDateTime(DateTime("2019-10-10T00:00:00", ZoneOffset.ofHours(-7))) + Assertions.assertEquals(expectedDate.valueAsString, actualDate!!.valueAsString) + + expectedDate = DateTimeType("2019-10-10T19:35:53.000Z") + expectedDate.precision = TemporalPrecisionEnum.MILLI + actualDate = + typeConverter.toFhirDateTime( + DateTime("2019-10-10T19:35:53", ZoneOffset.UTC).withPrecision(Precision.MILLISECOND) + ) + Assertions.assertEquals(expectedDate.valueAsString, actualDate!!.valueAsString) + } + + @Test + fun quantityToFhirQuantity() { + val expected = + Quantity() + .setValue(BigDecimal("2.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") + .setUnit("ml") + val actual = + typeConverter.toFhirQuantity( + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal("2.0")) + .withUnit("ml") + ) as Quantity? + Assertions.assertTrue(expected.equalsDeep(actual)) + } + + @Test + fun ratioToFhirRatio() { + val expectedNumerator = + Quantity() + .setValue(BigDecimal("1.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") + .setUnit("ml") + val expectedDenominator = + Quantity() + .setValue(BigDecimal("2.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") + .setUnit("ml") + + val expected = Ratio().setNumerator(expectedNumerator).setDenominator(expectedDenominator) + + val testData = org.opencds.cqf.cql.engine.runtime.Ratio() + testData.numerator = + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal.valueOf(1.0)) + .withUnit("ml") + testData.denominator = + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal.valueOf(2.0)) + .withUnit("ml") + + val actual = typeConverter.toFhirRatio(testData) as Ratio? + + Assertions.assertTrue(expected.equalsDeep(actual)) + } + + @Test + fun codeToFhirCoding() { + var expected: Coding? = + Coding() + .setSystem("http://the-system.com") + .setCode("test") + .setDisplay("system-test") + .setVersion("1.5") + val actual = + typeConverter.toFhirCoding( + Code() + .withSystem("http://the-system.com") + .withCode("test") + .withDisplay("system-test") + .withVersion("1.5") + ) as Coding? + Assertions.assertTrue(expected!!.equalsDeep(actual)) + + expected = typeConverter.toFhirCoding(null) as Coding? + Assertions.assertNull(expected) + } + + @Test + fun conceptToFhirCodeableConcept() { + var expected = + CodeableConcept( + Coding() + .setSystem("http://the-system.com") + .setCode("test") + .setDisplay("system-test") + .setVersion("1.5") + ) + .setText("additional-text") + val actual = + typeConverter.toFhirCodeableConcept( + Concept() + .withCode( + Code() + .withSystem("http://the-system.com") + .withCode("test") + .withDisplay("system-test") + .withVersion("1.5") + ) + .withDisplay("additional-text") + ) as CodeableConcept? + Assertions.assertTrue(expected.equalsDeep(actual)) + + expected = typeConverter.toFhirCodeableConcept(null) as CodeableConcept? + Assertions.assertNull(expected) + } + + @ParameterizedTest + @MethodSource("startAndEndTimes") + fun intervalToFhirPeriodYyyyMMdd(startTime: LocalDateTime, endTime: LocalDateTime) { + val startTimeAsyyyyMMdd = YYYY_MM_DD.format(startTime) + val endTimeAsyyyyMMdd = YYYY_MM_DD.format(endTime) + + val expected = + Period() + .setStartElement(DateTimeType(startTimeAsyyyyMMdd)) + .setEndElement(DateTimeType(endTimeAsyyyyMMdd)) + val actual = + typeConverter.toFhirPeriod( + Interval( + org.opencds.cqf.cql.engine.runtime.Date(startTimeAsyyyyMMdd), + true, + org.opencds.cqf.cql.engine.runtime.Date(endTimeAsyyyyMMdd), + true, + ) + ) as Period? + Assertions.assertTrue(expected.equalsDeep(actual)) + } + + @ParameterizedTest + @MethodSource("dateTimes") + fun intervalToFhirPeriodTimestampWithOffsets( + now: LocalDateTime, + startTime: LocalDateTime, + endTime: LocalDateTime, + ) { + val zonedDateTime = ZonedDateTime.of(now, ZoneId.systemDefault()) + val defaultOffset = zonedDateTime.offset + + val startTimeWithOffset = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(startTime.atOffset(defaultOffset)) + val endTimeWithOffset = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(endTime.atOffset(defaultOffset)) + val startTimeNoOffset = + DateTimeFormatter.ISO_DATE_TIME.format(startTime.atOffset(defaultOffset)) + val endTimeNoOffset = + DateTimeFormatter.ISO_DATE_TIME.format(endTime.atOffset(defaultOffset)) + + val dateTimeTypeStart = DateTimeType(startTimeWithOffset) + val dateTimeTypeEnd = DateTimeType(endTimeWithOffset) + val expected = Period().setStartElement(dateTimeTypeStart).setEndElement(dateTimeTypeEnd) + + val dateTimeStart = DateTime(startTimeNoOffset, defaultOffset) + val dateTimeEnd = DateTime(endTimeNoOffset, defaultOffset) + val intervalStartEnd = Interval(dateTimeStart, true, dateTimeEnd, true) + val actual = typeConverter.toFhirPeriod(intervalStartEnd) as Period? + + Assertions.assertTrue(expected.equalsDeep(actual)) + } + + @ParameterizedTest + @MethodSource("startAndEndYears") + fun intervalToFhirPeriodStartAndEndYears(now: LocalDateTime, startYear: Int, endYear: Int) { + val zonedDateTime = ZonedDateTime.of(now, ZoneId.systemDefault()) + val defaultOffset = zonedDateTime.offset + + val expected = + Period() + .setStartElement(DateTimeType("$startYear-01-01T00:00:00$defaultOffset")) + .setEndElement(DateTimeType("$endYear-01-01T00:00:00$defaultOffset")) + val actual = + typeConverter.toFhirPeriod( + Interval( + DateTime("" + startYear, defaultOffset), + true, + DateTime("" + endYear, defaultOffset), + true, + ) + ) as Period? + Assertions.assertTrue(expected.equalsDeep(actual)) + } + + @Test + fun intervalToFhirPeriodNull() { + Assertions.assertNull(typeConverter.toFhirPeriod(null)) + } + + @Test + fun invalidIntervalToFhirPeriod() { + val interval = Interval(5.toCqlInteger(), true, 6.toCqlInteger(), true) + Assertions.assertThrows(IllegalArgumentException::class.java) { + typeConverter.toFhirPeriod(interval) + } + } + + @Test + fun intervalToFhirRange() { + val expected = + Range() + .setLow( + SimpleQuantity() + .setValue(BigDecimal("2.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") as SimpleQuantity? + ) + .setHigh( + SimpleQuantity() + .setValue(BigDecimal("5.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") as SimpleQuantity? + ) + var actual = + typeConverter.toFhirRange( + Interval( + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal("2.0")) + .withUnit("ml"), + true, + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal("5.0")) + .withUnit("ml"), + true, + ) + ) as Range? + Assertions.assertTrue(expected.equalsDeep(actual)) + + actual = typeConverter.toFhirRange(null) as Range? + Assertions.assertNull(actual) + } + + @Test + fun invalidIntervalToFhirRange() { + val interval = Interval(5.toCqlInteger(), true, 6.toCqlInteger(), true) + Assertions.assertThrows(IllegalArgumentException::class.java) { + typeConverter.toFhirRange(interval) + } + } + + @Test + fun intervalToFhirInterval() { + val expectedPeriod = + Period() + .setStartElement(DateTimeType("2019-02-03")) + .setEndElement(DateTimeType("2019-02-05")) + val actualPeriod = + typeConverter.toFhirInterval( + Interval( + org.opencds.cqf.cql.engine.runtime.Date("2019-02-03"), + true, + org.opencds.cqf.cql.engine.runtime.Date("2019-02-05"), + true, + ) + ) as Period? + Assertions.assertTrue(expectedPeriod.equalsDeep(actualPeriod)) + + val expectedRange = + Range() + .setLow( + SimpleQuantity() + .setValue(BigDecimal("2.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") as SimpleQuantity? + ) + .setHigh( + SimpleQuantity() + .setValue(BigDecimal("5.0")) + .setCode("ml") + .setSystem("http://unitsofmeasure.org") as SimpleQuantity? + ) + val actualRange = + typeConverter.toFhirInterval( + Interval( + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal("2.0")) + .withUnit("ml"), + true, + org.opencds.cqf.cql.engine.runtime + .Quantity() + .withValue(BigDecimal("5.0")) + .withUnit("ml"), + true, + ) + ) as Range? + Assertions.assertTrue(expectedRange.equalsDeep(actualRange)) + + val expected: IBase? = typeConverter.toFhirInterval(null) + Assertions.assertNull(expected) + } + + @Test + fun integerIntervalToFhirString() { + val interval = Interval(5.toCqlInteger(), true, 6.toCqlInteger(), true) + val result: IBase? = typeConverter.toFhirInterval(interval) + Assertions.assertNotNull(result) + val stringType = Assertions.assertInstanceOf(StringType::class.java, result) + Assertions.assertEquals("Interval[5, 6]", stringType!!.value) + val extension = + stringType + .getExtension() + .stream() + .filter { e: Extension? -> e!!.getUrl() == FhirTypeConverter.CQL_TEXT_EXT_URL } + .findFirst() + Assertions.assertTrue(extension.isPresent) + } + + @Test + fun exceptionToFhirOperationOutcome() { + val exception = IllegalArgumentException("Test exception") + exception.fillInStackTrace() + val result: IBaseOperationOutcome? = typeConverter.toFhirOperationOutcome(exception) + Assertions.assertNotNull(result) + val outcome = Assertions.assertInstanceOf(OperationOutcome::class.java, result) + Assertions.assertEquals(1, outcome!!.getIssue().size) + val issue = outcome.getIssue()[0] + Assertions.assertEquals(OperationOutcome.IssueType.EXCEPTION, issue.getCode()) + Assertions.assertEquals(OperationOutcome.IssueSeverity.ERROR, issue.getSeverity()) + Assertions.assertEquals("Test exception", issue.getDiagnostics()) + + val stackTrace = + issue + .getExtension() + .stream() + .filter { e: Extension? -> + e!!.getUrl() == FhirTypeConverter.NATIVE_STACK_TRACE_EXT_URL + } + .findFirst() + Assertions.assertTrue(stackTrace.isPresent) + Assertions.assertNotNull(stackTrace.get().getValue().toString()) + } + + @Test + fun tupleToFhirTuple() { + var actual = typeConverter.toFhirTuple(null) as Parameters.ParametersParameterComponent? + Assertions.assertNull(actual) + + val tuple = Tuple() + actual = typeConverter.toFhirTuple(tuple) as Parameters.ParametersParameterComponent + Assertions.assertNotNull(actual) + Assertions.assertEquals( + FhirTypeConverter.EMPTY_TUPLE_EXT_URL, + actual.getValue().getExtension()[0].getUrl(), + ) + + val ints = mutableListOf() + for (i in 0..4) { + ints.add(i.toCqlInteger()) + } + + tuple.elements["V"] = ints.toCqlList() + tuple.elements["W"] = null + tuple.elements["X"] = 5.toCqlInteger() + // tuple.elements["Y"] = Encounter().setId("123") + tuple.elements["Z"] = List.EMPTY_LIST + + actual = typeConverter.toFhirTuple(tuple) as Parameters.ParametersParameterComponent + val first = actual + Assertions.assertEquals(8, first.getPart().size) + + val v: MutableList = getPartsByName(first, "V") + Assertions.assertEquals(5, v.size) + Assertions.assertEquals(0, (v[0].getValue() as IntegerType).value) + + val w: Parameters.ParametersParameterComponent = getPartsByName(first, "W")[0] + Assertions.assertEquals( + FhirTypeConverter.DATA_ABSENT_REASON_EXT_URL, + w.getValue().getExtension()[0].getUrl(), + ) + + val x: Parameters.ParametersParameterComponent = getPartsByName(first, "X")[0] + Assertions.assertEquals(5, (x.getValue() as IntegerType).value) + + // val y: Parameters.ParametersParameterComponent = getPartsByName(first, "Y")[0] + // Assertions.assertEquals("123", y.getResource().getId()) + + val z: Parameters.ParametersParameterComponent = getPartsByName(first, "Z")[0] + Assertions.assertEquals( + FhirTypeConverter.EMPTY_LIST_EXT_URL, + z.getValue().getExtension()[0].getUrl(), + ) + } + + @Test + fun complexTupleToFhirTuple() { + val innerTuple = Tuple() + innerTuple.elements["X"] = Integer.ONE + innerTuple.elements["Y"] = 2.toCqlInteger() + innerTuple.elements["Z"] = null + val outerTuple = Tuple() + outerTuple.elements["A"] = innerTuple + val tupleList = ArrayList() + for (i in 0..2) { + val elementTuple = Tuple() + elementTuple.elements["P"] = i.toCqlInteger() + elementTuple.elements["Q"] = (i + 1).toCqlInteger() + tupleList.add(elementTuple) + } + outerTuple.elements["B"] = tupleList.toCqlList() + + val actual = + typeConverter.toFhirTuple(outerTuple) as Parameters.ParametersParameterComponent + Assertions.assertEquals(4, actual.getPart().size) + + val a: MutableList = getPartsByName(actual, "A") + Assertions.assertEquals(1, a.size) + Assertions.assertEquals(3, a[0].getPart().size) + val x = a[0].getPart()[0] + Assertions.assertEquals(1, (x.getValue() as IntegerType).value) + val y = a[0].getPart()[1] + Assertions.assertEquals(2, (y.getValue() as IntegerType).value) + val z = a[0].getPart()[2] + Assertions.assertEquals( + FhirTypeConverter.DATA_ABSENT_REASON_EXT_URL, + z.getValue().getExtension()[0].getUrl(), + ) + + val b: MutableList = getPartsByName(actual, "B") + Assertions.assertEquals(3, b.size) + val b1 = b[0] + val p: MutableList = getPartsByName(b1, "P") + Assertions.assertEquals(1, p.size) + Assertions.assertEquals(0, (p[0].getValue() as IntegerType).value) + val q: MutableList = getPartsByName(b1, "Q") + Assertions.assertEquals(1, q.size) + Assertions.assertEquals(1, (q[0].getValue() as IntegerType).value) + } + + // FHIR-to-CQL + @Test + fun isCqlType() { + Assertions.assertTrue(typeConverter.isCqlType(5.toCqlInteger())) + Assertions.assertTrue(typeConverter.isCqlType(BigDecimal(0).toCqlDecimal())) + Assertions.assertTrue(typeConverter.isCqlType(Code())) + + Assertions.assertFalse(typeConverter.isCqlType(Patient())) + Assertions.assertFalse(typeConverter.isCqlType(IdType())) + } + + @Test + fun iterableIsCqlType() { + val value = ArrayList() + Assertions.assertFalse(typeConverter.isCqlType(value)) + } + + @Test + fun toCqlType() { + var actual = typeConverter.toCqlType(Code()) + assertIs(actual) + + actual = typeConverter.toCqlType(IntegerType(5)) + assertIs(actual) + + actual = typeConverter.toCqlType(StringType("test")) + assertIs(actual) + + actual = typeConverter.toCqlType(IdType("test")) + assertIs(actual) + + actual = typeConverter.toCqlType(BooleanType(true)) + assertIs(actual) + + actual = typeConverter.toCqlType(DecimalType(1.0)) + assertIs(actual) + + actual = typeConverter.toCqlType(DateType(Calendar.getInstance().getTime())) + assertIs(actual) + + actual = typeConverter.toCqlType(InstantType(Calendar.getInstance())) + assertIs(actual) + + actual = typeConverter.toCqlType(DateTimeType(Calendar.getInstance())) + assertIs(actual) + + actual = typeConverter.toCqlType(TimeType("10:00:00.0000")) + assertIs