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

The following examples show how to use org.hl7.fhir.r4.model.Bundle#getEntry() . 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: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private void addEvaluatedResourcesToParameters(Bundle contained, Parameters parameters) {
    Map<String, Resource> resourceMap = new HashMap<>();
    if (contained.hasEntry()) {
        for (Bundle.BundleEntryComponent entry : contained.getEntry()) {
            if (entry.hasResource() && !(entry.getResource() instanceof ListResource)) {
                if (!resourceMap.containsKey(entry.getResource().getIdElement().getValue())) {
                    parameters.addParameter(new Parameters.ParametersParameterComponent().setName("resource")
                            .setResource(entry.getResource()));

                    resourceMap.put(entry.getResource().getIdElement().getValue(), entry.getResource());

                    resolveReferences(entry.getResource(), parameters, resourceMap);
                }
            }
        }
    }
}
 
Example 3
Source File: MeasureOperationsProvider.java    From cqf-ruler with Apache License 2.0 6 votes vote down vote up
private Bundle createTransactionBundle(Bundle bundle) {
    Bundle transactionBundle;
    if (bundle != null) {
        if (bundle.hasType() && bundle.getType() == Bundle.BundleType.TRANSACTION) {
            transactionBundle = bundle;
        } else {
            transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION);
            if (bundle.hasEntry()) {
                for (Bundle.BundleEntryComponent entry : bundle.getEntry()) {
                    if (entry.hasResource()) {
                        transactionBundle.addEntry(createTransactionEntry(entry.getResource()));
                    }
                }
            }
        }
    } else {
        transactionBundle = new Bundle().setType(Bundle.BundleType.TRANSACTION).setEntry(new ArrayList<>());
    }

    return transactionBundle;
}
 
Example 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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");
      }
    }
  }
}