Search in sources :

Example 11 with Location

use of org.hl7.fhir.r4.model.Location in project hl7v2-fhir-converter by LinuxForHealth.

the class JvmTimeZoneIdTest method testEmptyDefaultTimeZoneYieldsJVMZoneId.

@Test
void testEmptyDefaultTimeZoneYieldsJVMZoneId() throws IOException {
    // Create our own properties file
    File configFile = new File(folder, "config.properties");
    writeSimpleProperties(configFile);
    System.setProperty(CONF_PROP_HOME, configFile.getParent());
    ConverterConfiguration.reset();
    // Prove that we're using our custom properties file with no ZoneId
    ConverterConfiguration theConvConfig = ConverterConfiguration.getInstance();
    // Four messages supported.  (Proves we're using our created file, not the default.)
    assertThat(theConvConfig.getSupportedMessageTemplates()).hasSize(13);
    // Purposely empty
    assertThat(theConvConfig.getZoneId()).isNull();
    // IMPORTANT: TimeZoneId's are different than an offset.  TimeZoneId's are a location.
    // The offset of the location changes depending on whether Daylight savings time is in effect.
    // Because we compare after processing, we can't compare locations, only offsets.
    // It is critical that when we compare offsets, we start with the same date, so the same daylight savings rules apply!
    // Otherwise a test might work only half of the year.
    // Calculate the local server zone offset
    // 20020202020000
    LocalDateTime localDateTime = LocalDateTime.of(2002, Month.FEBRUARY, 2, 2, 0, 0);
    String defaultLocalZone = TimeZone.getDefault().getID();
    ZoneId localZoneId = ZoneId.of(defaultLocalZone);
    ZonedDateTime localZonedDateTime = localDateTime.atZone(localZoneId);
    ZoneOffset localOffset = localZonedDateTime.getOffset();
    // PART 1
    // Test the format utility (which will fallback to local server time and zone offset)
    String testDateTime = DateUtil.formatToDateTimeWithDefaultZone("20020202020000");
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
    ZonedDateTime testZonedDateTime = ZonedDateTime.parse(testDateTime, dateTimeFormatter);
    ZoneOffset testOffset = testZonedDateTime.getOffset();
    // Offset from our function call test should equal offset of the local time
    assertThat(testOffset).isEqualTo(localOffset);
    // PART 2
    // Do the same for a date going through the entire conversion
    String hl7message = "MSH|^~\\&|||||20020202020000|1|PPR^PC1|331|P|2.3.1||\r" + "PID||||||||||||||||||||||||||||||\r" + "PV1||I||||||||||||||||||||||||||||||||||||||||||\r" + // PRB.2 to recordedDateTime (check time ZoneId)
    "PRB|AD|20020202020000|K80.00^Cholelithiasis^I10|53956||||||||||||\r";
    ConverterOptions customOptionsWithTenant = new Builder().withValidateResource().withPrettyPrint().build();
    List<BundleEntryComponent> e = ResourceUtils.createFHIRBundleFromHL7MessageReturnEntryList(ftv, hl7message, customOptionsWithTenant);
    // Find the condition from the FHIR bundle.
    List<Resource> conditionResource = ResourceUtils.getResourceList(e, ResourceType.Condition);
    assertThat(conditionResource).hasSize(1);
    Condition condition = (Condition) conditionResource.get(0);
    // Get the recordedDate value; convert it back to a zoned time; get the offset for comparison
    // PRB.2
    testDateTime = condition.getRecordedDateElement().getValueAsString();
    testZonedDateTime = ZonedDateTime.parse(testDateTime, dateTimeFormatter);
    testOffset = testZonedDateTime.getOffset();
    // Offset from our test should equal offset of the local time
    assertThat(testOffset).isEqualTo(localOffset);
// After the test, the properties file resets.
}
Also used : LocalDateTime(java.time.LocalDateTime) Condition(org.hl7.fhir.r4.model.Condition) ZoneId(java.time.ZoneId) ConverterOptions(io.github.linuxforhealth.hl7.ConverterOptions) Builder(io.github.linuxforhealth.hl7.ConverterOptions.Builder) Resource(org.hl7.fhir.r4.model.Resource) ConverterConfiguration(io.github.linuxforhealth.core.config.ConverterConfiguration) ZoneOffset(java.time.ZoneOffset) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) ZonedDateTime(java.time.ZonedDateTime) File(java.io.File) DateTimeFormatter(java.time.format.DateTimeFormatter) Test(org.junit.jupiter.api.Test)

Example 12 with Location

use of org.hl7.fhir.r4.model.Location in project BridgeServer2 by Sage-Bionetworks.

the class CRCController method addLocation.

/**
 * This is a nice-to-have addition of address information for the location given by an
 * ID in the appointment record. Do not fail the request if this fails, but log enough
 * to troubleshoot if the issue is on our side.
 */
void addLocation(JsonNode node, Account account, String locationId) {
    String cuimcEnv = (account.getDataGroups().contains(TEST_USER_GROUP)) ? "test" : "prod";
    String cuimcUrl = "cuimc." + cuimcEnv + ".location.url";
    String url = bridgeConfig.get(cuimcUrl);
    String reqBody = "id=\"" + locationId + "\"";
    try {
        HttpResponse response = post(url, account, reqBody);
        String resBody = IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8.name());
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200 && statusCode != 201) {
            logWarningMessage(locationId, statusCode, resBody);
            return;
        }
        JsonNode bundleJson = BridgeObjectMapper.get().readTree(resBody);
        if (!bundleJson.has("entry") || ((ArrayNode) bundleJson.get("entry")).size() == 0) {
            logWarningMessage(locationId, statusCode, resBody);
            return;
        }
        JsonNode resJson = bundleJson.get("entry").get(0).get("resource");
        if (resJson == null) {
            logWarningMessage(locationId, statusCode, resBody);
            return;
        }
        JsonNode telecom = resJson.get("telecom");
        JsonNode address = resJson.get("address");
        ArrayNode participants = (ArrayNode) node.get("participant");
        if (participants != null) {
            for (int i = 0; i < participants.size(); i++) {
                JsonNode child = participants.get(i);
                ObjectNode actor = (ObjectNode) child.get("actor");
                if (actor != null && actor.has("reference")) {
                    String ref = actor.get("reference").textValue();
                    if (ref.startsWith("Location")) {
                        if (telecom != null) {
                            actor.set("telecom", telecom);
                        }
                        if (address != null) {
                            actor.set("address", address);
                        // addGeocodingInformation(actor);
                        }
                        break;
                    }
                }
            }
        }
    } catch (IOException e) {
        LOG.warn("Error retrieving location, id = " + locationId, e);
        return;
    }
    LOG.info("Location added to appointment record for user " + account.getId());
}
Also used : ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) HttpResponse(org.apache.http.HttpResponse) JsonNode(com.fasterxml.jackson.databind.JsonNode) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) IOException(java.io.IOException) ContactPoint(org.hl7.fhir.dstu3.model.ContactPoint)

Example 13 with Location

use of org.hl7.fhir.r4.model.Location in project BridgeServer2 by Sage-Bionetworks.

the class CRCControllerTest method postAppointmentCreated.

@Test
public void postAppointmentCreated() throws Exception {
    when(mockRequest.getHeader(AUTHORIZATION)).thenReturn(AUTHORIZATION_HEADER_VALUE);
    when(mockAccountService.authenticate(any(), any())).thenReturn(account);
    when(mockAccountService.getAccount(ACCOUNT_ID)).thenReturn(Optional.of(account));
    mockGetLocation(LOCATION_JSON);
    // mockGetGeocoding();
    DateRangeResourceList<? extends ReportData> results = new DateRangeResourceList<>(ImmutableList.of());
    doReturn(results).when(mockReportService).getParticipantReport(APP_ID, TEST_USER_ID, APPOINTMENT_REPORT, HEALTH_CODE, JAN1, JAN2);
    Appointment appointment = new Appointment();
    appointment.setStatus(BOOKED);
    // add a wrong participant to verify we go through them all and look for ours
    addAppointmentParticipantComponent(appointment, "Location/foo");
    addAppointmentSageId(appointment, TEST_USER_ID);
    String json = FHIR_CONTEXT.newJsonParser().encodeResourceToString(appointment);
    mockRequestBody(mockRequest, json);
    ResponseEntity<StatusMessage> retValue = controller.postAppointment();
    assertEquals(retValue.getBody().getMessage(), "Appointment created (status = booked).");
    assertEquals(retValue.getStatusCodeValue(), 201);
    verify(mockAccountService).authenticate(eq(app), signInCaptor.capture());
    SignIn capturedSignIn = signInCaptor.getValue();
    assertEquals(capturedSignIn.getAppId(), APP_ID);
    assertEquals(capturedSignIn.getExternalId(), CUIMC_USERNAME);
    assertEquals(capturedSignIn.getPassword(), "dummy-password");
    verify(mockReportService).saveParticipantReport(eq(APP_ID), eq(TEST_USER_ID), eq(APPOINTMENT_REPORT), eq(HEALTH_CODE), reportCaptor.capture());
    ReportData capturedReport = reportCaptor.getValue();
    assertEquals(capturedReport.getDate(), "1970-01-01");
    verifyParticipant(capturedReport.getData());
    assertEquals(capturedReport.getStudyIds(), USER_STUDY_IDS);
    verify(mockAccountService).updateAccount(accountCaptor.capture());
    Account capturedAcct = accountCaptor.getValue();
    assertEquals(capturedAcct.getDataGroups(), makeSetOf(CRCController.AccountStates.TESTS_SCHEDULED, "group1"));
    assertEquals(capturedAcct.getAttributes().get(TIMESTAMP_FIELD), TIMESTAMP.toString());
    verify(mockHealthDataService).submitHealthData(eq(APP_ID), participantCaptor.capture(), dataCaptor.capture());
    HealthDataSubmission healthData = dataCaptor.getValue();
    assertEquals(healthData.getAppVersion(), "v1");
    assertEquals(healthData.getCreatedOn(), TIMESTAMP);
    assertEquals(healthData.getMetadata().toString(), "{\"type\":\"" + APPOINTMENT_REPORT + "\"}");
    assertEquals(healthData.getData().toString(), APPOINTMENT_JSON_FULLY_RESOLVED);
}
Also used : Appointment(org.hl7.fhir.dstu3.model.Appointment) Account(org.sagebionetworks.bridge.models.accounts.Account) HealthDataSubmission(org.sagebionetworks.bridge.models.healthdata.HealthDataSubmission) ReportData(org.sagebionetworks.bridge.models.reports.ReportData) SignIn(org.sagebionetworks.bridge.models.accounts.SignIn) DateRangeResourceList(org.sagebionetworks.bridge.models.DateRangeResourceList) StatusMessage(org.sagebionetworks.bridge.models.StatusMessage) Test(org.testng.annotations.Test)

Example 14 with Location

use of org.hl7.fhir.r4.model.Location in project quality-measure-and-cohort-service by Alvearie.

the class R4RestFhirTerminologyProvider method lookup.

/**
 * This is a small patch to the OSS implementation to use named-parameter lookup on
 * the operation response instead of just assuming a positional location.
 */
@Override
public Code lookup(Code code, CodeSystemInfo codeSystem) throws ResourceNotFoundException {
    Parameters respParam = fhirClient.operation().onType(CodeSystem.class).named("lookup").withParameter(Parameters.class, "code", new CodeType(code.getCode())).andParameter("system", new UriType(codeSystem.getId())).execute();
    StringType display = (StringType) respParam.getParameter("display");
    if (display != null) {
        code.withDisplay(display.getValue());
    }
    return code.withSystem(codeSystem.getId());
}
Also used : Parameters(org.hl7.fhir.r4.model.Parameters) StringType(org.hl7.fhir.r4.model.StringType) CodeType(org.hl7.fhir.r4.model.CodeType) UriType(org.hl7.fhir.r4.model.UriType)

Example 15 with Location

use of org.hl7.fhir.r4.model.Location in project openmrs-module-fhir2 by openmrs.

the class EncounterSearchQueryTest method searchForEncounters_shouldSearchForEncountersByEncounterLocationPostalCode.

@Test
public void searchForEncounters_shouldSearchForEncountersByEncounterLocationPostalCode() {
    ReferenceAndListParam locationReference = new ReferenceAndListParam();
    ReferenceParam location = new ReferenceParam();
    location.setValue(ENCOUNTER_LOCATION_POSTAL_CODE);
    location.setChain(Location.SP_ADDRESS_POSTALCODE);
    locationReference.addValue(new ReferenceOrListParam().add(location));
    SearchParameterMap theParams = new SearchParameterMap().addParameter(FhirConstants.LOCATION_REFERENCE_SEARCH_HANDLER, locationReference);
    IBundleProvider results = search(theParams);
    List<IBaseResource> resultList = get(results);
    assertThat(results, notNullValue());
    assertThat(resultList, not(empty()));
    assertThat(resultList, hasSize(greaterThanOrEqualTo(1)));
}
Also used : ReferenceParam(ca.uhn.fhir.rest.param.ReferenceParam) ReferenceAndListParam(ca.uhn.fhir.rest.param.ReferenceAndListParam) IBundleProvider(ca.uhn.fhir.rest.api.server.IBundleProvider) IBaseResource(org.hl7.fhir.instance.model.api.IBaseResource) ReferenceOrListParam(ca.uhn.fhir.rest.param.ReferenceOrListParam) SearchParameterMap(org.openmrs.module.fhir2.api.search.param.SearchParameterMap) BaseModuleContextSensitiveTest(org.openmrs.test.BaseModuleContextSensitiveTest) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)215 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)94 Location (org.hl7.fhir.r4.model.Location)93 IBundleProvider (ca.uhn.fhir.rest.api.server.IBundleProvider)71 Location (org.hl7.fhir.dstu3.model.Location)66 InputStream (java.io.InputStream)46 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)39 Matchers.containsString (org.hamcrest.Matchers.containsString)38 Test (org.junit.jupiter.api.Test)38 BaseModuleContextSensitiveTest (org.openmrs.test.BaseModuleContextSensitiveTest)37 SearchParameterMap (org.openmrs.module.fhir2.api.search.param.SearchParameterMap)35 ArrayList (java.util.ArrayList)29 Complex (org.hl7.fhir.r4.utils.formats.Turtle.Complex)29 BaseFhirProvenanceResourceTest (org.openmrs.module.fhir2.providers.BaseFhirProvenanceResourceTest)26 Reference (org.hl7.fhir.r4.model.Reference)25 Date (java.util.Date)24 Bundle (org.hl7.fhir.r4.model.Bundle)24 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)24 ReferenceAndListParam (ca.uhn.fhir.rest.param.ReferenceAndListParam)23 ReferenceOrListParam (ca.uhn.fhir.rest.param.ReferenceOrListParam)23