Search in sources :

Example 66 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project synthea by synthetichealth.

the class FHIRR4ExporterTest method testSampledDataExport.

@Test
public void testSampledDataExport() throws Exception {
    Person person = new Person(0L);
    person.attributes.put(Person.GENDER, "F");
    person.attributes.put(Person.FIRST_LANGUAGE, "spanish");
    person.attributes.put(Person.RACE, "other");
    person.attributes.put(Person.ETHNICITY, "hispanic");
    person.attributes.put(Person.INCOME, Integer.parseInt(Config.get("generate.demographics.socioeconomic.income.poverty")) * 2);
    person.attributes.put(Person.OCCUPATION_LEVEL, 1.0);
    person.attributes.put(Person.CONTACT_EMAIL, "test@test.test");
    person.attributes.put(Person.CONTACT_GIVEN_NAME, "John");
    person.attributes.put(Person.CONTACT_FAMILY_NAME, "Appleseed");
    person.history = new LinkedList<>();
    Provider mock = Mockito.mock(Provider.class);
    Mockito.when(mock.getResourceID()).thenReturn("Mock-UUID");
    person.setProvider(EncounterType.AMBULATORY, mock);
    person.setProvider(EncounterType.WELLNESS, mock);
    person.setProvider(EncounterType.EMERGENCY, mock);
    person.setProvider(EncounterType.INPATIENT, mock);
    Long time = System.currentTimeMillis();
    int age = 35;
    long birthTime = time - Utilities.convertTime("years", age);
    person.attributes.put(Person.BIRTHDATE, birthTime);
    Payer.loadNoInsurance();
    for (int i = 0; i < age; i++) {
        long yearTime = time - Utilities.convertTime("years", i);
        person.coverage.setPayerAtTime(yearTime, Payer.noInsurance);
    }
    Module module = TestHelper.getFixture("observation.json");
    State encounter = module.getState("SomeEncounter");
    assertTrue(encounter.process(person, time));
    person.history.add(encounter);
    State physiology = module.getState("Simulate_CVS");
    assertTrue(physiology.process(person, time));
    person.history.add(physiology);
    State sampleObs = module.getState("SampledDataObservation");
    assertTrue(sampleObs.process(person, time));
    person.history.add(sampleObs);
    FhirContext ctx = FhirR4.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    String fhirJson = FhirR4.convertToFHIRJson(person, System.currentTimeMillis());
    Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
    for (BundleEntryComponent entry : bundle.getEntry()) {
        if (entry.getResource() instanceof Observation) {
            Observation obs = (Observation) entry.getResource();
            assertTrue(obs.getValue() instanceof SampledData);
            SampledData data = (SampledData) obs.getValue();
            // 0.01s == 10ms
            assertEquals(10, data.getPeriod().doubleValue(), 0.001);
            assertEquals(3, (int) data.getDimensions());
        }
    }
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Bundle(org.hl7.fhir.r4.model.Bundle) Provider(org.mitre.synthea.world.agents.Provider) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) State(org.mitre.synthea.engine.State) Observation(org.hl7.fhir.r4.model.Observation) SampledData(org.hl7.fhir.r4.model.SampledData) Module(org.mitre.synthea.engine.Module) Person(org.mitre.synthea.world.agents.Person) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 67 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project synthea by synthetichealth.

the class FHIRSTU3ExporterTest method testFHIRSTU3Export.

@Test
public void testFHIRSTU3Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirStu3.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);
    ValidationResources validationResources = new ValidationResources();
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        TestHelper.exportOff();
        Config.set("exporter.fhir_stu3.export", "true");
        Config.set("exporter.fhir.use_shr_extensions", "true");
        FhirStu3.TRANSACTION_BUNDLE = person.randBoolean();
        String fhirJson = FhirStu3.convertToFHIRJson(person, System.currentTimeMillis());
        // (these should have been converted into URIs)
        if (fhirJson.contains("SNOMED-CT")) {
            validationErrors.add("JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
        }
        // let's crack open the Bundle and validate
        // each individual entry.resource to get context-sensitive error
        // messages...
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (BundleEntryComponent entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateWithResult(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    boolean valid = false;
                    if (emessage.getMessage().contains("@ Observation obs-7")) {
                        /*
               * The obs-7 invariant basically says that Observations should have values, unless
               * they are made of components. This test replaces an invalid XPath expression
               * that was causing correct instances to fail validation.
               */
                        valid = validateObs7((Observation) entry.getResource());
                    } else if (emessage.getMessage().contains("@ Condition con-4")) {
                        /*
               * The con-4 invariant says "If condition is abated, then clinicalStatus must be
               * either inactive, resolved, or remission" which is very clear and sensical.
               * However, the XPath expression does not evaluate correctly for valid instances,
               * so we must manually validate.
               */
                        valid = validateCon4((Condition) entry.getResource());
                    } else if (emessage.getMessage().contains("@ MedicationRequest mps-1")) {
                        /*
               * The mps-1 invariant says MedicationRequest.requester.onBehalfOf can only be
               * specified if MedicationRequest.requester.agent is practitioner or device.
               * But the invariant is poorly written and does not correctly handle references
               * starting with "urn:uuid"
               */
                        // ignore this error
                        valid = true;
                    } else if (emessage.getMessage().contains("per-1: If present, start SHALL have a lower value than end")) {
                        /*
               * The per-1 invariant does not account for daylight savings time... so, if the
               * daylight savings switch happens between the start and end, the validation
               * fails, even if it is valid.
               */
                        // ignore this error
                        valid = true;
                    }
                    if (!valid) {
                        System.out.println(parser.encodeResourceToString(entry.getResource()));
                        System.out.println("ERROR: " + emessage.getMessage());
                        validationErrors.add(emessage.getMessage());
                    }
                }
            }
            // Check ExplanationOfBenefit Resources against BlueButton
            if (entry.getResource().fhirType().equals("ExplanationOfBenefit")) {
                ValidationResult bbResult = validationResources.validateSTU3(entry.getResource());
                for (SingleValidationMessage message : bbResult.getMessages()) {
                    if (message.getMessage().contains("extension https://bluebutton.cms.gov/assets")) {
                        /*
               * The instance validator complains about the BlueButton extensions, ignore
               */
                        continue;
                    } else if (message.getSeverity() == ResultSeverityEnum.ERROR) {
                        if (!(message.getMessage().contains("Element 'ExplanationOfBenefit.id': minimum required = 1, but only found 0") || message.getMessage().contains("Could not verify slice for profile"))) {
                            // For some reason the validator is not detecting the IDs on the resources,
                            // even though they appear to be present while debugging and during normal
                            // operations.
                            System.out.println(message.getSeverity() + ": " + message.getMessage());
                            Assert.fail(message.getSeverity() + ": " + message.getMessage());
                        }
                    }
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            FailedExportHelper.dumpInfo("FHIRSTU3", fhirJson, validationErrors, person);
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(org.hl7.fhir.dstu3.model.Bundle) ArrayList(java.util.ArrayList) FhirValidator(ca.uhn.fhir.validation.FhirValidator) ValidationResult(ca.uhn.fhir.validation.ValidationResult) BundleEntryComponent(org.hl7.fhir.dstu3.model.Bundle.BundleEntryComponent) Observation(org.hl7.fhir.dstu3.model.Observation) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 68 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project bunsen by cerner.

the class BunsenTestStu3ProfileProvider method load.

private static void load(PrePopulatedValidationSupport support, IParser jsonParser, String resource) {
    try (InputStream input = BunsenTestStu3ProfileProvider.class.getClassLoader().getResourceAsStream(resource)) {
        StructureDefinition definition = (StructureDefinition) jsonParser.parseResource(new InputStreamReader(input));
        support.addStructureDefinition(definition);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}
Also used : StructureDefinition(org.hl7.fhir.dstu3.model.StructureDefinition) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 69 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project bunsen by cerner.

the class UsCoreStu3ProfileProvider method load.

private static void load(PrePopulatedValidationSupport support, IParser jsonParser, String resource) {
    try (InputStream input = UsCoreStu3ProfileProvider.class.getClassLoader().getResourceAsStream(resource)) {
        StructureDefinition definition = (StructureDefinition) jsonParser.parseResource(new InputStreamReader(input));
        support.addStructureDefinition(definition);
    } catch (IOException exception) {
        throw new RuntimeException(exception);
    }
}
Also used : StructureDefinition(org.hl7.fhir.dstu3.model.StructureDefinition) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 70 with IParser

use of org.hl7.fhir.r4b.formats.IParser in project dpc-app by CMSgov.

the class OrganizationResourceTest method testUpdateOrganization.

@Test
void testUpdateOrganization() throws IOException, URISyntaxException, GeneralSecurityException {
    final String orgID = UUID.randomUUID().toString();
    final IParser parser = ctx.newJsonParser();
    final IGenericClient attrClient = APITestHelpers.buildAttributionClient(ctx);
    final String macaroon = FHIRHelpers.registerOrganization(attrClient, parser, orgID, "1111121111", getAdminURL());
    final Pair<UUID, PrivateKey> uuidPrivateKeyPair = APIAuthHelpers.generateAndUploadKey("org-update-key", orgID, GOLDEN_MACAROON, getBaseURL());
    final IGenericClient client = APIAuthHelpers.buildAuthenticatedClient(ctx, getBaseURL(), macaroon, uuidPrivateKeyPair.getLeft(), uuidPrivateKeyPair.getRight());
    Organization organization = client.read().resource(Organization.class).withId(orgID).encodedJson().execute();
    assertNotNull(organization);
    organization.setName("New Org Name");
    organization.setContact(Lists.emptyList());
    MethodOutcome outcome = client.update().resource(organization).execute();
    Organization result = (Organization) outcome.getResource();
    assertEquals("1111121111", result.getIdentifierFirstRep().getValue());
    assertEquals(organization.getName(), result.getName(), "Name should be updated");
    assertTrue(organization.getContact().isEmpty(), "Contact list should be updated");
    assertEquals(1, result.getEndpoint().size(), "Endpoint list should be unchanged");
    // Try to update when authenticated as different organization
    final String org2ID = UUID.randomUUID().toString();
    final String org2Macaroon = FHIRHelpers.registerOrganization(attrClient, parser, org2ID, "4321234211", getAdminURL());
    final Pair<UUID, PrivateKey> org2UUIDPrivateKeyPair = APIAuthHelpers.generateAndUploadKey("org2-update-key", org2ID, GOLDEN_MACAROON, getBaseURL());
    final IGenericClient org2Client = APIAuthHelpers.buildAuthenticatedClient(ctx, getBaseURL(), org2Macaroon, org2UUIDPrivateKeyPair.getLeft(), org2UUIDPrivateKeyPair.getRight());
    IUpdateTyped update = org2Client.update().resource(organization);
    assertThrows(AuthenticationException.class, update::execute);
}
Also used : PrivateKey(java.security.PrivateKey) Organization(org.hl7.fhir.dstu3.model.Organization) IUpdateTyped(ca.uhn.fhir.rest.gclient.IUpdateTyped) IGenericClient(ca.uhn.fhir.rest.client.api.IGenericClient) UUID(java.util.UUID) MethodOutcome(ca.uhn.fhir.rest.api.MethodOutcome) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.jupiter.api.Test) AbstractSecureApplicationTest(gov.cms.dpc.api.AbstractSecureApplicationTest)

Aggregations

IParser (ca.uhn.fhir.parser.IParser)89 FhirContext (ca.uhn.fhir.context.FhirContext)43 IOException (java.io.IOException)35 ByteArrayOutputStream (java.io.ByteArrayOutputStream)30 Test (org.junit.Test)24 InputStream (java.io.InputStream)22 IParser (org.hl7.fhir.r5.formats.IParser)19 JsonParser (org.hl7.fhir.r5.formats.JsonParser)18 Test (org.junit.jupiter.api.Test)18 FHIRException (org.hl7.fhir.exceptions.FHIRException)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 File (java.io.File)16 FileInputStream (java.io.FileInputStream)16 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)15 Bundle (org.hl7.fhir.r4.model.Bundle)14 FileOutputStream (java.io.FileOutputStream)12 Bundle (org.hl7.fhir.dstu3.model.Bundle)12 IBaseResource (org.hl7.fhir.instance.model.api.IBaseResource)12 XmlParser (org.hl7.fhir.r5.formats.XmlParser)12 ArrayList (java.util.ArrayList)11