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);
}
}
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;
}
}
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);
}
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);
}
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");
}
}
}
}
Aggregations