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

The following examples show how to use org.hl7.fhir.r4.model.Bundle.BundleType. 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: LoincToDEConvertor.java    From org.hl7.fhir.core with Apache License 2.0 6 votes vote down vote up
public Bundle process(String sourceFile) throws FileNotFoundException, SAXException, IOException, ParserConfigurationException {
  this.definitions = sourceFile;
  log("Begin. Produce Loinc CDEs in "+dest+" from "+definitions);
  loadLoinc();
  log("LOINC loaded");

  now = DateTimeType.now();

  bundle = new Bundle();
  bundle.setType(BundleType.COLLECTION);
  bundle.setId("http://hl7.org/fhir/commondataelement/loinc");
  bundle.setMeta(new Meta().setLastUpdatedElement(InstantType.now()));

  processLoincCodes();
  return bundle;
}
 
Example #2
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 #3
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 #4
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 #5
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);
	}
}