org.hl7.fhir.r4.model.Bundle.BundleEntryComponent Java Examples

The following examples show how to use org.hl7.fhir.r4.model.Bundle.BundleEntryComponent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FhirR4.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Helper function to create an Entry for the given Resource within the given Bundle. Sets the
 * resourceID to a random UUID, sets the entry's fullURL to that resourceID, and adds the entry to
 * the bundle.
 *
 * @param bundle   The Bundle to add the Entry to
 * @param resource Resource the new Entry should contain
 * @param resourceID The Resource ID to assign
 * @return the created Entry
 */
private static BundleEntryComponent newEntry(Bundle bundle, Resource resource,
    String resourceID) {
  BundleEntryComponent entry = bundle.addEntry();

  resource.setId(resourceID);
  entry.setFullUrl(getUrlPrefix(resource.fhirType()) + resourceID);
  entry.setResource(resource);

  if (TRANSACTION_BUNDLE) {
    BundleEntryRequestComponent request = entry.getRequest();
    request.setMethod(HTTPVerb.POST);
    request.setUrl(resource.getResourceType().name());
    entry.setRequest(request);
  }

  return entry;
}
 
Example #2
Source File: Unbundler.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
private static void unbundle(String src) throws FHIRFormatError, FileNotFoundException, IOException {
  String folder = Utilities.getDirectoryForFile(src);
  Bundle bnd = (Bundle) new JsonParser().parse(new FileInputStream(src));
  for (BundleEntryComponent be : bnd.getEntry()) {
    Resource r = be.getResource();
    if (r != null) {
      if (StringUtils.isBlank(r.getId())) {
        if (r instanceof MetadataResource)
          r.setId(tail((MetadataResource) r));
      }
      if (!StringUtils.isBlank(r.getId())) {
        String tgt = Utilities.path(folder, r.fhirType()+"-"+r.getId()+".json");
        if (!new File(tgt).exists())
          new JsonParser().compose(new FileOutputStream(tgt), r);
      }
    }
  }
}
 
Example #3
Source File: GraphQLEngineTests.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
@Override
public Bundle search(Object appInfo, String type, List<Argument> searchParams) throws FHIRException {
  try {
    Bundle bnd = new Bundle();
    BundleLinkComponent bl = bnd.addLink();
    bl.setRelation("next");
    bl.setUrl("http://test.fhir.org/r4/Patient?_format=text/xhtml&search-id=77c97e03-8a6c-415f-a63d-11c80cf73f&&active=true&_sort=_id&search-offset=50&_count=50");
    bl = bnd.addLink();
    bl.setRelation("self");
    bl.setUrl("http://test.fhir.org/r4/Patient?_format=text/xhtml&search-id=77c97e03-8a6c-415f-a63d-11c80cf73f&&active=true&_sort=_id&search-offset=0&_count=50");
    BundleEntryComponent be = bnd.addEntry();
    be.setFullUrl("http://hl7.org/fhir/Patient/example");
    be.setResource(new XmlParser().parse(new FileInputStream(Utilities.path(TestingUtilities.resourceNameToFile("patient-example.xml")))));
    be = bnd.addEntry();
    be.setFullUrl("http://hl7.org/fhir/Patient/example");
    be.setResource(new XmlParser().parse(new FileInputStream(Utilities.path(TestingUtilities.resourceNameToFile("patient-example-xds.xml")))));
    be.getSearch().setScore(0.5);
    be.getSearch().setMode(SearchEntryMode.MATCH);
    bnd.setTotal(50);
    return bnd;
  } catch (Exception e) {
    throw new FHIRException(e);
  }
}
 
Example #4
Source File: FhirR4.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Map the JsonObject for a Supply into a FHIR SupplyDelivery and add it to the Bundle.
 *
 * @param personEntry    The Person entry.
 * @param bundle         Bundle to add to.
 * @param supply         The supplied object to add.
 * @param encounter      The encounter during which the supplies were delivered
 * @return The added Entry.
 */
private static BundleEntryComponent supplyDelivery(BundleEntryComponent personEntry,
        Bundle bundle, HealthRecord.Supply supply, Encounter encounter) {
 
  SupplyDelivery supplyResource = new SupplyDelivery();
  supplyResource.setStatus(SupplyDeliveryStatus.COMPLETED);
  supplyResource.setPatient(new Reference(personEntry.getFullUrl()));
  
  CodeableConcept type = new CodeableConcept();
  type.addCoding()
    .setCode("device")
    .setDisplay("Device")
    .setSystem("http://terminology.hl7.org/CodeSystem/supply-item-type");
  supplyResource.setType(type);
  
  SupplyDeliverySuppliedItemComponent suppliedItem = new SupplyDeliverySuppliedItemComponent();
  suppliedItem.setItem(mapCodeToCodeableConcept(supply.codes.get(0), SNOMED_URI));
  suppliedItem.setQuantity(new Quantity(supply.quantity));
  
  supplyResource.setSuppliedItem(suppliedItem);
  
  supplyResource.setOccurrence(convertFhirDateTime(supply.start, true));
  
  return newEntry(bundle, supplyResource);
}
 
Example #5
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static Resource getById(Bundle feed, ResourceType type, String reference) {
  for (BundleEntryComponent item : feed.getEntry()) {
    if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
      return item.getResource();
  }
  return null;
}
 
Example #6
Source File: R4ApelonFhirTerminologyProvider.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
public String resolveByIdentifier(ValueSetInfo valueSet) {
    String valueSetId = valueSet.getId();

    // Turns out we got a FHIR url. Let's use that.
    if (valueSetId.startsWith("http")) {
        return valueSetId;
    }
    
    valueSetId = valueSetId.replace("urn:oid:", "");

    IQuery<Bundle> bundleQuery = this.getFhirClient()
        .search()
        .byUrl("ValueSet?identifier=" + valueSetId)
        .returnBundle(Bundle.class)
        .accept("application/fhir+xml");
        
    Bundle searchResults = bundleQuery.execute();

    if (searchResults.hasEntry()) {
        for (BundleEntryComponent bec : searchResults.getEntry()) {
            if (bec.hasResource()) {
                String id = bec.getResource().getIdElement().getIdPart();
                if (id.equals(valueSetId)) {
                    return ((ValueSet)bec.getResource()).getUrl();
                }
            }

        }
    }

    return null;
}
 
Example #7
Source File: ValidationSupportR4.java    From synthea with Apache License 2.0 5 votes vote down vote up
private void handleResource(IBaseResource resource) {
  if (resource instanceof Bundle) {
    Bundle bundle = (Bundle) resource;
    for (BundleEntryComponent entry : bundle.getEntry()) {
      if (entry.hasResource()) {
        handleResource(entry.getResource());
      }
    }
  } else {
    resources.add(resource);
    if (resource instanceof CodeSystem) {
      CodeSystem cs = (CodeSystem) resource;
      resourcesMap.put(cs.getUrl(), cs);
      codeSystemMap.put(cs.getUrl(), cs);
    } else if (resource instanceof ValueSet) {
      ValueSet vs = (ValueSet) resource;
      resourcesMap.put(vs.getUrl(), vs);

      if (vs.hasExpansion() && vs.getExpansion().hasContains()) {
        processExpansion(vs.getExpansion().getContains());
      }
    } else if (resource instanceof StructureDefinition) {
      StructureDefinition sd = (StructureDefinition) resource;
      resourcesMap.put(sd.getUrl(), sd);
      definitions.add(sd);
      definitionsMap.put(sd.getUrl(), sd);
    }
  }
}
 
Example #8
Source File: HospitalExporterR4.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Export the hospital in FHIR R4 format.
 */
public static void export(long stop) {
  if (Boolean.parseBoolean(Config.get("exporter.hospital.fhir.export"))) {

    Bundle bundle = new Bundle();
    if (Boolean.parseBoolean(Config.get("exporter.fhir.transaction_bundle"))) {
      bundle.setType(BundleType.TRANSACTION);
    } else {
      bundle.setType(BundleType.COLLECTION);
    }
    for (Provider h : Provider.getProviderList()) {
      // filter - exports only those hospitals in use
      Table<Integer, String, AtomicInteger> utilization = h.getUtilization();
      int totalEncounters = utilization.column(Provider.ENCOUNTERS).values().stream()
          .mapToInt(ai -> ai.get()).sum();
      if (totalEncounters > 0) {
        BundleEntryComponent entry = FhirR4.provider(bundle, h);
        addHospitalExtensions(h, (Organization) entry.getResource());
      }
    }

    String bundleJson = FHIR_CTX.newJsonParser().setPrettyPrint(true)
        .encodeResourceToString(bundle);

    // get output folder
    List<String> folders = new ArrayList<>();
    folders.add("fhir");
    String baseDirectory = Config.get("exporter.baseDirectory");
    File f = Paths.get(baseDirectory, folders.toArray(new String[0])).toFile();
    f.mkdirs();
    Path outFilePath = f.toPath().resolve("hospitalInformation" + stop + ".json");

    try {
      Files.write(outFilePath, Collections.singleton(bundleJson), StandardOpenOption.CREATE_NEW);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
 
Example #9
Source File: FhirR4.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Find the Location entry in this bundle for the given provider, and return the
 * "fullUrl" attribute.
 *
 * @param provider A given provider.
 * @param bundle The current bundle being generated.
 * @return Location.fullUrl if found, otherwise null.
 */
private static String findLocationUrl(Provider provider, Bundle bundle) {
  for (BundleEntryComponent entry : bundle.getEntry()) {
    if (entry.getResource().fhirType().equals("Location")) {
      org.hl7.fhir.r4.model.Location location =
          (org.hl7.fhir.r4.model.Location) entry.getResource();
      if (location.getManagingOrganization()
          .getReference().endsWith(provider.getResourceID())) {
        return entry.getFullUrl();
      }
    }
  }
  return null;
}
 
Example #10
Source File: FhirR4.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Find the provider entry in this bundle, and return the associated "fullUrl" attribute.
 *
 * @param provider A given provider.
 * @param bundle   The current bundle being generated.
 * @return Provider.fullUrl if found, otherwise null.
 */
private static String findProviderUrl(Provider provider, Bundle bundle) {
  for (BundleEntryComponent entry : bundle.getEntry()) {
    if (entry.getResource().fhirType().equals("Organization")) {
      Organization org = (Organization) entry.getResource();
      if (org.getIdentifierFirstRep().getValue() != null
          && org.getIdentifierFirstRep().getValue().equals(provider.getResourceID())) {
        return entry.getFullUrl();
      }
    }
  }
  return null;
}
 
Example #11
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static BundleEntryComponent getEntryById(Bundle feed, ResourceType type, String reference) {
  for (BundleEntryComponent item : feed.getEntry()) {
    if (item.getResource().getId().equals(reference) && item.getResource().getResourceType() == type)
      return item;
  }
  return null;
}
 
Example #12
Source File: FhirR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Map the clinician into a FHIR Practitioner resource, and add it to the given Bundle.
 * @param bundle The Bundle to add to
 * @param clinician The clinician
 * @return The added Entry
 */
protected static BundleEntryComponent practitioner(Bundle bundle, Clinician clinician) {
  Practitioner practitionerResource = new Practitioner();
  if (USE_US_CORE_IG) {
    Meta meta = new Meta();
    meta.addProfile(
        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitioner");
    practitionerResource.setMeta(meta);
  }
  practitionerResource.addIdentifier().setSystem("http://hl7.org/fhir/sid/us-npi")
  .setValue("" + (9_999_999_999L - clinician.identifier));
  practitionerResource.setActive(true);
  practitionerResource.addName().setFamily(
      (String) clinician.attributes.get(Clinician.LAST_NAME))
    .addGiven((String) clinician.attributes.get(Clinician.FIRST_NAME))
    .addPrefix((String) clinician.attributes.get(Clinician.NAME_PREFIX));
  String email = (String) clinician.attributes.get(Clinician.FIRST_NAME)
      + "." + (String) clinician.attributes.get(Clinician.LAST_NAME)
      + "@example.com";
  practitionerResource.addTelecom()
      .setSystem(ContactPointSystem.EMAIL)
      .setUse(ContactPointUse.WORK)
      .setValue(email);
  if (USE_US_CORE_IG) {
    practitionerResource.getTelecomFirstRep().addExtension()
        .setUrl("http://hl7.org/fhir/us/core/StructureDefinition/us-core-direct")
        .setValue(new BooleanType(true));
  }
  Address address = new Address()
      .addLine((String) clinician.attributes.get(Clinician.ADDRESS))
      .setCity((String) clinician.attributes.get(Clinician.CITY))
      .setPostalCode((String) clinician.attributes.get(Clinician.ZIP))
      .setState((String) clinician.attributes.get(Clinician.STATE));
  if (COUNTRY_CODE != null) {
    address.setCountry(COUNTRY_CODE);
  }
  practitionerResource.addAddress(address);

  if (clinician.attributes.get(Person.GENDER).equals("M")) {
    practitionerResource.setGender(AdministrativeGender.MALE);
  } else if (clinician.attributes.get(Person.GENDER).equals("F")) {
    practitionerResource.setGender(AdministrativeGender.FEMALE);
  }
  BundleEntryComponent practitionerEntry =
      newEntry(bundle, practitionerResource, clinician.getResourceID());

  if (USE_US_CORE_IG) {
    // generate an accompanying PractitionerRole resource
    PractitionerRole practitionerRole = new PractitionerRole();
    Meta meta = new Meta();
    meta.addProfile(
        "http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitionerrole");
    practitionerRole.setMeta(meta);
    practitionerRole.setPractitioner(new Reference()
        .setReference(practitionerEntry.getFullUrl())
        .setDisplay(practitionerResource.getNameFirstRep().getNameAsSingleString()));
    practitionerRole.setOrganization(new Reference()
        .setReference(
            getUrlPrefix("Organization") + clinician.getOrganization().getResourceID())
        .setDisplay(clinician.getOrganization().name));
    practitionerRole.addCode(
        mapCodeToCodeableConcept(
            new Code("http://nucc.org/provider-taxonomy", "208D00000X", "General Practice"),
            null));
    practitionerRole.addSpecialty(
        mapCodeToCodeableConcept(
            new Code("http://nucc.org/provider-taxonomy", "208D00000X", "General Practice"),
            null));
    practitionerRole.addLocation()
        .setReference(findLocationUrl(clinician.getOrganization(), bundle))
        .setDisplay(clinician.getOrganization().name);
    if (clinician.getOrganization().phone != null
        && !clinician.getOrganization().phone.isEmpty()) {
      practitionerRole.addTelecom(new ContactPoint()
          .setSystem(ContactPointSystem.PHONE)
          .setValue(clinician.getOrganization().phone));
    }
    practitionerRole.addTelecom(practitionerResource.getTelecomFirstRep());

    newEntry(bundle, practitionerRole);
  }

  return practitionerEntry;
}
 
Example #13
Source File: FhirChCrlDocumentBundle.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void createBundle(){
	try {
		Date now = new Date();
		
		this.bundle = new Bundle();
		bundle.setId("BundleFromPractitioner");
		bundle.setMeta(new Meta().setLastUpdated(now).setProfile(Collections.singletonList(
			new CanonicalType("http://fhir.ch/ig/ch-crl/StructureDefinition/ch-crl-bundle"))));
		bundle.setType(BundleType.DOCUMENT);
		
		BundleEntryComponent compositionEntry = bundle.addEntry();
		Composition composition = new Composition();
		compositionEntry.setResource(composition);
		composition.setId("CompFromPractitioner");
		composition.setMeta(new Meta().setLastUpdated(now)
			.setProfile(Collections.singletonList(new CanonicalType(
				"http://fhir.ch/ig/ch-crl/StructureDefinition/ch-crl-composition"))));
		composition.setStatus(CompositionStatus.FINAL);
		composition.setType(new CodeableConcept(
			new Coding("http://loinc.org", "72134-0", "Cancer event report")));
		composition.setDate(now);
		composition.setTitle("Report to the Cancer Registry");
		
		BundleEntryComponent subjectEntry = bundle.addEntry();
		IFhirTransformer<Patient, IPatient> patientTransformer =
			(IFhirTransformer<Patient, IPatient>) FhirTransformersHolder
				.getTransformerFor(Patient.class, IPatient.class);
		Patient subject = patientTransformer.getFhirObject(patient)
			.orElseThrow(() -> new IllegalStateException("Could not create subject"));
		subject.getExtension().clear();
		fixAhvIdentifier(subject);
		
		subjectEntry.setResource(subject);
		
		BundleEntryComponent practitionerEntry = bundle.addEntry();
		IFhirTransformer<Practitioner, IMandator> practitionerTransformer =
			(IFhirTransformer<Practitioner, IMandator>) FhirTransformersHolder
				.getTransformerFor(Practitioner.class, IMandator.class);
		Practitioner practitioner = practitionerTransformer.getFhirObject(author)
			.orElseThrow(() -> new IllegalStateException("Could not create autor"));
		practitioner.getExtension().clear();
		practitioner.getIdentifier().clear();
		practitionerEntry.setResource(practitioner);
		
		BundleEntryComponent documentReferenceEntry = bundle.addEntry();
		DocumentReference documentReference = new DocumentReference();
		documentReferenceEntry.setResource(documentReference);
		documentReference.setId(document.getId());
		DocumentReferenceContentComponent content = documentReference.addContent();
		content.setAttachment(new Attachment().setContentType("application/pdf")
			.setData(IOUtils.toByteArray(document.getContent())));
		
		composition.setSubject(new Reference(subject));
		composition.setAuthor(Collections.singletonList(new Reference(practitioner)));
		SectionComponent section = composition.addSection();
		section.addEntry(new Reference(documentReference));
	} catch (IOException e) {
		LoggerFactory.getLogger(getClass()).error("Error creating FHIR bundle", e);
		throw new IllegalStateException("Error creating FHIR bundle", e);
	}
}
 
Example #14
Source File: BatchLoader.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private static void sendFile(FHIRToolingClient client, File f, int size, IniFile ini) throws FHIRFormatError, FileNotFoundException, IOException {
  long ms = System.currentTimeMillis();
  System.out.print("Loading "+f.getName()+".. ");
  IParser parser = f.getName().endsWith(".json") ? new JsonParser() : new XmlParser();
  Resource res = parser.parse(new FileInputStream(f));
  System.out.println("  done: ("+Long.toString(System.currentTimeMillis()-ms)+" ms)");
  
  if (res instanceof Bundle) {
    Bundle bnd = (Bundle) res;
    int cursor = ini.hasProperty("progress", f.getName()) ? ini.getIntegerProperty("progress", f.getName()) : 0;
    while (cursor < bnd.getEntry().size()) {
      Bundle bt = new Bundle();
      bt.setType(BundleType.BATCH);     
      bt.setId(UUID.randomUUID().toString().toLowerCase());
      for (int i = cursor; i < Math.min(bnd.getEntry().size(), cursor+size); i++) {
        BundleEntryComponent be = bt.addEntry();
        be.setResource(bnd.getEntry().get(i).getResource());
        be.getRequest().setMethod(HTTPVerb.PUT);
        be.getRequest().setUrl(be.getResource().getResourceType().toString()+"/"+be.getResource().getId());
      }
      System.out.print(f.getName()+" ("+cursor+"/"+bnd.getEntry().size()+"): ");
      ms = System.currentTimeMillis();
      Bundle resp = client.transaction(bt);

      int ncursor = cursor+size;
      for (int i = 0; i < resp.getEntry().size(); i++) {
        BundleEntryComponent t = resp.getEntry().get(i);
        if (!t.getResponse().getStatus().startsWith("2")) { 
          System.out.println("failed status at "+Integer.toString(i)+": "+t.getResponse().getStatus());
          ncursor = cursor+i-1;
          break;
        }
      }
      cursor = ncursor;
      System.out.println("  .. done: ("+Long.toString(System.currentTimeMillis()-ms)+" ms) "+SimpleDateFormat.getInstance().format(new Date()));
      ini.setIntegerProperty("progress", f.getName(), cursor, null);
      ini.save();
    }
    ini.setBooleanProperty("finished", f.getName(), true, null);
    ini.save();
  } else {
    client.update(res);
    ini.setBooleanProperty("finished", f.getName(), true, null);
    ini.save();
  }    
}
 
Example #15
Source File: FHIRR4ExporterTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
@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);
  mock.uuid = "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();
  long birthTime = time - Utilities.convertTime("years", 35);
  person.attributes.put(Person.BIRTHDATE, birthTime);

  Payer.loadNoInsurance();
  for (int i = 0; i < person.payerHistory.length; i++) {
    person.setPayerAtAge(i, 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 = FhirContext.forR4();
  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");
      }
    }
  }
}
 
Example #16
Source File: FHIRR4ExporterTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
@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.history = new LinkedList<>();
  Provider mock = Mockito.mock(Provider.class);
  mock.uuid = "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();
  long birthTime = time - Utilities.convertTime("years", 35);
  person.attributes.put(Person.BIRTHDATE, birthTime);

  Payer.loadNoInsurance();
  for (int i = 0; i < person.payerHistory.length; i++) {
    person.setPayerAtAge(i, 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 = FhirContext.forR4();
  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();
      assertEquals(10, data.getPeriod().doubleValue(), 0.001); // 0.01s == 10ms
      assertEquals(3, (int) data.getDimensions());
    }
  }
}
 
Example #17
Source File: FHIRR4ExporterTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
@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 = FhirContext.forR4();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  ValidationResources validator = new ValidationResources();
  List<String> validationErrors = new ArrayList<String>();

  int numberOfPeople = 10;
  Generator generator = new Generator(numberOfPeople);
  
  generator.options.overflow = false;

  for (int i = 0; i < numberOfPeople; i++) {
    int x = validationErrors.size();
    TestHelper.exportOff();
    Person person = generator.generatePerson(i);
    FhirR4.TRANSACTION_BUNDLE = person.random.nextBoolean();
    FhirR4.USE_US_CORE_IG = person.random.nextBoolean();
    FhirR4.USE_SHR_EXTENSIONS = false;
    String fhirJson = FhirR4.convertToFHIRJson(person, System.currentTimeMillis());
    // Check that the fhirJSON doesn't contain unresolved SNOMED-CT strings
    // (these should have been converted into URIs)
    if (fhirJson.contains("SNOMED-CT")) {
      validationErrors.add(
          "JSON contains unconverted references to 'SNOMED-CT' (should be URIs)");
    }
    // Now validate the resource...
    IBaseResource resource = ctx.newJsonParser().parseResource(fhirJson);
    ValidationResult result = validator.validateR4(resource);
    if (!result.isSuccessful()) {
      // If the validation failed, 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 (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
        ValidationResult eresult = validator.validateR4(entry.getResource());
        if (!eresult.isSuccessful()) {
          for (SingleValidationMessage emessage : eresult.getMessages()) {
            boolean valid = false;
            if (emessage.getMessage().contains("@ AllergyIntolerance ait-2")) {
              /*
               * The ait-2 invariant:
               * Description:
               * AllergyIntolerance.clinicalStatus SHALL NOT be present
               * if verification Status is entered-in-error
               * Expression:
               * verificationStatus!='entered-in-error' or clinicalStatus.empty()
               */
              valid = true;
            } else if (emessage.getMessage().contains("@ ExplanationOfBenefit dom-3")) {
              /*
               * For some reason, it doesn't like the contained ServiceRequest and contained
               * Coverage resources in the ExplanationOfBenefit, both of which are
               * properly referenced. Running $validate on test servers finds this valid...
               */
              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.
               */
              valid = true; // ignore this error
            } else if (emessage.getMessage().contains("[active, inactive, entered-in-error]")
                || emessage.getMessage().contains("MedicationStatusCodes-list")) {
              /*
               * MedicationStatement.status has more legal values than this... including
               * completed and stopped.
               */
              valid = true;
            }
            if (!valid) {
              System.out.println(parser.encodeResourceToString(entry.getResource()));
              System.out.println("ERROR: " + emessage.getMessage());
              validationErrors.add(emessage.getMessage());
            }
          }
        }
      }
    }
    int y = validationErrors.size();
    if (x != y) {
      Exporter.export(person, System.currentTimeMillis());
    }
  }
  assertTrue("Validation of exported FHIR bundle failed: "
      + String.join("|", validationErrors), validationErrors.size() == 0);
}
 
Example #18
Source File: GraphQLEngine.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
SearchEdge(String type, BundleEntryComponent be) {
  this.type = type;
  this.be = be;
}
 
Example #19
Source File: GraphQLEngine.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
private List<Base> getEdges() {
  List<Base> list = new ArrayList<>();
  for (BundleEntryComponent be : bnd.getEntry())
    list.add(new SearchEdge(type.substring(0, type.length() - 10) + "Edge", be));
  return list;
}
 
Example #20
Source File: R3ToR4Loader.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
  return false;
}
 
Example #21
Source File: FhirR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Map the given Observation with attachment element to a FHIR Media resource, and add it to the
 * given Bundle.
 *
 * @param personEntry    The Entry for the Person
 * @param bundle         Bundle to add the Media to
 * @param encounterEntry Current Encounter entry
 * @param obs   The Observation to map to FHIR and add to the bundle
 * @return The added Entry
 */
private static BundleEntryComponent media(BundleEntryComponent personEntry, Bundle bundle,
    BundleEntryComponent encounterEntry, Observation obs) {
  org.hl7.fhir.r4.model.Media mediaResource =
      new org.hl7.fhir.r4.model.Media();

  // Hard code as Image since we don't anticipate using video or audio any time soon
  Code mediaType = new Code("http://terminology.hl7.org/CodeSystem/media-type", "image", "Image");

  if (obs.codes != null && obs.codes.size() > 0) {
    List<CodeableConcept> reasonList = obs.codes.stream()
        .map(code -> mapCodeToCodeableConcept(code, SNOMED_URI)).collect(Collectors.toList());
    mediaResource.setReasonCode(reasonList);
  }
  mediaResource.setType(mapCodeToCodeableConcept(mediaType, MEDIA_TYPE_URI));
  mediaResource.setStatus(MediaStatus.COMPLETED);
  mediaResource.setSubject(new Reference(personEntry.getFullUrl()));
  mediaResource.setEncounter(new Reference(encounterEntry.getFullUrl()));

  Attachment content = (Attachment) obs.value;
  org.hl7.fhir.r4.model.Attachment contentResource = new org.hl7.fhir.r4.model.Attachment();
  
  contentResource.setContentType(content.contentType);
  contentResource.setLanguage(content.language);
  if (content.data != null) {
    contentResource.setDataElement(new org.hl7.fhir.r4.model.Base64BinaryType(content.data));
  }
  contentResource.setUrl(content.url);
  contentResource.setSize(content.size);
  contentResource.setTitle(content.title);
  if (content.hash != null) {
    contentResource.setHashElement(new org.hl7.fhir.r4.model.Base64BinaryType(content.hash));
  }
  
  mediaResource.setWidth(content.width);
  mediaResource.setHeight(content.height);

  mediaResource.setContent(contentResource);

  return newEntry(bundle, mediaResource);
}
 
Example #22
Source File: FhirR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Add a MedicationAdministration if needed for the given medication.
 * 
 * @param personEntry       The Entry for the Person
 * @param bundle            Bundle to add the MedicationAdministration to
 * @param encounterEntry    Current Encounter entry
 * @param medication        The Medication
 * @param medicationRequest The related medicationRequest
 * @return The added Entry
 */
private static BundleEntryComponent medicationAdministration(
    BundleEntryComponent personEntry, Bundle bundle, BundleEntryComponent encounterEntry,
    Medication medication, MedicationRequest medicationRequest) {

  MedicationAdministration medicationResource = new MedicationAdministration();

  medicationResource.setSubject(new Reference(personEntry.getFullUrl()));
  medicationResource.setContext(new Reference(encounterEntry.getFullUrl()));

  Code code = medication.codes.get(0);
  String system = code.system.equals("SNOMED-CT") ? SNOMED_URI : RXNORM_URI;

  medicationResource.setMedication(mapCodeToCodeableConcept(code, system));
  medicationResource.setEffective(new DateTimeType(new Date(medication.start)));

  medicationResource.setStatus("completed");

  if (medication.prescriptionDetails != null) {
    JsonObject rxInfo = medication.prescriptionDetails;
    MedicationAdministrationDosageComponent dosage =
        new MedicationAdministrationDosageComponent();

    // as_needed is false
    if ((rxInfo.has("dosage")) && (!rxInfo.has("as_needed"))) {
      Quantity dose = new SimpleQuantity()
          .setValue(rxInfo.get("dosage").getAsJsonObject().get("amount").getAsDouble());
      dosage.setDose((SimpleQuantity) dose);

      if (rxInfo.has("instructions")) {
        for (JsonElement instructionElement : rxInfo.get("instructions").getAsJsonArray()) {
          JsonObject instruction = instructionElement.getAsJsonObject();

          dosage.setText(instruction.get("display").getAsString());
        }
      }
    }
    if (rxInfo.has("refills")) {
      SimpleQuantity rate = new SimpleQuantity();
      rate.setValue(rxInfo.get("refills").getAsLong());
      dosage.setRate(rate);
    }
    medicationResource.setDosage(dosage);
  }

  if (!medication.reasons.isEmpty()) {
    // Only one element in list
    Code reason = medication.reasons.get(0);
    for (BundleEntryComponent entry : bundle.getEntry()) {
      if (entry.getResource().fhirType().equals("Condition")) {
        Condition condition = (Condition) entry.getResource();
        // Only one element in list
        Coding coding = condition.getCode().getCoding().get(0);
        if (reason.code.equals(coding.getCode())) {
          medicationResource.addReasonReference().setReference(entry.getFullUrl());
        }
      }
    }
  }

  BundleEntryComponent medicationAdminEntry = newEntry(bundle, medicationResource);
  return medicationAdminEntry;
}
 
Example #23
Source File: NpmPackageVersionConverter.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
  return false;
}
 
Example #24
Source File: FhirR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Create an entry for the given Claim, which references a Medication.
 *
 * @param person         The person being prescribed medication
 * @param personEntry     Entry for the person
 * @param bundle          The Bundle to add to
 * @param encounterEntry  The current Encounter
 * @param claim           the Claim object
 * @param medicationEntry The Entry for the Medication object, previously created
 * @return the added Entry
 */
private static BundleEntryComponent medicationClaim(
    Person person, BundleEntryComponent personEntry,
    Bundle bundle, BundleEntryComponent encounterEntry, Claim claim,
    BundleEntryComponent medicationEntry) {
  
  org.hl7.fhir.r4.model.Claim claimResource = new org.hl7.fhir.r4.model.Claim();
  org.hl7.fhir.r4.model.Encounter encounterResource =
      (org.hl7.fhir.r4.model.Encounter) encounterEntry.getResource();

  claimResource.setStatus(ClaimStatus.ACTIVE);
  CodeableConcept type = new CodeableConcept();
  type.getCodingFirstRep()
    .setSystem("http://terminology.hl7.org/CodeSystem/claim-type")
    .setCode("pharmacy");
  claimResource.setType(type);
  claimResource.setUse(org.hl7.fhir.r4.model.Claim.Use.CLAIM);

  // Get the insurance info at the time that the encounter occurred.
  InsuranceComponent insuranceComponent = new InsuranceComponent();
  insuranceComponent.setSequence(1);
  insuranceComponent.setFocal(true);
  insuranceComponent.setCoverage(new Reference().setDisplay(claim.payer.getName()));
  claimResource.addInsurance(insuranceComponent);

  // duration of encounter
  claimResource.setBillablePeriod(encounterResource.getPeriod());
  claimResource.setCreated(encounterResource.getPeriod().getEnd());

  claimResource.setPatient(new Reference(personEntry.getFullUrl()));
  claimResource.setProvider(encounterResource.getServiceProvider());

  // set the required priority
  CodeableConcept priority = new CodeableConcept();
  priority.getCodingFirstRep()
    .setSystem("http://terminology.hl7.org/CodeSystem/processpriority")
    .setCode("normal");
  claimResource.setPriority(priority);

  // add item for encounter
  claimResource.addItem(new ItemComponent(new PositiveIntType(1),
        encounterResource.getTypeFirstRep())
      .addEncounter(new Reference(encounterEntry.getFullUrl())));

  // add prescription.
  claimResource.setPrescription(new Reference(medicationEntry.getFullUrl()));

  Money moneyResource = new Money();
  moneyResource.setValue(claim.getTotalClaimCost());
  moneyResource.setCurrency("USD");
  claimResource.setTotal(moneyResource);

  return newEntry(bundle, claimResource);
}
 
Example #25
Source File: IGR2ConvertorAdvisor.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
  return false;
}
 
Example #26
Source File: R2016MayToR4Loader.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
  return false;
}
 
Example #27
Source File: FhirR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Convert the given Person into a FHIR Bundle of the Patient and the
 * associated entries from their health record.
 *
 * @param person   Person to generate the FHIR JSON for
 * @param stopTime Time the simulation ended
 * @return FHIR Bundle containing the Person's health record
 */
public static Bundle convertToFHIR(Person person, long stopTime) {
  Bundle bundle = new Bundle();
  if (TRANSACTION_BUNDLE) {
    bundle.setType(BundleType.TRANSACTION);
  } else {
    bundle.setType(BundleType.COLLECTION);
  }

  BundleEntryComponent personEntry = basicInfo(person, bundle, stopTime);

  for (Encounter encounter : person.record.encounters) {
    BundleEntryComponent encounterEntry = encounter(person, personEntry, bundle, encounter);

    for (HealthRecord.Entry condition : encounter.conditions) {
      condition(personEntry, bundle, encounterEntry, condition);
    }

    for (HealthRecord.Entry allergy : encounter.allergies) {
      allergy(personEntry, bundle, encounterEntry, allergy);
    }

    for (Observation observation : encounter.observations) {
      // If the Observation contains an attachment, use a Media resource, since
      // Observation resources in v4 don't support Attachments
      if (observation.value instanceof Attachment) {
        media(personEntry, bundle, encounterEntry, observation);
      } else {
        observation(personEntry, bundle, encounterEntry, observation);
      }
    }

    for (Procedure procedure : encounter.procedures) {
      procedure(personEntry, bundle, encounterEntry, procedure);
    }

    for (HealthRecord.Device device : encounter.devices) {
      device(personEntry, bundle, device);
    }
    
    for (HealthRecord.Supply supply : encounter.supplies) {
      supplyDelivery(personEntry, bundle, supply, encounter);
    }

    for (Medication medication : encounter.medications) {
      medicationRequest(person, personEntry, bundle, encounterEntry, medication);
    }

    for (HealthRecord.Entry immunization : encounter.immunizations) {
      immunization(personEntry, bundle, encounterEntry, immunization);
    }

    for (Report report : encounter.reports) {
      report(personEntry, bundle, encounterEntry, report);
    }

    for (CarePlan careplan : encounter.careplans) {
      BundleEntryComponent careTeamEntry =
          careTeam(personEntry, bundle, encounterEntry, careplan);
      carePlan(personEntry, bundle, encounterEntry, encounter.provider, careTeamEntry, careplan);
    }

    for (ImagingStudy imagingStudy : encounter.imagingStudies) {
      imagingStudy(personEntry, bundle, encounterEntry, imagingStudy);
    }
    
    if (USE_US_CORE_IG) {
      String clinicalNoteText = ClinicalNoteExporter.export(person, encounter);
      boolean lastNote =
          (encounter == person.record.encounters.get(person.record.encounters.size() - 1));
      clinicalNote(personEntry, bundle, encounterEntry, clinicalNoteText, lastNote);
    }

    // one claim per encounter
    BundleEntryComponent encounterClaim =
        encounterClaim(person, personEntry, bundle, encounterEntry, encounter.claim);

    explanationOfBenefit(personEntry, bundle, encounterEntry, person,
        encounterClaim, encounter);
  }

  if (USE_US_CORE_IG) {
    // Add Provenance to the Bundle
    provenance(bundle, person, stopTime);
  }
  return bundle;
}
 
Example #28
Source File: R2ToR4Loader.java    From org.hl7.fhir.core with Apache License 2.0 4 votes vote down vote up
@Override
public boolean ignoreEntry(BundleEntryComponent src) {
  return false;
}
 
Example #29
Source File: FhirR4.java    From synthea with Apache License 2.0 2 votes vote down vote up
/**
 * Helper function to create an Entry for the given Resource within the given Bundle. Sets the
 * resourceID to a random UUID, sets the entry's fullURL to that resourceID, and adds the entry to
 * the bundle.
 *
 * @param bundle   The Bundle to add the Entry to
 * @param resource Resource the new Entry should contain
 * @return the created Entry
 */
private static BundleEntryComponent newEntry(Bundle bundle, Resource resource) {
  String resourceID = UUID.randomUUID().toString();
  return newEntry(bundle, resource, resourceID);
}