Search in sources :

Example 16 with Server

use of org.hl7.gravity.refimpl.sdohexchange.model.Server in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method evaluateMeasure.

@POST
@Path("/evaluation")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces({ MediaType.APPLICATION_JSON })
@ApiOperation(value = "Evaluates a measure bundle for a single patient", notes = EVALUATION_API_NOTES, response = String.class, tags = { "Measure Evaluation" }, nickname = "evaluate_measure", extensions = { @Extension(properties = { @ExtensionProperty(name = DarkFeatureSwaggerFilter.DARK_FEATURE_NAME, value = CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION) }) })
@ApiImplicitParams({ // This is necessary for the dark launch feature
@ApiImplicitParam(access = DarkFeatureSwaggerFilter.DARK_FEATURE_CONTROLLED, paramType = "header", dataType = "string"), // These are necessary to create a proper view of the request body that is all wrapped up in the Liberty IMultipartBody parameter
@ApiImplicitParam(name = REQUEST_DATA_PART, value = EXAMPLE_REQUEST_DATA_JSON, dataTypeClass = MeasureEvaluation.class, required = true, paramType = "form", type = "file"), @ApiImplicitParam(name = MEASURE_PART, value = EXAMPLE_MEASURE_ZIP, dataTypeClass = File.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation: This API returns the JSON representation of a FHIR MeasureReport. A full example can be found at https://www.hl7.org/fhir/measurereport-cms146-cat1-example.html"), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response evaluateMeasure(@Context HttpServletRequest request, @ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody) {
    final String methodName = MethodNames.EVALUATE_MEASURE.getName();
    Response response = null;
    // Error out if feature is not enabled
    ServiceBaseUtility.isDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION);
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        if (multipartBody == null) {
            throw new IllegalArgumentException("A multipart/form-data body is required");
        }
        IAttachment metadataAttachment = multipartBody.getAttachment(REQUEST_DATA_PART);
        if (metadataAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", REQUEST_DATA_PART));
        }
        IAttachment measureAttachment = multipartBody.getAttachment(MEASURE_PART);
        if (measureAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", MEASURE_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        MeasureEvaluation evaluationRequest = om.readValue(metadataAttachment.getDataHandler().getInputStream(), MeasureEvaluation.class);
        // validate the contents of the evaluationRequest
        validateBean(evaluationRequest);
        FhirContext fhirContext = FhirContext.forR4();
        try (InputStream is = measureAttachment.getDataHandler().getInputStream();
            RetrieveCacheContext retrieveCacheContext = new DefaultRetrieveCacheContext()) {
            MeasureEvaluator evaluator = createMeasureEvaluator(is, evaluationRequest.getDataServerConfig(), evaluationRequest.getTerminologyServerConfig(), evaluationRequest.isExpandValueSets(), evaluationRequest.getSearchPageSize(), retrieveCacheContext, fhirContext);
            MeasureReport report = evaluator.evaluatePatientMeasure(evaluationRequest.getPatientId(), evaluationRequest.getMeasureContext(), evaluationRequest.getEvidenceOptions());
            // The default serializer gets into an infinite loop when trying to serialize MeasureReport, so we use the
            // HAPI encoder instead.
            IParser parser = fhirContext.newJsonParser();
            ResponseBuilder responseBuilder = Response.status(Response.Status.OK).header("Content-Type", "application/json").entity(parser.encodeResourceToString(report));
            response = responseBuilder.build();
        }
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        response = new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) MeasureEvaluation(com.ibm.cohort.engine.api.service.model.MeasureEvaluation) PatientListMeasureEvaluation(com.ibm.cohort.engine.api.service.model.PatientListMeasureEvaluation) ZipInputStream(java.util.zip.ZipInputStream) InputStream(java.io.InputStream) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) RetrieveCacheContext(com.ibm.cohort.engine.measure.cache.RetrieveCacheContext) MeasureReport(org.hl7.fhir.r4.model.MeasureReport) DefaultRetrieveCacheContext(com.ibm.cohort.engine.measure.cache.DefaultRetrieveCacheContext) MeasureEvaluator(com.ibm.cohort.engine.measure.MeasureEvaluator) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(ca.uhn.fhir.parser.IParser) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 17 with Server

use of org.hl7.gravity.refimpl.sdohexchange.model.Server in project quality-measure-and-cohort-service by Alvearie.

the class CohortEngineRestHandler method getMeasureParameters.

@POST
@Path("/fhir/measure/identifier/{measure_identifier_value}/parameters")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@ApiOperation(value = "Get measure parameters", notes = CohortEngineRestHandler.MEASURE_API_NOTES, response = MeasureParameterInfoList.class, authorizations = { @Authorization(value = "BasicAuth") }, responseContainer = "List", tags = { "FHIR Measures" })
@ApiImplicitParams({ @ApiImplicitParam(name = FHIR_DATA_SERVER_CONFIG_PART, value = CohortEngineRestHandler.EXAMPLE_DATA_SERVER_CONFIG_JSON, dataTypeClass = FhirServerConfig.class, required = true, paramType = "form", type = "file") })
@ApiResponses(value = { @ApiResponse(code = 200, message = "Successful Operation", response = MeasureParameterInfoList.class), @ApiResponse(code = 400, message = "Bad Request", response = ServiceErrorList.class), @ApiResponse(code = 500, message = "Server Error", response = ServiceErrorList.class) })
public Response getMeasureParameters(@ApiParam(value = ServiceBaseConstants.MINOR_VERSION_DESCRIPTION, required = true, defaultValue = ServiceBuildConstants.DATE) @QueryParam(CohortEngineRestHandler.VERSION) String version, @ApiParam(hidden = true, type = "file", required = true) IMultipartBody multipartBody, @ApiParam(value = CohortEngineRestHandler.MEASURE_IDENTIFIER_VALUE_DESC, required = true) @PathParam(CohortEngineRestHandler.MEASURE_IDENTIFIER_VALUE) String measureIdentifierValue, @ApiParam(value = CohortEngineRestHandler.MEASURE_IDENTIFIER_SYSTEM_DESC, required = false) @QueryParam(CohortEngineRestHandler.MEASURE_IDENTIFIER_SYSTEM) String measureIdentifierSystem, @ApiParam(value = CohortEngineRestHandler.MEASURE_VERSION_DESC, required = false) @QueryParam(CohortEngineRestHandler.MEASURE_VERSION) String measureVersion) {
    final String methodName = MethodNames.GET_MEASURE_PARAMETERS.getName();
    Response response = null;
    try {
        // Perform api setup
        Response errorResponse = ServiceBaseUtility.apiSetup(version, logger, methodName);
        if (errorResponse != null) {
            return errorResponse;
        }
        IAttachment dataSourceAttachment = multipartBody.getAttachment(FHIR_DATA_SERVER_CONFIG_PART);
        if (dataSourceAttachment == null) {
            throw new IllegalArgumentException(String.format("Missing '%s' MIME attachment", FHIR_DATA_SERVER_CONFIG_PART));
        }
        // deserialize the MeasuresEvaluation request
        ObjectMapper om = new ObjectMapper();
        FhirServerConfig fhirServerConfig = om.readValue(dataSourceAttachment.getDataHandler().getInputStream(), FhirServerConfig.class);
        // validate the contents of the fhirServerConfig
        validateBean(fhirServerConfig);
        // get the fhir client object used to call to FHIR
        FhirClientBuilder clientBuilder = FhirClientBuilderFactory.newInstance().newFhirClientBuilder();
        IGenericClient measureClient = clientBuilder.createFhirClient(fhirServerConfig);
        // build the identifier object which is used by the fhir client
        // to find the measure
        Identifier identifier = new Identifier().setValue(measureIdentifierValue).setSystem(measureIdentifierSystem);
        // resolve the measure, and return the parameter info for all the libraries linked to by the measure
        FhirResourceResolver<Measure> measureResolver = R4FhirServerResourceResolverFactory.createMeasureResolver(measureClient);
        List<MeasureParameterInfo> parameterInfoList = FHIRRestUtils.getParametersForMeasureIdentifier(measureResolver, identifier, measureVersion);
        // return the results
        MeasureParameterInfoList status = new MeasureParameterInfoList().measureParameterInfoList(parameterInfoList);
        response = Response.ok(status).build();
    } catch (Throwable e) {
        // map any exceptions caught into the proper REST error response objects
        return new CohortServiceExceptionMapper().toResponse(e);
    } finally {
        // Perform api cleanup
        Response errorResponse = ServiceBaseUtility.apiCleanup(logger, methodName);
        if (errorResponse != null) {
            response = errorResponse;
        }
    }
    return response;
}
Also used : MeasureParameterInfo(com.ibm.cohort.engine.api.service.model.MeasureParameterInfo) FhirClientBuilder(com.ibm.cohort.fhir.client.config.FhirClientBuilder) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) IAttachment(com.ibm.websphere.jaxrs20.multipart.IAttachment) Response(javax.ws.rs.core.Response) ApiResponse(io.swagger.annotations.ApiResponse) Identifier(org.hl7.fhir.r4.model.Identifier) Measure(org.hl7.fhir.r4.model.Measure) MeasureParameterInfoList(com.ibm.cohort.engine.api.service.model.MeasureParameterInfoList) FhirServerConfig(com.ibm.cohort.fhir.client.config.FhirServerConfig) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Path(javax.ws.rs.Path) ApiImplicitParams(io.swagger.annotations.ApiImplicitParams) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 18 with Server

use of org.hl7.gravity.refimpl.sdohexchange.model.Server in project quality-measure-and-cohort-service by Alvearie.

the class CDMMeasureEvaluationTest method testSetReportMeasureToMeasureId__measureFromBundleWithoutMetaVersion__onlyMeasurePortionWithoutHistoryOnReport.

@Test
public void testSetReportMeasureToMeasureId__measureFromBundleWithoutMetaVersion__onlyMeasurePortionWithoutHistoryOnReport() {
    MeasureReport report = new MeasureReport();
    String bundleInput = "{\"resourceType\":\"Bundle\",\"id\":\"98765\",\"entry\":[{\"fullUrl\":\"https://full-url-to/fhir-server/api/v4/Measure/id1\",\"resource\":{\"resourceType\":\"Measure\",\"id\":\"id1\"}}]}";
    Measure measure = (Measure) fhirParser.parseResource(Bundle.class, bundleInput).getEntryFirstRep().getResource();
    CDMMeasureEvaluation.setReportMeasureToMeasureId(report, measure);
    assertEquals("Measure/id1", report.getMeasure());
}
Also used : Bundle(org.hl7.fhir.r4.model.Bundle) Measure(org.hl7.fhir.r4.model.Measure) MeasureReport(org.hl7.fhir.r4.model.MeasureReport) Test(org.junit.Test)

Example 19 with Server

use of org.hl7.gravity.refimpl.sdohexchange.model.Server in project quality-measure-and-cohort-service by Alvearie.

the class MeasureHelperTest method testResolveByCanonicalUrl.

@Test
public void testResolveByCanonicalUrl() throws Exception {
    Measure measure = getCohortMeasure("Test", getLibrary("123", DEFAULT_VERSION, "cql/basic/Test-1.0.0.xml"), "Female");
    measure.setUrl("http://fhir.ibm.com/fhir-server/api/v4/Measure/Test-1.0.0");
    MappingBuilder builder = get(urlMatching("/Measure\\?url=.*&_format=json"));
    mockFhirResourceRetrieval(builder, getBundle(measure));
    Measure actual = MeasureHelper.loadMeasure(measure.getUrl(), resolver);
    assertNotNull(actual);
    assertEquals("Test", actual.getName());
}
Also used : MappingBuilder(com.github.tomakehurst.wiremock.client.MappingBuilder) Measure(org.hl7.fhir.r4.model.Measure) Test(org.junit.Test)

Example 20 with Server

use of org.hl7.gravity.refimpl.sdohexchange.model.Server in project quality-measure-and-cohort-service by Alvearie.

the class DefaultVT method testMeasureEvaluationByMeasureIdentifier.

// to tag a specific test to be part of DVT (deployment verification test)
@Category(DVT.class)
@Test
public /**
 * Test a successful measure evaluation using identifier and version as the lookup key
 */
void testMeasureEvaluationByMeasureIdentifier() throws Exception {
    // You want -Denabled.dark.features=all in your Liberty jvm.options
    Assume.assumeTrue(isServiceDarkFeatureEnabled(CohortEngineRestConstants.DARK_LAUNCHED_MEASURE_EVALUATION));
    final String RESOURCE = getUrlBase() + CohortServiceAPISpec.CREATE_DELETE_EVALUATION_PATH;
    FhirContext fhirContext = FhirContext.forR4();
    IParser parser = fhirContext.newJsonParser().setPrettyPrint(true);
    Library library = TestHelper.getTemplateLibrary();
    Identifier identifier = new Identifier().setValue("measure-identifier").setSystem("http://ibm.com/health/test");
    Measure measure = TestHelper.getTemplateMeasure(library);
    measure.setIdentifier(Arrays.asList(identifier));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    TestHelper.createMeasureArtifact(baos, parser, measure, library);
    // Files.write( baos.toByteArray(), new File("target/test_measure_v1_0_0.zip"));
    Map<String, Parameter> parameterOverrides = new HashMap<>();
    parameterOverrides.put("Measurement Period", new IntervalParameter(new DateParameter("2019-07-04"), true, new DateParameter("2020-07-04"), true));
    MeasureEvaluation requestData = new MeasureEvaluation();
    requestData.setDataServerConfig(dataServerConfig);
    requestData.setTerminologyServerConfig(termServerConfig);
    // This is a patient ID that is assumed to exist in the target FHIR server
    requestData.setPatientId(VALID_PATIENT_ID);
    requestData.setMeasureContext(new MeasureContext(null, parameterOverrides, new com.ibm.cohort.engine.measure.Identifier(identifier.getSystem(), identifier.getValue()), measure.getVersion()));
    requestData.setEvidenceOptions(new MeasureEvidenceOptions(false, MeasureEvidenceOptions.DefineReturnOptions.NONE));
    ObjectMapper om = new ObjectMapper();
    System.out.println(om.writeValueAsString(requestData));
    RequestSpecification request = buildBaseRequest(new Headers()).queryParam(CohortEngineRestHandler.VERSION, ServiceBuildConstants.DATE).multiPart(CohortEngineRestHandler.REQUEST_DATA_PART, requestData, "application/json").multiPart(CohortEngineRestHandler.MEASURE_PART, "test_measure_v1_0_0.zip", new ByteArrayInputStream(baos.toByteArray()));
    ValidatableResponse response = request.post(RESOURCE, getServiceVersion()).then();
    ValidatableResponse vr = runSuccessValidation(response, ContentType.JSON, HttpStatus.SC_OK);
    String expected = getJsonFromFile(ServiceAPIGlobalSpec.EXP_FOLDER_TYPE, "measure_evaluation_exp.json");
    String actual = vr.extract().asString();
    assertMeasureReportEquals(parser, expected, actual, false);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) ValidatableResponse(com.jayway.restassured.response.ValidatableResponse) HashMap(java.util.HashMap) MeasureEvaluation(com.ibm.cohort.engine.api.service.model.MeasureEvaluation) PatientListMeasureEvaluation(com.ibm.cohort.engine.api.service.model.PatientListMeasureEvaluation) Headers(com.jayway.restassured.response.Headers) RequestSpecification(com.jayway.restassured.specification.RequestSpecification) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MeasureEvidenceOptions(com.ibm.cohort.engine.measure.evidence.MeasureEvidenceOptions) MeasureContext(com.ibm.cohort.engine.measure.MeasureContext) Identifier(org.hl7.fhir.r4.model.Identifier) DateParameter(com.ibm.cohort.cql.evaluation.parameters.DateParameter) ByteArrayInputStream(java.io.ByteArrayInputStream) Measure(org.hl7.fhir.r4.model.Measure) DateParameter(com.ibm.cohort.cql.evaluation.parameters.DateParameter) Parameter(com.ibm.cohort.cql.evaluation.parameters.Parameter) IntervalParameter(com.ibm.cohort.cql.evaluation.parameters.IntervalParameter) Library(org.hl7.fhir.r4.model.Library) IntervalParameter(com.ibm.cohort.cql.evaluation.parameters.IntervalParameter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IParser(ca.uhn.fhir.parser.IParser) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)107 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)100 IOException (java.io.IOException)47 OperationOutcome (org.hl7.fhir.r4.model.OperationOutcome)42 FHIRException (org.hl7.fhir.exceptions.FHIRException)39 OperationOutcome (org.hl7.fhir.dstu3.model.OperationOutcome)38 ArrayList (java.util.ArrayList)25 BaseFhirIntegrationTest (org.openmrs.module.fhir2.BaseFhirIntegrationTest)24 FileNotFoundException (java.io.FileNotFoundException)21 TerminologyServiceException (org.hl7.fhir.exceptions.TerminologyServiceException)19 Date (java.util.Date)18 Bundle (org.hl7.fhir.r4.model.Bundle)17 URISyntaxException (java.net.URISyntaxException)16 HashMap (java.util.HashMap)16 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)16 FhirContext (ca.uhn.fhir.context.FhirContext)14 LocalDate (java.time.LocalDate)14 NoTerminologyServiceException (org.hl7.fhir.exceptions.NoTerminologyServiceException)13 File (java.io.File)12 Header (org.apache.http.Header)11