Search in sources :

Example 61 with IParser

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

the class SeedCommand method seedOrganizationBundle.

private void seedOrganizationBundle(FHIREntityConverter converter, DSLContext context, IParser parser) throws IOException {
    try (final InputStream orgBundleStream = SeedCommand.class.getClassLoader().getResourceAsStream(ORGANIZATION_BUNDLE)) {
        if (orgBundleStream == null) {
            throw new MissingResourceException("Can not find seeds file", this.getClass().getName(), CSV);
        }
        final Bundle bundle = parser.parseResource(Bundle.class, orgBundleStream);
        final List<EndpointEntity> endpointEntities = BundleParser.parse(Endpoint.class, bundle, (endpoint) -> converter.fromFHIR(EndpointEntity.class, endpoint), ORGANIZATION_ID);
        final List<OrganizationEntity> organizationEntities = BundleParser.parse(Organization.class, bundle, (org) -> converter.fromFHIR(OrganizationEntity.class, org), ORGANIZATION_ID);
        organizationEntities.stream().map(entity -> organizationEntityToRecord(context, entity)).forEach(context::executeInsert);
        endpointEntities.stream().map(entity -> endpointsEntityToRecord(context, entity)).forEach(context::executeInsert);
    }
}
Also used : FHIREntityConverter(gov.cms.dpc.fhir.converters.FHIREntityConverter) java.util(java.util) RosterUtils(gov.cms.dpc.attribution.jdbi.RosterUtils) DSL(org.jooq.impl.DSL) Connection(java.sql.Connection) LoggerFactory(org.slf4j.LoggerFactory) PatientsRecord(gov.cms.dpc.attribution.dao.tables.records.PatientsRecord) FhirContext(ca.uhn.fhir.context.FhirContext) Namespace(net.sourceforge.argparse4j.inf.Namespace) org.hl7.fhir.dstu3.model(org.hl7.fhir.dstu3.model) DSLContext(org.jooq.DSLContext) ProvidersRecord(gov.cms.dpc.attribution.dao.tables.records.ProvidersRecord) ZoneOffset(java.time.ZoneOffset) OrganizationEndpoints(gov.cms.dpc.attribution.dao.tables.OrganizationEndpoints) DPCAttributionConfiguration(gov.cms.dpc.attribution.DPCAttributionConfiguration) IParser(ca.uhn.fhir.parser.IParser) Environment(io.dropwizard.setup.Environment) OrganizationEndpointsRecord(gov.cms.dpc.attribution.dao.tables.records.OrganizationEndpointsRecord) Application(io.dropwizard.Application) EnvironmentCommand(io.dropwizard.cli.EnvironmentCommand) Logger(org.slf4j.Logger) ManagedDataSource(io.dropwizard.db.ManagedDataSource) Subparser(net.sourceforge.argparse4j.inf.Subparser) Settings(org.jooq.conf.Settings) IOException(java.io.IOException) Patients(gov.cms.dpc.attribution.dao.tables.Patients) PooledDataSourceFactory(io.dropwizard.db.PooledDataSourceFactory) RenderQuotedNames(org.jooq.conf.RenderQuotedNames) Providers(gov.cms.dpc.attribution.dao.tables.Providers) OffsetDateTime(java.time.OffsetDateTime) Organizations(gov.cms.dpc.attribution.dao.tables.Organizations) OrganizationsRecord(gov.cms.dpc.attribution.dao.tables.records.OrganizationsRecord) gov.cms.dpc.common.entities(gov.cms.dpc.common.entities) DBUtils(gov.cms.dpc.attribution.utils.DBUtils) SeedProcessor(gov.cms.dpc.common.utils.SeedProcessor) InputStream(java.io.InputStream) InputStream(java.io.InputStream)

Example 62 with IParser

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

the class SeedCommand method seedPatientBundle.

private Map<String, Reference> seedPatientBundle(FHIREntityConverter converter, DSLContext context, IParser parser, UUID organizationID) throws IOException {
    try (final InputStream providerBundleStream = SeedCommand.class.getClassLoader().getResourceAsStream(PATIENT_BUNDLE)) {
        final Parameters parameters = parser.parseResource(Parameters.class, providerBundleStream);
        final Bundle patientBundle = (Bundle) parameters.getParameterFirstRep().getResource();
        final List<PatientEntity> patients = BundleParser.parse(Patient.class, patientBundle, (patient) -> converter.fromFHIR(PatientEntity.class, patient), organizationID);
        Map<String, Reference> patientReferences = new HashMap<>();
        patients.stream().peek(entity -> {
            final OrganizationEntity organization = new OrganizationEntity();
            organization.setId(organizationID);
            entity.setOrganization(organization);
        }).map(entity -> patientEntityToRecord(context, entity)).peek(context::executeInsert).forEach(record -> {
            final Reference ref = new Reference(new IdType("Patient", record.getId().toString()));
            patientReferences.put(record.getBeneficiaryId(), ref);
        });
        return patientReferences;
    }
}
Also used : FHIREntityConverter(gov.cms.dpc.fhir.converters.FHIREntityConverter) java.util(java.util) RosterUtils(gov.cms.dpc.attribution.jdbi.RosterUtils) DSL(org.jooq.impl.DSL) Connection(java.sql.Connection) LoggerFactory(org.slf4j.LoggerFactory) PatientsRecord(gov.cms.dpc.attribution.dao.tables.records.PatientsRecord) FhirContext(ca.uhn.fhir.context.FhirContext) Namespace(net.sourceforge.argparse4j.inf.Namespace) org.hl7.fhir.dstu3.model(org.hl7.fhir.dstu3.model) DSLContext(org.jooq.DSLContext) ProvidersRecord(gov.cms.dpc.attribution.dao.tables.records.ProvidersRecord) ZoneOffset(java.time.ZoneOffset) OrganizationEndpoints(gov.cms.dpc.attribution.dao.tables.OrganizationEndpoints) DPCAttributionConfiguration(gov.cms.dpc.attribution.DPCAttributionConfiguration) IParser(ca.uhn.fhir.parser.IParser) Environment(io.dropwizard.setup.Environment) OrganizationEndpointsRecord(gov.cms.dpc.attribution.dao.tables.records.OrganizationEndpointsRecord) Application(io.dropwizard.Application) EnvironmentCommand(io.dropwizard.cli.EnvironmentCommand) Logger(org.slf4j.Logger) ManagedDataSource(io.dropwizard.db.ManagedDataSource) Subparser(net.sourceforge.argparse4j.inf.Subparser) Settings(org.jooq.conf.Settings) IOException(java.io.IOException) Patients(gov.cms.dpc.attribution.dao.tables.Patients) PooledDataSourceFactory(io.dropwizard.db.PooledDataSourceFactory) RenderQuotedNames(org.jooq.conf.RenderQuotedNames) Providers(gov.cms.dpc.attribution.dao.tables.Providers) OffsetDateTime(java.time.OffsetDateTime) Organizations(gov.cms.dpc.attribution.dao.tables.Organizations) OrganizationsRecord(gov.cms.dpc.attribution.dao.tables.records.OrganizationsRecord) gov.cms.dpc.common.entities(gov.cms.dpc.common.entities) DBUtils(gov.cms.dpc.attribution.utils.DBUtils) SeedProcessor(gov.cms.dpc.common.utils.SeedProcessor) InputStream(java.io.InputStream) InputStream(java.io.InputStream)

Example 63 with IParser

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

the class FHIRDSTU2ExporterTest method testFHIRDSTU2Export.

@Test
public void testFHIRDSTU2Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirDstu2.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    FhirValidator validator = ctx.newValidator();
    validator.setValidateAgainstStandardSchema(true);
    validator.setValidateAgainstStandardSchematron(true);
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        Config.set("exporter.fhir_dstu2.export", "true");
        FhirDstu2.TRANSACTION_BUNDLE = person.randBoolean();
        String fhirJson = FhirDstu2.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 (Entry entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateWithResult(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    if (emessage.getMessage().contains("start SHALL have a lower value than end")) {
                        continue;
                    }
                    System.out.println(parser.encodeResourceToString(entry.getResource()));
                    System.out.println("ERROR: " + emessage.getMessage());
                    validationErrors.add(emessage.getMessage());
                }
            }
            if (entry.getResource() instanceof DiagnosticReport) {
                DiagnosticReport report = (DiagnosticReport) entry.getResource();
                if (report.getPerformer().isEmpty()) {
                    validationErrors.add("Performer is a required field on DiagnosticReport!");
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            Exporter.export(person, System.currentTimeMillis());
        }
        return validationErrors;
    });
    assertTrue("Validation of exported FHIR bundle failed: " + String.join("|", errors), errors.size() == 0);
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Entry(ca.uhn.fhir.model.dstu2.resource.Bundle.Entry) SingleValidationMessage(ca.uhn.fhir.validation.SingleValidationMessage) Bundle(ca.uhn.fhir.model.dstu2.resource.Bundle) ArrayList(java.util.ArrayList) DiagnosticReport(org.hl7.fhir.dstu3.model.DiagnosticReport) FhirValidator(ca.uhn.fhir.validation.FhirValidator) ValidationResult(ca.uhn.fhir.validation.ValidationResult) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 64 with IParser

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

the class FHIRR4ExporterTest method testFHIRR4Export.

@Test
public void testFHIRR4Export() throws Exception {
    TestHelper.loadTestProperties();
    Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
    Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());
    FhirContext ctx = FhirR4.getContext();
    IParser parser = ctx.newJsonParser().setPrettyPrint(true);
    ValidationResources validator = new ValidationResources();
    List<String> errors = ParallelTestingService.runInParallel((person) -> {
        List<String> validationErrors = new ArrayList<String>();
        TestHelper.exportOff();
        FhirR4.TRANSACTION_BUNDLE = person.randBoolean();
        FhirR4.USE_US_CORE_IG = person.randBoolean();
        FhirR4.USE_SHR_EXTENSIONS = false;
        String fhirJson = FhirR4.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...
        // IMPORTANT: this approach significantly reduces memory usage when compared to
        // validating the entire bundle at a time, but means that validating references
        // is impossible.
        // As of 2021-01-05, validating the bundle didn't validate references anyway,
        // but at some point we may want to do that.
        Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
        for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
            ValidationResult eresult = validator.validateR4(entry.getResource());
            if (!eresult.isSuccessful()) {
                for (SingleValidationMessage emessage : eresult.getMessages()) {
                    boolean valid = false;
                    if (emessage.getSeverity() == ResultSeverityEnum.INFORMATION || emessage.getSeverity() == ResultSeverityEnum.WARNING) {
                        /*
               * Ignore warnings.
               */
                        valid = true;
                    }
                    if (!valid) {
                        System.out.println(parser.encodeResourceToString(entry.getResource()));
                        System.out.println("ERROR: " + emessage.getMessage());
                        validationErrors.add(emessage.getMessage());
                    }
                }
            }
        }
        if (!validationErrors.isEmpty()) {
            FailedExportHelper.dumpInfo("FHIRR4", 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.r4.model.Bundle) ArrayList(java.util.ArrayList) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) ValidationResult(ca.uhn.fhir.validation.ValidationResult) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

Example 65 with IParser

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

the class FHIRR4ExporterTest method testObservationAttachment.

@Test
public void testObservationAttachment() 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("Pulmonary Resistance", 0.1552);
    person.attributes.put("BMI Multiplier", 0.055);
    person.setVitalSign(VitalSign.BMI, 21.0);
    person.history = new LinkedList<>();
    Provider mock = Mockito.mock(Provider.class);
    Mockito.when(mock.getResourceID()).thenReturn("Mock-Provider");
    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 physiology = module.getState("Simulate_CVS");
    assertTrue(physiology.process(person, time));
    person.history.add(physiology);
    State encounter = module.getState("SomeEncounter");
    assertTrue(encounter.process(person, time));
    person.history.add(encounter);
    State chartState = module.getState("ChartObservation");
    assertTrue(chartState.process(person, time));
    person.history.add(chartState);
    State urlState = module.getState("UrlObservation");
    assertTrue(urlState.process(person, time));
    person.history.add(urlState);
    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 Media) {
            Media media = (Media) entry.getResource();
            if (media.getContent().getData() != null) {
                assertEquals(400, media.getWidth());
                assertEquals(200, media.getHeight());
                assertEquals("Invasive arterial pressure", media.getReasonCode().get(0).getText());
                assertTrue(Base64.isBase64(media.getContent().getDataElement().getValueAsString()));
            } else if (media.getContent().getUrl() != null) {
                assertEquals("https://example.com/image/12498596132", media.getContent().getUrl());
                assertEquals("en-US", media.getContent().getLanguage());
                assertTrue(media.getContent().getSize() > 0);
            } else {
                fail("Invalid Media element in output JSON");
            }
        }
    }
}
Also used : FhirContext(ca.uhn.fhir.context.FhirContext) Bundle(org.hl7.fhir.r4.model.Bundle) Media(org.hl7.fhir.r4.model.Media) Provider(org.mitre.synthea.world.agents.Provider) BundleEntryComponent(org.hl7.fhir.r4.model.Bundle.BundleEntryComponent) State(org.mitre.synthea.engine.State) Module(org.mitre.synthea.engine.Module) Person(org.mitre.synthea.world.agents.Person) IParser(ca.uhn.fhir.parser.IParser) Test(org.junit.Test)

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