Search in sources :

Example 81 with ResourceType

use of org.hl7.fhir.dstu3.model.ResourceType in project health-patterns by LinuxForHealth.

the class DeIdentifier method postResource.

/**
 * Posts the given Resource to the FHIR server
 *
 * @param fhirResource the resource to post
 * @return the FHIR response of executing the POST operation
 * @throws DeIdentifierException if there is a problem posting the resource
 */
@SuppressWarnings("unchecked")
private String postResource(JsonNode fhirResource) throws DeIdentifierException {
    System.out.println("Initializing FHIR create resource...");
    IParser parser = fhirClient.getFhirContext().newJsonParser();
    // We don't know exactly what type of Resource we are going to POST to FHiR and the FHIR requires
    // that when parsing a Resource a concrete class is used, so we load the concrete type reflexively
    ClassLoader classLoader = this.getClass().getClassLoader();
    Class<? extends Resource> aClass = null;
    String resourceType = getResourceType(fhirResource);
    try {
        aClass = (Class<? extends Resource>) classLoader.loadClass("org.hl7.fhir.r4.model." + resourceType);
    } catch (ClassNotFoundException e) {
        throw new DeIdentifierException("A Resource of type '" + resourceType + "' could not be found in the current HAPI FHIR JAR: " + e.getMessage(), e);
    }
    Resource resource = parser.parseResource(aClass, fhirResource.toString());
    MethodOutcome outcome;
    try {
        outcome = fhirClient.create().resource(resource).encodedJson().execute();
    } catch (BaseServerResponseException e) {
        throw new DeIdentifierException("The FHIR transaction could not be executed: " + e.getMessage(), e);
    }
    System.out.println("FHIR create resource done!");
    return outcome.getId().toString();
}
Also used : Resource(org.hl7.fhir.r4.model.Resource) BaseServerResponseException(ca.uhn.fhir.rest.server.exceptions.BaseServerResponseException) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) IParser(ca.uhn.fhir.parser.IParser)

Example 82 with ResourceType

use of org.hl7.fhir.dstu3.model.ResourceType in project health-patterns by LinuxForHealth.

the class TerminologyService method installTranslationResources.

/**
 * Install the default translation FHIR resources on the FHIR server.
 *
 * @param fileNames the resources to install
 */
private void installTranslationResources(String... fileNames) {
    boolean errors = false;
    for (String fileName : fileNames) {
        InputStream configInputStream = this.getClass().getResourceAsStream(MAPPINGS_DIRECTORY + fileName);
        String mappingResource;
        try {
            mappingResource = IOUtils.toString(configInputStream, Charset.defaultCharset());
        } catch (IOException e) {
            System.err.println("Could not read default FHIR mapping resource: " + fileName + ", the Terminology Service won't be functional: " + e.getMessage());
            errors = true;
            continue;
        }
        JsonNode mappingResourceJson;
        try {
            mappingResourceJson = jsonDeserializer.readTree(mappingResource);
        } catch (JsonProcessingException e) {
            System.err.println("The default FHIR resource JSON file " + fileName + " is not valid JSON , the Terminology Service may not be functional: " + e.getMessage());
            errors = true;
            continue;
        }
        String resourceType = getResourceType(mappingResourceJson);
        String id = mappingResourceJson.get(ID_OBJECT).asText();
        Class<? extends IBaseResource> type = null;
        if (resourceType.equals(VALUE_SET_TYPE)) {
            type = ValueSet.class;
        } else if (resourceType.equals(CONCEPT_MAP_TYPE)) {
            type = ConceptMap.class;
        } else {
            System.err.println("Unknown resource type " + type + " for mapping FHIR resource JSON file " + fileName + ", the Terminology Service may not be functional.");
            errors = true;
            continue;
        }
        Bundle bundle = fhirClient.search().forResource(type).withIdAndCompartment(id, null).returnBundle(Bundle.class).execute();
        // We save the URI of the resources that this Terminology Service uses, that either are already there or were installed
        // in case a consumer needs access to them, such as a test case to clean up
        installedResources.add(fhirClient.getServerBase() + "/" + type.getSimpleName() + "/" + id);
        if (bundle.getEntry().isEmpty()) {
            System.out.println("Did not find Terminology Service FHIR mapping resource '" + type.getCanonicalName() + "' with ID '" + id + "' in the FHIR server, installing...");
            MethodOutcome outcome = fhirClient.update().resource(mappingResource).encodedJson().execute();
            IIdType newId = outcome.getId();
            System.out.println("Installed Terminology Service FHIR mapping resource in the FHIR server: " + newId.getValue());
        } else {
            System.out.println("Terminology Service FHIR mapping resource '" + type.getCanonicalName() + "' with ID '" + id + "' is already intalled in the FHIR server.");
        }
    }
    fhirResourcesInstalled = !errors;
}
Also used : InputStream(java.io.InputStream) Bundle(org.hl7.fhir.r4.model.Bundle) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) ConceptMap(org.hl7.fhir.r4.model.ConceptMap) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) IIdType(org.hl7.fhir.instance.model.api.IIdType)

Example 83 with ResourceType

use of org.hl7.fhir.dstu3.model.ResourceType in project openmrs-module-fhir2 by openmrs.

the class FhirImmunizationServiceImplTest method saveImmunization_shouldCreateEncounterAndObsGroupWhenNewImmunization.

@Test
public void saveImmunization_shouldCreateEncounterAndObsGroupWhenNewImmunization() {
    // setup
    FhirContext ctx = FhirContext.forR4();
    IParser parser = ctx.newJsonParser();
    Immunization newImmunization = parser.parseResource(Immunization.class, "{\n" + "  \"resourceType\": \"Immunization\",\n" + "  \"status\": \"completed\",\n" + "  \"vaccineCode\": {\n" + "    \"coding\": [\n" + "      {\n" + "        \"code\": \"15f83cd6-64e9-4e06-a5f9-364d3b14a43d\",\n" + "        \"display\": \"Aspirin as a vaccine\"\n" + "      }\n" + "    ]\n" + "  },\n" + "  \"patient\": {\n" + "    \"reference\": \"Patient/a7e04421-525f-442f-8138-05b619d16def\",\n" + "    \"type\": \"Patient\"\n" + "  },\n" + "  \"encounter\": {\n" + "    \"reference\": \"Encounter/7d8c1980-6b78-11e0-93c3-18a905e044dc\",\n" + "    \"type\": \"Encounter\"\n" + "  },\n" + "  \"occurrenceDateTime\": \"2020-07-08T18:30:00.000Z\",\n" + "  \"manufacturer\": {\n" + "    \"display\": \"Acme\"\n" + "  },\n" + "  \"lotNumber\": \"FOO1234\",\n" + "  \"expirationDate\": \"2022-07-31T18:30:00.000Z\",\n" + "  \"performer\": [\n" + "    {\n" + "      \"actor\": {\n" + "        \"reference\": \"Practitioner/f9badd80-ab76-11e2-9e96-0800200c9a66\",\n" + "        \"type\": \"Practitioner\"\n" + "      }\n" + "    }\n" + "  ],\n" + "  \"protocolApplied\": [\n" + "    {\n" + "      \"doseNumberPositiveInt\": 2,\n" + "      \"series\": \"Dose 2\"\n" + "    }\n" + "  ]\n" + "}");
    // replay
    Immunization savedImmunization = service.create(newImmunization);
    Obs obs = obsService.getObsByUuid(savedImmunization.getId());
    // verify
    helper.validateImmunizationObsGroup(obs);
    assertObsCommons(obs, "a7e04421-525f-442f-8138-05b619d16def", "7d8c1980-6b78-11e0-93c3-18a905e044dc", "f9badd80-ab76-11e2-9e96-0800200c9a66");
    obs.getGroupMembers().forEach(o -> assertObsCommons(o, "a7e04421-525f-442f-8138-05b619d16def", "7d8c1980-6b78-11e0-93c3-18a905e044dc", "f9badd80-ab76-11e2-9e96-0800200c9a66"));
    Map<String, Obs> members = helper.getObsMembersMap(obs);
    assertThat(members.get(CIEL_984).getValueCoded().getUuid(), is("15f83cd6-64e9-4e06-a5f9-364d3b14a43d"));
    assertThat(members.get(CIEL_1410).getValueDatetime(), equalTo(new DateTimeType("2020-07-08T18:30:00.000Z").getValue()));
    assertThat(members.get(CIEL_1418).getValueNumeric(), equalTo(2.0));
    assertThat(members.get(CIEL_1419).getValueText(), is("Acme"));
    assertThat(members.get(CIEL_1420).getValueText(), is("FOO1234"));
    assertThat(members.get(CIEL_165907).getValueDatetime(), equalTo(new DateTimeType("2022-07-31T18:30:00.000Z").getValue()));
}
Also used : Obs(org.openmrs.Obs) FhirContext(ca.uhn.fhir.context.FhirContext) Immunization(org.hl7.fhir.r4.model.Immunization) DateTimeType(org.hl7.fhir.r4.model.DateTimeType) IParser(ca.uhn.fhir.parser.IParser) BaseModuleContextSensitiveTest(org.openmrs.test.BaseModuleContextSensitiveTest) Test(org.junit.Test)

Example 84 with ResourceType

use of org.hl7.fhir.dstu3.model.ResourceType in project openmrs-module-fhir2 by openmrs.

the class PatientFhirResourceProviderIntegrationTest method shouldReturnForPatientTypeEverythingWhenCountIsSpecifiedAsJson.

@Test
public void shouldReturnForPatientTypeEverythingWhenCountIsSpecifiedAsJson() throws Exception {
    MockHttpServletResponse response = get("/Patient/$everything?_count=5").accept(FhirMediaTypes.JSON).go();
    assertThat(response, isOk());
    assertThat(response.getContentType(), is(FhirMediaTypes.JSON.toString()));
    assertThat(response.getContentAsString(), notNullValue());
    Bundle result = readBundleResponse(response);
    assertThat(result, notNullValue());
    assertThat(result.getType(), equalTo(Bundle.BundleType.SEARCHSET));
    assertThat(result, hasProperty("total", equalTo(46)));
    assertThat(result.getEntry(), hasSize(5));
    List<Bundle.BundleEntryComponent> entries = result.getEntry();
    assertThat(entries, everyItem(hasProperty("fullUrl", startsWith("http://localhost/ws/fhir2/R4/"))));
    assertThat(entries, everyItem(hasResource(hasProperty("resourceType", in(getEverythingValidResourceTypes())))));
}
Also used : Bundle(org.hl7.fhir.r4.model.Bundle) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Example 85 with ResourceType

use of org.hl7.fhir.dstu3.model.ResourceType in project openmrs-module-fhir2 by openmrs.

the class PatientFhirResourceProviderIntegrationTest method shouldReturnPatientTypeEverythingAsJson.

@Test
public void shouldReturnPatientTypeEverythingAsJson() throws Exception {
    MockHttpServletResponse response = get("/Patient/$everything").accept(FhirMediaTypes.JSON).go();
    assertThat(response, isOk());
    assertThat(response.getContentType(), is(FhirMediaTypes.JSON.toString()));
    assertThat(response.getContentAsString(), notNullValue());
    Bundle result = readBundleResponse(response);
    assertThat(result, notNullValue());
    assertThat(result.getType(), equalTo(Bundle.BundleType.SEARCHSET));
    assertThat(result, hasProperty("total", equalTo(46)));
    assertThat(result.getEntry(), hasSize(46));
    List<Bundle.BundleEntryComponent> entries = result.getEntry();
    assertThat(entries, everyItem(hasProperty("fullUrl", startsWith("http://localhost/ws/fhir2/R4/"))));
    assertThat(entries, everyItem(hasResource(hasProperty("resourceType", in(getEverythingValidResourceTypes())))));
}
Also used : Bundle(org.hl7.fhir.r4.model.Bundle) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) Test(org.junit.Test)

Aggregations

JsonElement (com.google.gson.JsonElement)33 HashSet (java.util.HashSet)26 Bundle (org.hl7.fhir.r4.model.Bundle)24 ResourceType (org.hl7.fhir.r4.model.Enumerations.ResourceType)21 Test (org.junit.Test)20 Nonnull (javax.annotation.Nonnull)18 ArrayList (java.util.ArrayList)15 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)10 FhirContext (ca.uhn.fhir.context.FhirContext)9 File (java.io.File)9 Row (org.apache.spark.sql.Row)9 IdType (org.hl7.fhir.dstu3.model.IdType)9 BundleEntryComponent (org.hl7.fhir.r4.model.Bundle.BundleEntryComponent)9 JsonObject (com.google.gson.JsonObject)8 Test (org.junit.jupiter.api.Test)8 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)8 IOException (java.io.IOException)7 List (java.util.List)7 Bundle (org.hl7.fhir.dstu3.model.Bundle)7 Resource (org.hl7.fhir.r4.model.Resource)7