Search in sources :

Example 26 with Library

use of org.hl7.fhir.r4b.model.Library in project cqf-ruler by DBCG.

the class ExpressionEvaluation method setupContext.

private Context setupContext(DomainResource instance, String cql, String patientId, Boolean aliasedExpression, RequestDetails theRequest) {
    JpaFhirDal jpaFhirDal = jpaFhirDalFactory.create(theRequest);
    List<CanonicalType> libraries = getLibraryReferences(instance, theRequest);
    String fhirVersion = this.fhirContext.getVersion().getVersion().getFhirVersionString();
    // Remove LocalLibrary from cache first...
    VersionedIdentifier localLibraryIdentifier = new VersionedIdentifier().withId("LocalLibrary");
    globalLibraryCache.remove(localLibraryIdentifier);
    // temporary LibraryLoader to resolve library dependencies when building
    // includes
    LibraryLoader tempLibraryLoader = libraryLoaderFactory.create(new ArrayList<LibraryContentProvider>(Arrays.asList(jpaLibraryContentProviderFactory.create(theRequest))));
    String source = "";
    if (aliasedExpression) {
        if (libraries.size() != 1) {
            throw new RuntimeException("If an aliased expression is provided, there must be exactly one primary Library");
        }
        VersionedIdentifier vi = getVersionedIdentifierFromCanonical(libraries.get(0));
        // Still not the best way to build include, but at least checks dal for an
        // existing library
        // Check if id works for LibraryRetrieval
        org.cqframework.cql.elm.execution.Library executionLibrary = null;
        try {
            executionLibrary = tempLibraryLoader.load(vi);
        } catch (Exception e) {
        // log error
        }
        if (executionLibrary == null) {
            Library library = (Library) jpaFhirDal.read(new IdType("Library", Canonicals.getIdPart(libraries.get(0))));
            vi.setId(library.getName());
            if (library.getVersion() != null) {
                vi.setVersion(library.getVersion());
            }
        }
        source = String.format("library LocalLibrary using FHIR version '" + fhirVersion + "' include FHIRHelpers version '" + fhirVersion + "' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s", buildIncludes(tempLibraryLoader, jpaFhirDal, libraries, theRequest), instance.fhirType(), instance.fhirType(), instance.fhirType(), vi.getId() + ".\"" + cql + "\"");
    } else {
        source = String.format("library LocalLibrary using FHIR version '" + fhirVersion + "' include FHIRHelpers version '" + fhirVersion + "' called FHIRHelpers %s parameter %s %s parameter \"%%context\" %s define Expression: %s", buildIncludes(tempLibraryLoader, jpaFhirDal, libraries, theRequest), instance.fhirType(), instance.fhirType(), instance.fhirType(), cql);
    }
    LibraryLoader libraryLoader = libraryLoaderFactory.create(new ArrayList<LibraryContentProvider>(Arrays.asList(jpaLibraryContentProviderFactory.create(theRequest), new InMemoryLibraryContentProvider(Arrays.asList(source)))));
    // resolve execution context
    return setupContext(instance, patientId, libraryLoader, theRequest);
}
Also used : LibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.LibraryContentProvider) InMemoryLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibraryContentProvider) InMemoryLibraryContentProvider(org.opencds.cqf.cql.evaluator.cql2elm.content.InMemoryLibraryContentProvider) JpaFhirDal(org.opencds.cqf.ruler.cql.JpaFhirDal) CanonicalType(org.hl7.fhir.r4.model.CanonicalType) LibraryLoader(org.opencds.cqf.cql.engine.execution.LibraryLoader) IdType(org.hl7.fhir.r4.model.IdType) VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) Library(org.hl7.fhir.r4.model.Library)

Example 27 with Library

use of org.hl7.fhir.r4b.model.Library in project cqf-ruler by DBCG.

the class DataOperationProviderIT method testDstu3MeasureDataRequirementsOperation.

@Disabled("Erroring because could not convert r5 Library to dstu3")
@Test
public void testDstu3MeasureDataRequirementsOperation() throws IOException {
    String bundleAsText = stringFromResource("Exm105Dstu3MeasureBundle.json");
    Bundle bundle = (Bundle) getFhirContext().newJsonParser().parseResource(bundleAsText);
    getClient().transaction().withBundle(bundle).execute();
    Parameters params = new Parameters();
    params.addParameter().setName("startPeriod").setValue(new StringType("2019-01-01"));
    params.addParameter().setName("endPeriod").setValue(new StringType("2020-01-01"));
    Library returnLibrary = getClient().operation().onInstance(new IdType("Measure", "measure-EXM105-FHIR3-8.0.000")).named("$data-requirements").withParameters(params).returnResourceType(Library.class).execute();
    assertNotNull(returnLibrary);
}
Also used : Parameters(org.hl7.fhir.dstu3.model.Parameters) StringType(org.hl7.fhir.dstu3.model.StringType) Bundle(org.hl7.fhir.dstu3.model.Bundle) Library(org.hl7.fhir.dstu3.model.Library) IdType(org.hl7.fhir.dstu3.model.IdType) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) RestIntegrationTest(org.opencds.cqf.ruler.test.RestIntegrationTest) Disabled(org.junit.jupiter.api.Disabled)

Example 28 with Library

use of org.hl7.fhir.r4b.model.Library in project cqf-ruler by DBCG.

the class ElmCacheResourceChangeListener method invalidateCacheById.

private void invalidateCacheById(IIdType theId) {
    if (!theId.getResourceType().equals("Library")) {
        return;
    }
    try {
        IBaseResource library = this.myLibraryDao.read(theId);
        String name = this.myNameFunction.apply(library);
        String version = this.myVersionFunction.apply(library);
        this.myGlobalLibraryCache.remove(new VersionedIdentifier().withId(name).withVersion(version));
    }// name and version.
     catch (Exception e) {
        // TODO: This needs to be smarter... the issue is that ELM is cached with
        // library name and version as the key since
        // that's the access path the CQL engine uses, but change notifications occur
        // with the resource Id, which is not
        // necessarily tied to the resource name. In any event, if a unknown resource is
        // deleted, clear all libraries as a workaround.
        // One option is to maintain a cache with multiple indices.
        ourLog.debug("Failed to locate resource {} to look up name and version. Clearing all libraries from cache.", theId.getValueAsString());
        this.myGlobalLibraryCache.clear();
    }
}
Also used : VersionedIdentifier(org.cqframework.cql.elm.execution.VersionedIdentifier) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource)

Example 29 with Library

use of org.hl7.fhir.r4b.model.Library in project cqf-ruler by DBCG.

the class ActivityDefinitionApplyProvider method resolveActivityDefinition.

// For library use
public Resource resolveActivityDefinition(ActivityDefinition activityDefinition, String patientId, String practitionerId, String organizationId, RequestDetails theRequest) throws FHIRException {
    Resource result = newResource(activityDefinition.getKind().toCode());
    switch(result.fhirType()) {
        case "ServiceRequest":
            result = resolveServiceRequest(activityDefinition, patientId, practitionerId, organizationId);
            break;
        case "MedicationRequest":
            result = resolveMedicationRequest(activityDefinition, patientId);
            break;
        case "SupplyRequest":
            result = resolveSupplyRequest(activityDefinition, practitionerId, organizationId);
            break;
        case "Procedure":
            result = resolveProcedure(activityDefinition, patientId);
            break;
        case "DiagnosticReport":
            result = resolveDiagnosticReport(activityDefinition, patientId);
            break;
        case "Communication":
            result = resolveCommunication(activityDefinition, patientId);
            break;
        case "CommunicationRequest":
            result = resolveCommunicationRequest(activityDefinition, patientId);
            break;
        case "Task":
            result = resolveTask(activityDefinition, patientId);
            break;
    }
    for (ActivityDefinition.ActivityDefinitionDynamicValueComponent dynamicValue : activityDefinition.getDynamicValue()) {
        // ActivityDefinition apply operation does not fail.
        try {
            if (dynamicValue.getExpression() != null) {
                // Special case for setting a Patient reference
                if ("Patient".equals(dynamicValue.getExpression().getExpression())) {
                    this.modelResolver.setValue(result, dynamicValue.getPath(), new Reference(patientId));
                } else {
                    /*
						 * TODO: Passing the activityDefinition as context here because that's what will
						 * have the libraries, but perhaps the "context" here should be the result
						 * resource?
						 */
                    Object value = expressionEvaluation.evaluateInContext(activityDefinition, dynamicValue.getExpression().getExpression(), patientId, theRequest);
                    if (value != null) {
                        logger.debug("dynamicValue value: {}", value);
                        if (value instanceof Boolean) {
                            value = new BooleanType((Boolean) value);
                        } else if (value instanceof DateTime) {
                            value = Date.from(((DateTime) value).getDateTime().toInstant());
                        } else if (value instanceof String) {
                            value = new StringType((String) value);
                        }
                        this.modelResolver.setValue(result, dynamicValue.getPath(), value);
                    } else {
                        logger.warn("WARNING: ActivityDefinition has null value for path: {}", dynamicValue.getPath());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("ERROR: ActivityDefinition dynamicValue {} could not be applied and threw exception {}", dynamicValue.getPath(), e.toString());
            logger.error(e.toString());
        }
    }
    return result;
}
Also used : StringType(org.hl7.fhir.r4.model.StringType) Reference(org.hl7.fhir.r4.model.Reference) Resource(org.hl7.fhir.r4.model.Resource) BooleanType(org.hl7.fhir.r4.model.BooleanType) DateTime(org.opencds.cqf.cql.engine.runtime.DateTime) InternalErrorException(ca.uhn.fhir.rest.server.exceptions.InternalErrorException) FHIRException(org.hl7.fhir.exceptions.FHIRException) ActivityDefinition(org.hl7.fhir.r4.model.ActivityDefinition)

Example 30 with Library

use of org.hl7.fhir.r4b.model.Library in project cqf-ruler by DBCG.

the class CqlExecutionProviderIT method testDataBundleCqlExecutionProviderWithSubject.

@Test
public void testDataBundleCqlExecutionProviderWithSubject() throws Exception {
    Parameters params = new Parameters();
    Parameters libraryParameter = new Parameters();
    params.addParameter().setName("subject").setValue(new StringType("Patient/SimplePatient"));
    libraryParameter.addParameter().setName("url").setValue(new StringType(this.getClient().getServerBase() + "Library/SimpleDstu3Library"));
    libraryParameter.addParameter().setName("name").setValue(new StringType("SimpleDstu3Library"));
    params.addParameter().setName("library").setResource(libraryParameter);
    params.addParameter().setName("expression").setValue(new StringType("SimpleDstu3Library.\"observationRetrieve\""));
    String packagePrefix = "org/opencds/cqf/ruler/cpg/dstu3/provider/";
    loadResource(packagePrefix + "SimpleDstu3Library.json");
    loadResource(packagePrefix + "SimplePatient.json");
    Bundle data = (Bundle) loadResource(packagePrefix + "SimpleDataBundle.json");
    params.addParameter().setName("data").setResource(data);
    params.addParameter().setName("useServerData").setValue(new BooleanType(false));
    Parameters results = getClient().operation().onServer().named("$cql").withParameters(params).execute();
    assertTrue(results.getParameter().get(0).getResource() instanceof Bundle);
    assertTrue(((Bundle) results.getParameter().get(0).getResource()).getEntry().get(0).getResource() instanceof Observation);
    assertTrue(results.getParameter().get(1).getValue() instanceof StringType);
    assertTrue(((StringType) results.getParameter().get(1).getValue()).asStringValue().equals("List"));
    logger.debug("Results: ", results);
}
Also used : Parameters(org.hl7.fhir.dstu3.model.Parameters) StringType(org.hl7.fhir.dstu3.model.StringType) Bundle(org.hl7.fhir.dstu3.model.Bundle) BooleanType(org.hl7.fhir.dstu3.model.BooleanType) Observation(org.hl7.fhir.dstu3.model.Observation) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) RestIntegrationTest(org.opencds.cqf.ruler.test.RestIntegrationTest)

Aggregations

Library (org.hl7.fhir.r4.model.Library)130 Test (org.junit.Test)85 Measure (org.hl7.fhir.r4.model.Measure)60 Patient (org.hl7.fhir.r4.model.Patient)41 HashMap (java.util.HashMap)36 Test (org.junit.jupiter.api.Test)34 ArrayList (java.util.ArrayList)32 Library (org.hl7.fhir.dstu3.model.Library)23 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)21 ByteArrayOutputStream (java.io.ByteArrayOutputStream)21 CapabilityStatement (org.hl7.fhir.r4.model.CapabilityStatement)21 MeasureReport (org.hl7.fhir.r4.model.MeasureReport)21 StringType (org.hl7.fhir.r4.model.StringType)21 IOException (java.io.IOException)20 VersionedIdentifier (org.cqframework.cql.elm.execution.VersionedIdentifier)20 FhirContext (ca.uhn.fhir.context.FhirContext)19 IParser (ca.uhn.fhir.parser.IParser)19 MeasureEvidenceOptions (com.ibm.cohort.engine.measure.evidence.MeasureEvidenceOptions)19 Bundle (org.hl7.fhir.r4.model.Bundle)19 Parameter (com.ibm.cohort.cql.evaluation.parameters.Parameter)18