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

The following examples show how to use org.hl7.fhir.dstu3.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: FhirStu3.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 entry's fullURL to 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);
  if (Boolean.parseBoolean(Config.get("exporter.fhir.bulk_data"))) {
    entry.setFullUrl(resource.fhirType() + "/" + resourceID);
  } else {
    entry.setFullUrl("urn:uuid:" + 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: SNOMEDUKMockValidationSupport.java    From careconnect-reference-implementation with Apache License 2.0 6 votes vote down vote up
private void loadStructureDefinitions(FhirContext theContext, Map<String, StructureDefinition> theCodeSystems, String theClasspath) {
  logD("SNOMEDMOCK Loading structure definitions from classpath: "+ theClasspath);
  InputStream valuesetText = SNOMEDUKMockValidationSupport.class.getResourceAsStream(theClasspath);
  if (valuesetText != null) {
    InputStreamReader reader = new InputStreamReader(valuesetText, Charsets.UTF_8);

    Bundle bundle = theContext.newXmlParser().parseResource(Bundle.class, reader);
    for (BundleEntryComponent next : bundle.getEntry()) {
      if (next.getResource() instanceof StructureDefinition) {
        StructureDefinition nextSd = (StructureDefinition) next.getResource();
        nextSd.getText().setDivAsString("");
        String system = nextSd.getUrl();
        if (isNotBlank(system)) {
          theCodeSystems.put(system, nextSd);
        }
      }
    }
  } else {
    log.warn("Unable to load resource: {}", theClasspath);
  }
}
 
Example #3
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public Resource resolve(String value) {
  if (value.startsWith("#")) {
    for (Resource r : resourceResource.getContained()) {
      if (r.getId().equals(value.substring(1)))
        return r;
    }
    return null;
  }
  if (bundleResource != null) {
    for (BundleEntryComponent be : bundleResource.getEntry()) {
      if (be.getFullUrl().equals(value))
        return be.getResource();
      if (value.equals(be.getResource().fhirType()+"/"+be.getResource().getId()))
        return be.getResource();
    }
  }
  return null;
}
 
Example #4
Source File: CCDAConverter.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
protected String addReference(DomainResource r, String title, String id) throws Exception {
	if (r.getText() == null)
		r.setText(new Narrative());
	if (r.getText().getDiv() == null) {
		r.getText().setStatus(NarrativeStatus.GENERATED);
		new NarrativeGenerator("", "", context).generate(r);
	}
	r.setMeta(new Meta().setLastUpdatedElement(InstantType.now()));
	r.setId(id);
	feed.getEntry().add(new BundleEntryComponent().setResource(r));
	return id;
}
 
Example #5
Source File: Dstu3ApelonFhirTerminologyProvider.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 #6
Source File: HospitalExporterStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Export the hospital in FHIR STU3 format.
 */
public static void export(long stop) {
  if (Boolean.parseBoolean(Config.get("exporter.hospital.fhir_stu3.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 = FhirStu3.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_stu3");
    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 #7
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 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();

  practitionerResource.addIdentifier().setSystem("http://hl7.org/fhir/sid/us-npi")
  .setValue("" + 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));

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

  return newEntry(bundle, practitionerResource, clinician.getResourceID());
}
 
Example #8
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 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://hl7.org/fhir/supply-item-type");
  supplyResource.setType(type);
  
  SupplyDeliverySuppliedItemComponent suppliedItem = new SupplyDeliverySuppliedItemComponent();
  suppliedItem.setItem(mapCodeToCodeableConcept(supply.codes.get(0), SNOMED_URI));
  
  SimpleQuantity quantity = new SimpleQuantity();
  quantity.setValue(supply.quantity);
  suppliedItem.setQuantity(quantity);
  
  supplyResource.setSuppliedItem(suppliedItem);
  
  supplyResource.setOccurrence(convertFhirDateTime(supply.start, true));
  
  return newEntry(bundle, supplyResource);
}
 
Example #9
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Map the given Media 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.dstu3.model.Media mediaResource =
      new org.hl7.fhir.dstu3.model.Media();

  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);
  }
  
  // Hard code as an image
  mediaResource.setType(DigitalMediaType.PHOTO);
  mediaResource.setSubject(new Reference(personEntry.getFullUrl()));

  Attachment content = (Attachment) obs.value;
  org.hl7.fhir.dstu3.model.Attachment contentResource = new org.hl7.fhir.dstu3.model.Attachment();
  
  contentResource.setContentType(content.contentType);
  contentResource.setLanguage(content.language);
  if (content.data != null) {
    contentResource.setDataElement(new org.hl7.fhir.dstu3.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.dstu3.model.Base64BinaryType(content.hash));
  }
  
  mediaResource.setWidth(content.width);
  mediaResource.setHeight(content.height);
  
  mediaResource.setContent(contentResource);

  return newEntry(bundle, mediaResource);
}
 
Example #10
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Create an entry for the given Claim, which references a 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(BundleEntryComponent personEntry,
    Bundle bundle, BundleEntryComponent encounterEntry, Claim claim,
    BundleEntryComponent medicationEntry) {
  org.hl7.fhir.dstu3.model.Claim claimResource = new org.hl7.fhir.dstu3.model.Claim();
  org.hl7.fhir.dstu3.model.Encounter encounterResource =
      (org.hl7.fhir.dstu3.model.Encounter) encounterEntry.getResource();

  claimResource.setStatus(ClaimStatus.ACTIVE);
  claimResource.setUse(org.hl7.fhir.dstu3.model.Claim.Use.COMPLETE);

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

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

  // add item for encounter
  claimResource.addItem(new org.hl7.fhir.dstu3.model.Claim.ItemComponent(new PositiveIntType(1))
      .addEncounter(new Reference(encounterEntry.getFullUrl())));

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

  Money moneyResource = new Money();
  moneyResource.setValue(claim.getTotalClaimCost());
  moneyResource.setCode("USD");
  moneyResource.setSystem("urn:iso:std:iso:4217");
  claimResource.setTotal(moneyResource);

  return newEntry(bundle, claimResource);
}
 
Example #11
Source File: FhirStu3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Find the Practitioner entry in this bundle, and return the associated "fullUrl"
 * attribute.
 * @param clinician A given clinician.
 * @param bundle The current bundle being generated.
 * @return Practitioner.fullUrl if found, otherwise null.
 */
private static String findPractitioner(Clinician clinician, Bundle bundle) {
  for (BundleEntryComponent entry : bundle.getEntry()) {
    if (entry.getResource().fhirType().equals("Practitioner")) {
      Practitioner doc = (Practitioner) entry.getResource();
      if (doc.getIdentifierFirstRep().getValue().equals("" + clinician.identifier)) {
        return entry.getFullUrl();
      }
    }
  }
  return null;
}
 
Example #12
Source File: FhirStu3.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().equals(provider.getResourceID())) {
        return entry.getFullUrl();
      }
    }
  }
  return null;
}
 
Example #13
Source File: Stu3FhirConversionSupport.java    From bunsen with Apache License 2.0 5 votes vote down vote up
@Override
public List<IBaseResource> extractEntryFromBundle(IBaseBundle bundle, String resourceName) {

  Bundle stu3Bundle = (Bundle) bundle;

  List<IBaseResource> items = stu3Bundle.getEntry().stream()
          .map(BundleEntryComponent::getResource)
          .filter(resource ->
              resource != null
                  && resourceName.equalsIgnoreCase(resource.getResourceType().name()))
          .collect(Collectors.toList());

  return items;
}
 
Example #14
Source File: Unbundler.java    From org.hl7.fhir.core with Apache License 2.0 5 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) {
      String tgt = Utilities.path(folder, r.fhirType()+"-"+r.getId()+".json");
      new JsonParser().compose(new FileOutputStream(tgt), r);
    }
  }
}
 
Example #15
Source File: NarrativeGenerator.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public boolean generate(Bundle b, boolean evenIfAlreadyHasNarrative) throws EOperationOutcome, FHIRException, IOException {
  boolean res = false;
  this.bundle = b;
  for (BundleEntryComponent be : b.getEntry()) {
    if (be.hasResource() && be.getResource() instanceof DomainResource) {
      DomainResource dr = (DomainResource) be.getResource();
      if (evenIfAlreadyHasNarrative || !dr.getText().hasDiv())
        res = generate(new ResourceContext(b, dr), dr) || res;
    }
  }
  return res;
}
 
Example #16
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static boolean hasUnits(Bundle bundle) {
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    if (ToolingExtensions.getAllowedUnits(de.getElement().get(0)) != null)
      return true;
  }
  return false;
}
 
Example #17
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static boolean hasType(Bundle bundle) {
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    if (de.getElement().get(0).hasType())
      return true;
  }
  return false;
}
 
Example #18
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static boolean hasCode(Bundle bundle) {
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    if (de.getElement().get(0).hasCode())
      return true;
  }
  return false;
}
 
Example #19
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static boolean hasBinding(Bundle bundle) {
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    if (de.getElement().get(0).hasBinding())
      return true;
  }
  return false;
}
 
Example #20
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
private static boolean hasExtension(Bundle bundle, String url) {
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    if (ToolingExtensions.hasExtension(de, url))
      return true;
  }
  return false;
}
 
Example #21
Source File: ResourceUtilities.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static String representDataElementCollection(IWorkerContext context, Bundle bundle, boolean profileLink, String linkBase) {
  StringBuilder b = new StringBuilder();
  DataElement common = showDECHeader(b, bundle);
  b.append("<table class=\"grid\">\r\n"); 
  List<String> cols = chooseColumns(bundle, common, b, profileLink);
  for (BundleEntryComponent e : bundle.getEntry()) {
    DataElement de = (DataElement) e.getResource();
    renderDE(de, cols, b, profileLink, linkBase);
  }
  b.append("</table>\r\n");
  return b.toString();
}
 
Example #22
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 #23
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 #24
Source File: FhirStu3.java    From synthea with Apache License 2.0 4 votes vote down vote up
/**
 * Map the given CarePlan to a FHIR CarePlan resource, and add it to the given Bundle.
 *
 * @param personEntry The Entry for the Person
 * @param bundle Bundle to add the CarePlan to
 * @param encounterEntry Current Encounter entry
 * @param carePlan The CarePlan to map to FHIR and add to the bundle
 * @return The added Entry
 */
private static BundleEntryComponent careplan(BundleEntryComponent personEntry, Bundle bundle,
    BundleEntryComponent encounterEntry, CarePlan carePlan) {
  org.hl7.fhir.dstu3.model.CarePlan careplanResource = new org.hl7.fhir.dstu3.model.CarePlan();
  careplanResource.setIntent(CarePlanIntent.ORDER);
  careplanResource.setSubject(new Reference(personEntry.getFullUrl()));
  careplanResource.setContext(new Reference(encounterEntry.getFullUrl()));

  Code code = carePlan.codes.get(0);
  careplanResource.addCategory(mapCodeToCodeableConcept(code, SNOMED_URI));

  CarePlanActivityStatus activityStatus;
  GoalStatus goalStatus;

  Period period = new Period().setStart(new Date(carePlan.start));
  careplanResource.setPeriod(period);
  if (carePlan.stop != 0L) {
    period.setEnd(new Date(carePlan.stop));
    careplanResource.setStatus(CarePlanStatus.COMPLETED);
    activityStatus = CarePlanActivityStatus.COMPLETED;
    goalStatus = GoalStatus.ACHIEVED;
  } else {
    careplanResource.setStatus(CarePlanStatus.ACTIVE);
    activityStatus = CarePlanActivityStatus.INPROGRESS;
    goalStatus = GoalStatus.INPROGRESS;
  }

  if (!carePlan.activities.isEmpty()) {
    for (Code activity : carePlan.activities) {
      CarePlanActivityComponent activityComponent = new CarePlanActivityComponent();
      CarePlanActivityDetailComponent activityDetailComponent =
          new CarePlanActivityDetailComponent();

      activityDetailComponent.setStatus(activityStatus);

      activityDetailComponent.setCode(mapCodeToCodeableConcept(activity, SNOMED_URI));
      activityComponent.setDetail(activityDetailComponent);

      careplanResource.addActivity(activityComponent);
    }
  }

  if (!carePlan.reasons.isEmpty()) {
    // Only one element in list
    Code reason = carePlan.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())) {
          careplanResource.addAddresses().setReference(entry.getFullUrl());
        }
      }
    }
  }

  for (JsonObject goal : carePlan.goals) {
    BundleEntryComponent goalEntry = caregoal(bundle, goalStatus, goal);
    careplanResource.addGoal().setReference(goalEntry.getFullUrl());
  }

  return newEntry(bundle, careplanResource);
}
 
Example #25
Source File: IGPackConverter102.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: CodeResolveAndExportTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
private void verifyEncounterCodeR4() throws FileNotFoundException {
  InputStream inputStream = new FileInputStream(r4OutputPath.toFile().getAbsolutePath());
  org.hl7.fhir.r4.model.Bundle bundle = (org.hl7.fhir.r4.model.Bundle) getR4FhirContext()
      .newJsonParser().parseResource(inputStream);

  // Find encounter reason code.
  Optional<org.hl7.fhir.r4.model.Bundle.BundleEntryComponent> maybeEncounterEntry = bundle
      .getEntry().stream()
      .filter(entry -> entry.getResource().getResourceType().equals(
          org.hl7.fhir.r4.model.ResourceType.Encounter))
      .findFirst();
  assertTrue(maybeEncounterEntry.isPresent());

  org.hl7.fhir.r4.model.Encounter encounterResource = 
      (org.hl7.fhir.r4.model.Encounter) maybeEncounterEntry.get().getResource();
  assertEquals(encounterResource.getReasonCode().size(), 1);
  org.hl7.fhir.r4.model.CodeableConcept encounterReason = encounterResource.getReasonCode()
      .get(0);
  assertEquals(encounterReason.getCoding().size(), 1);
  org.hl7.fhir.r4.model.Coding reasonCoding = encounterReason.getCoding().get(0);

  // Check encounter reason code.
  assertEquals(SNOMED_URI, reasonCoding.getSystem());
  assertEquals(EXPECTED_REASON_CODE, reasonCoding.getCode());
  assertEquals(EXPECTED_REASON_DISPLAY, reasonCoding.getDisplay());

  Optional<org.hl7.fhir.r4.model.Bundle.BundleEntryComponent> maybeObservationEntry = 
      bundle.getEntry().stream()
      .filter(entry -> entry.getResource().getResourceType().equals(
          org.hl7.fhir.r4.model.ResourceType.Observation))
      .findFirst();
  assertTrue(maybeObservationEntry.isPresent());

  // Find observation type code.
  org.hl7.fhir.r4.model.Observation observationResource =
      (org.hl7.fhir.r4.model.Observation) maybeObservationEntry.get().getResource();
  org.hl7.fhir.r4.model.CodeableConcept observationType = observationResource.getCode();
  assertNotNull(observationType);
  assertEquals(observationType.getCoding().size(), 1);
  org.hl7.fhir.r4.model.Coding observationTypeCoding = observationType.getCoding().get(0);

  // Check observation type code.
  assertEquals(LOINC_URI, observationTypeCoding.getSystem());
  assertEquals(OBSERVATION_CODE, observationTypeCoding.getCode());
  assertEquals(OBSERVATION_DISPLAY, observationTypeCoding.getDisplay());

  // Find observation value code.
  org.hl7.fhir.r4.model.CodeableConcept observationValue = 
      observationResource.getValueCodeableConcept();
  assertNotNull(observationValue);
  assertEquals(observationValue.getCoding().size(), 1);
  org.hl7.fhir.r4.model.Coding observationValueCoding = observationValue.getCoding().get(0);

  // Check observation value code.
  assertEquals(LOINC_URI, observationValueCoding.getSystem());
  assertEquals(EXPECTED_VALUE_CODE, observationValueCoding.getCode());
  assertEquals(EXPECTED_VALUE_DISPLAY, observationValueCoding.getDisplay());
}
 
Example #27
Source File: CodeResolveAndExportTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
private void verifyEncounterCodeStu3() throws FileNotFoundException {
  InputStream inputStream = new FileInputStream(stu3OutputPath.toFile().getAbsolutePath());
  Bundle bundle = (Bundle) getStu3FhirContext().newJsonParser().parseResource(inputStream);

  // Find encounter reason code.
  Optional<BundleEntryComponent> maybeEncounterEntry = bundle.getEntry().stream()
      .filter(entry -> entry.getResource().getResourceType().equals(ResourceType.Encounter))
      .findFirst();
  assertTrue(maybeEncounterEntry.isPresent());

  org.hl7.fhir.dstu3.model.Encounter encounterResource =
      (org.hl7.fhir.dstu3.model.Encounter) maybeEncounterEntry.get().getResource();
  assertEquals(encounterResource.getReason().size(), 1);
  CodeableConcept encounterReason = encounterResource.getReason().get(0);
  assertEquals(encounterReason.getCoding().size(), 1);
  Coding reasonCoding = encounterReason.getCoding().get(0);

  // Check encounter reason code.
  assertEquals(SNOMED_URI, reasonCoding.getSystem());
  assertEquals(EXPECTED_REASON_CODE, reasonCoding.getCode());
  assertEquals(EXPECTED_REASON_DISPLAY, reasonCoding.getDisplay());

  Optional<BundleEntryComponent> maybeObservationEntry = bundle.getEntry().stream()
      .filter(entry -> entry.getResource().getResourceType().equals(ResourceType.Observation))
      .findFirst();
  assertTrue(maybeObservationEntry.isPresent());

  // Find observation type code.
  org.hl7.fhir.dstu3.model.Observation observationResource =
      (org.hl7.fhir.dstu3.model.Observation) maybeObservationEntry.get().getResource();
  CodeableConcept observationType = observationResource.getCode();
  assertNotNull(observationType);
  assertEquals(observationType.getCoding().size(), 1);
  Coding observationTypeCoding = observationType.getCoding().get(0);

  // Check observation type code.
  assertEquals(LOINC_URI, observationTypeCoding.getSystem());
  assertEquals(OBSERVATION_CODE, observationTypeCoding.getCode());
  assertEquals(OBSERVATION_DISPLAY, observationTypeCoding.getDisplay());

  // Find observation value code.
  CodeableConcept observationValue = observationResource.getValueCodeableConcept();
  assertNotNull(observationValue);
  assertEquals(observationValue.getCoding().size(), 1);
  Coding observationValueCoding = observationValue.getCoding().get(0);

  // Check observation value code.
  assertEquals(LOINC_URI, observationValueCoding.getSystem());
  assertEquals(EXPECTED_VALUE_CODE, observationValueCoding.getCode());
  assertEquals(EXPECTED_VALUE_DISPLAY, observationValueCoding.getDisplay());
}
 
Example #28
Source File: FHIRSTU3ExporterTest.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.forDstu3();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  String fhirJson = FhirStu3.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 #29
Source File: FHIRSTU3ExporterTest.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.forDstu3();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  String fhirJson = FhirStu3.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 #30
Source File: R2ToR3Loader.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;
}