Java Code Examples for org.hl7.fhir.r4.model.Bundle.BundleEntryComponent#getResource()

The following examples show how to use org.hl7.fhir.r4.model.Bundle.BundleEntryComponent#getResource() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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");
      }
    }
  }
}