Search in sources :

Example 36 with Function

use of org.hl7.fhir.r5.model.ExpressionNode.Function in project hapi-fhir-jpaserver-starter by hapifhir.

the class ExampleServerR4IT method testWebsocketSubscription.

@Test
@Order(1)
void testWebsocketSubscription() throws Exception {
    /*
		 * Create subscription
		 */
    Subscription subscription = new Subscription();
    subscription.setReason("Monitor new neonatal function (note, age will be determined by the monitor)");
    subscription.setStatus(Subscription.SubscriptionStatus.REQUESTED);
    subscription.setCriteria("Observation?status=final");
    Subscription.SubscriptionChannelComponent channel = new Subscription.SubscriptionChannelComponent();
    channel.setType(Subscription.SubscriptionChannelType.WEBSOCKET);
    channel.setPayload("application/json");
    subscription.setChannel(channel);
    MethodOutcome methodOutcome = ourClient.create().resource(subscription).execute();
    IIdType mySubscriptionId = methodOutcome.getId();
    // Wait for the subscription to be activated
    await().atMost(1, TimeUnit.MINUTES).until(() -> activeSubscriptionCount() == 3);
    /*
		 * Attach websocket
		 */
    WebSocketClient myWebSocketClient = new WebSocketClient();
    SocketImplementation mySocketImplementation = new SocketImplementation(mySubscriptionId.getIdPart(), EncodingEnum.JSON);
    myWebSocketClient.start();
    URI echoUri = new URI("ws://localhost:" + port + "/websocket");
    ClientUpgradeRequest request = new ClientUpgradeRequest();
    ourLog.info("Connecting to : {}", echoUri);
    Future<Session> connection = myWebSocketClient.connect(mySocketImplementation, echoUri, request);
    Session session = connection.get(2, TimeUnit.SECONDS);
    ourLog.info("Connected to WS: {}", session.isOpen());
    /*
		 * Create a matching resource
		 */
    Observation obs = new Observation();
    obs.setStatus(Observation.ObservationStatus.FINAL);
    ourClient.create().resource(obs).execute();
    /*
		 * Ensure that we receive a ping on the websocket
		 */
    waitForSize(1, () -> mySocketImplementation.myPingCount);
    /*
		 * Clean up
		 */
    ourClient.delete().resourceById(mySubscriptionId).execute();
}
Also used : Observation(org.hl7.fhir.r4.model.Observation) ClientUpgradeRequest(org.eclipse.jetty.websocket.client.ClientUpgradeRequest) Subscription(org.hl7.fhir.r4.model.Subscription) WebSocketClient(org.eclipse.jetty.websocket.client.WebSocketClient) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) URI(java.net.URI) IIdType(org.hl7.fhir.instance.model.api.IIdType) Session(org.eclipse.jetty.websocket.api.Session) Order(org.junit.jupiter.api.Order) Test(org.junit.jupiter.api.Test) SpringBootTest(org.springframework.boot.test.context.SpringBootTest)

Example 37 with Function

use of org.hl7.fhir.r5.model.ExpressionNode.Function in project synthea by synthetichealth.

the class FhirR4 method mapCodeToCodeableConcept.

/**
 * Helper function to convert a Code into a CodeableConcept. Takes an optional system, which
 * replaces the Code.system in the resulting CodeableConcept if not null.
 *
 * @param from   The Code to create a CodeableConcept from.
 * @param system The system identifier, such as a URI. Optional; may be null.
 * @return The converted CodeableConcept
 */
private static CodeableConcept mapCodeToCodeableConcept(Code from, String system) {
    CodeableConcept to = new CodeableConcept();
    system = system == null ? null : ExportHelper.getSystemURI(system);
    from.system = ExportHelper.getSystemURI(from.system);
    if (from.display != null) {
        to.setText(from.display);
    }
    Coding coding = new Coding();
    coding.setCode(from.code);
    coding.setDisplay(from.display);
    if (from.system == null) {
        coding.setSystem(system);
    } else {
        coding.setSystem(from.system);
    }
    to.addCoding(coding);
    return to;
}
Also used : Coding(org.hl7.fhir.r4.model.Coding) CodeableConcept(org.hl7.fhir.r4.model.CodeableConcept)

Example 38 with Function

use of org.hl7.fhir.r5.model.ExpressionNode.Function in project synthea by synthetichealth.

the class FhirStu3 method mapCodeToCodeableConcept.

/**
 * Helper function to convert a Code into a CodeableConcept. Takes an optional system, which
 * replaces the Code.system in the resulting CodeableConcept if not null.
 *
 * @param from The Code to create a CodeableConcept from.
 * @param system The system identifier, such as a URI. Optional; may be null.
 * @return The converted CodeableConcept
 */
private static CodeableConcept mapCodeToCodeableConcept(Code from, String system) {
    CodeableConcept to = new CodeableConcept();
    system = system == null ? null : ExportHelper.getSystemURI(system);
    from.system = ExportHelper.getSystemURI(from.system);
    if (from.display != null) {
        to.setText(from.display);
    }
    Coding coding = new Coding();
    coding.setCode(from.code);
    coding.setDisplay(from.display);
    if (from.system == null) {
        coding.setSystem(system);
    } else {
        coding.setSystem(from.system);
    }
    to.addCoding(coding);
    return to;
}
Also used : Coding(org.hl7.fhir.dstu3.model.Coding) CodeableConcept(org.hl7.fhir.dstu3.model.CodeableConcept)

Example 39 with Function

use of org.hl7.fhir.r5.model.ExpressionNode.Function in project loinc2hpo by monarch-initiative.

the class FhirObservationAnalyzer method getHPO4ObservationOutcome.

/**
 * A core function that tries three ways to return a LabTestResultInHPO object:
 * first, it tries to return the result through the interpretation field. If it fails,
 * second, it tries to return the result through the quantative value, or
 * third, it tries to return the retult through the coded value (ordinal Loinc)
 * @param loinc2HPOannotationMap
 * @param loincIds
 * @return
 */
public static LabTestResultInHPO getHPO4ObservationOutcome(HashSet<LoincId> loincIds, Map<LoincId, UniversalLoinc2HPOAnnotation> loinc2HPOannotationMap) {
    // first make sure the observation has a valid loinc code; otherwise, we cannot handle it
    if (!hasValidLoincCode(loincIds)) {
        // TODO: consider handling this as a future project
        return null;
    }
    LoincId loincId = null;
    try {
        loincId = getLoincIdOfObservation();
    } catch (MalformedLoincCodeException e) {
        logger.error("malformed loinc code; should never happen");
        return null;
    } catch (LoincCodeNotFoundException e) {
        logger.error("No loinc code was found in the observation; should never happen");
        return null;
    } catch (UnsupportedCodingSystemException e) {
        logger.error("coding system not recognized");
        return null;
    }
    if (!loinc2HPOannotationMap.containsKey(loincId)) {
        return null;
    }
    if (observation.hasInterpretation()) {
        logger.debug("enter analyzer using the interpretation field");
        try {
            // return getHPOFromInterpretation(observation.getInterpretation(), loinc2HPOannotationMap);
            HpoTermId4LoincTest hpoterm = new ObservationAnalysisFromInterpretation(getLoincIdOfObservation(), observation.getInterpretation(), loinc2HPOannotationMap).getHPOforObservation();
            return new BasicLabTestResultInHPO(hpoterm, null);
        } catch (UnrecognizedCodeException e) {
            // this means the interpretation code is not recognized
            logger.info("The interpretation codes for this loinc code is not annotated; system will try using raw values");
        } catch (MalformedLoincCodeException e1) {
            // not going to happen
            logger.error("malformed loinc code.");
            return null;
        } catch (LoincCodeNotFoundException e2) {
            // not going to happen
            logger.error("no loinc code is found in the observation");
            return null;
        } catch (UnsupportedCodingSystemException e3) {
            // not going to happen
            logger.error("The interpretation coding system cannot be recognized.");
            return null;
        } catch (AmbiguousResultsFoundException e) {
            logger.error("The observation has conflicting interpretation codes.");
            return null;
        } catch (AnnotationNotFoundException e) {
            logger.error("There is no annotation for the loinc code used in the observation");
        }
    }
    // Qn will have a value field
    if (observation.hasValueQuantity()) {
        try {
            HpoTermId4LoincTest hpoterm = new ObservationAnalysisFromQnValue(loincId, observation, loinc2HPOannotationMap).getHPOforObservation();
            if (hpoterm != null)
                return new BasicLabTestResultInHPO(hpoterm, null);
        } catch (ReferenceNotFoundException e) {
            // if there is no reference
            logger.error("The observation has no reference field.");
        // TODO: make a list of our own references
        } catch (AmbiguousReferenceException e) {
            logger.info("There are two reference ranges or more");
        } catch (UnrecognizedCodeException e) {
            logger.error("uncognized coding system");
        }
    }
    // Ord will have a ValueCodeableConcept field
    if (observation.hasValueCodeableConcept()) {
        try {
            HpoTermId4LoincTest hpoterm = null;
            hpoterm = new ObservationAnalysisFromCodedValues(loincId, observation.getValueCodeableConcept(), loinc2HPOannotationMap).getHPOforObservation();
            if (hpoterm != null)
                return new BasicLabTestResultInHPO(hpoterm, null);
        } catch (AmbiguousResultsFoundException e) {
            logger.error("multiple results are found");
        } catch (UnrecognizedCodeException e) {
            logger.error("unrecognized codes");
        } catch (FHIRException e) {
            // not going to happen
            logger.error("Could not get HPO term from coded value");
        } catch (AnnotationNotFoundException e) {
            logger.error("There is no annotation for the loinc code used in the observation");
        }
    }
    // if all the above fails, we cannot do nothing
    logger.error("Could not return HPO for observation: " + observation.getId());
    return null;
}
Also used : FHIRException(org.hl7.fhir.exceptions.FHIRException) BasicLabTestResultInHPO(org.monarchinitiative.loinc2hpo.testresult.BasicLabTestResultInHPO)

Example 40 with Function

use of org.hl7.fhir.r5.model.ExpressionNode.Function in project dpc-app by CMSgov.

the class RESTUtils method bulkResourceHandler.

/**
 * Helper method for bulk submitting a {@link Bundle} of specific resources
 *
 * @param clazz          - {@link Class} of type of filter {@link Bundle} entries
 * @param params         - {@link Parameters} which has a {@link Parameters#getParameterFirstRep()}
 * @param resourceAction - {@link Function} which performs the actual bulk action for a single {@link BaseResource} of type {@link T}
 * @param <T>            - {@link T} generic type parameter which extends {@link BaseResource}
 * @return - {@link Bundle} containing the processed results from the bulk submission
 */
@SuppressWarnings("unchecked")
public static <T extends BaseResource> List<T> bulkResourceHandler(Class<T> clazz, Parameters params, Function<T, Response> resourceAction) {
    final Bundle resourceBundle = (Bundle) params.getParameterFirstRep().getResource();
    final Bundle bundle = new Bundle();
    bundle.setType(Bundle.BundleType.COLLECTION);
    return resourceBundle.getEntry().stream().filter(Bundle.BundleEntryComponent::hasResource).map(Bundle.BundleEntryComponent::getResource).filter(resource -> resource.getClass().equals(clazz)).map(clazz::cast).map(resource -> {
        final Response response = resourceAction.apply(resource);
        if (HttpStatus.isSuccess(response.getStatus())) {
            return (Resource) response.getEntity();
        }
        // If there's an error, rethrow the original method
        throw new WebApplicationException(response);
    }).map(r -> (T) r).collect(Collectors.toList());
}
Also used : Response(javax.ws.rs.core.Response) List(java.util.List) Response(javax.ws.rs.core.Response) org.hl7.fhir.dstu3.model(org.hl7.fhir.dstu3.model) WebApplicationException(javax.ws.rs.WebApplicationException) HttpStatus(org.eclipse.jetty.http.HttpStatus) UUID(java.util.UUID) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) WebApplicationException(javax.ws.rs.WebApplicationException)

Aggregations

Test (org.junit.jupiter.api.Test)17 List (java.util.List)8 FhirPath (au.csiro.pathling.fhirpath.FhirPath)7 Reference (org.hl7.fhir.r4.model.Reference)7 SpringBootTest (org.springframework.boot.test.context.SpringBootTest)7 ParserContext (au.csiro.pathling.fhirpath.parser.ParserContext)6 MethodOutcome (ca.uhn.fhir.rest.api.MethodOutcome)6 URI (java.net.URI)6 Row (org.apache.spark.sql.Row)6 Session (org.eclipse.jetty.websocket.api.Session)6 ClientUpgradeRequest (org.eclipse.jetty.websocket.client.ClientUpgradeRequest)6 WebSocketClient (org.eclipse.jetty.websocket.client.WebSocketClient)6 IIdType (org.hl7.fhir.instance.model.api.IIdType)6 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)6 FhirReference (org.openmrs.module.fhir2.model.FhirReference)6 FhirTask (org.openmrs.module.fhir2.model.FhirTask)6 DatasetBuilder (au.csiro.pathling.test.builders.DatasetBuilder)5 ElementPathBuilder (au.csiro.pathling.test.builders.ElementPathBuilder)5 ParserContextBuilder (au.csiro.pathling.test.builders.ParserContextBuilder)5 ArrayList (java.util.ArrayList)5