Java Code Examples for org.hl7.fhir.dstu3.model.Bundle

The following examples show how to use org.hl7.fhir.dstu3.model.Bundle. These examples are extracted from open source projects. 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
public static void main(String[] theArgs) {
   FhirContext ctx = FhirContext.forDstu3();
   IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

   // Build a search and execute it
   Bundle response = client.search()
      .forResource(Patient.class)
      .where(Patient.NAME.matches().value("Test"))
      .and(Patient.BIRTHDATE.before().day("2014-01-01"))
      .count(100)
      .returnBundle(Bundle.class)
      .execute();

   // How many resources did we find?
   System.out.println("Responses: " + response.getTotal());

   // Print the ID of the first one
   System.out.println("First response ID: " + response.getEntry().get(0).getResource().getId());
}
 
Example 2
Source Project: org.hl7.fhir.core   Source File: ObservationStatsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void buildVitalSignsSet() throws FileNotFoundException, IOException, FHIRFormatError {
  Calendar base = Calendar.getInstance();
  base.add(Calendar.DAY_OF_MONTH, -1);
  Bundle b = new Bundle();
  b.setType(BundleType.COLLECTION);
  b.setId(UUID.randomUUID().toString().toLowerCase());
  
  vitals(b, base, 0, 80, 120, 95, 37.1);
  vitals(b, base, 35, 85, 140, 98, 36.9);
  vitals(b, base, 53, 75, 110, 96, 36.2);
  vitals(b, base, 59, 65, 100, 94, 35.5);
  vitals(b, base, 104, 60, 90, 90, 35.9);
  vitals(b, base, 109, 65, 100, 92, 36.5);
  vitals(b, base, 114, 70, 130, 94, 37.5);
  vitals(b, base, 120, 90, 150, 97, 37.3);
  vitals(b, base, 130, 95, 133, 97, 37.2);
  vitals(b, base, 150, 85, 125, 98, 37.1);
  
  new XmlParser().setOutputStyle(OutputStyle.PRETTY).compose(new FileOutputStream("c:\\temp\\vitals.xml"), b);
}
 
Example 3
Source Project: org.hl7.fhir.core   Source File: ObservationStatsBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private static void addAge(Bundle b, int y, int m, String v) throws FHIRException {
  Observation obs = new Observation();
  obs.setId("obs-example-age-weight-"+Integer.toString(y)+"-"+Integer.toString(m));
  obs.setSubject(new Reference().setReference("Patient/123"));
  obs.setStatus(ObservationStatus.FINAL);
  Calendar when = Calendar.getInstance();
  when.add(Calendar.YEAR, -y);
  when.add(Calendar.MONTH, m);
  obs.setEffective(new DateTimeType(when));
  obs.getCode().addCoding().setCode("29463-7").setSystem("http://loinc.org");
  obs.setValue(new Quantity());
  obs.getValueQuantity().setCode("kg");
  obs.getValueQuantity().setSystem("http://unitsofmeasure.org");
  obs.getValueQuantity().setUnit("kg");
  obs.getValueQuantity().setValue(new BigDecimal(v));
  b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
}
 
Example 4
Source Project: org.hl7.fhir.core   Source File: Test.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
	try {
		CCDAConverter c = new CCDAConverter(new UcumEssenceService(UCUM_PATH), SimpleWorkerContext.fromPack(Utilities.path(SRC_PATH, "validation.zip")));
		Bundle a = c.convert(new FileInputStream(DEF_PATH + "ccda.xml"));
		String fx = DEF_PATH + "output.xml";
		IParser x = new XmlParser().setOutputStyle(OutputStyle.PRETTY);
		x.compose(new FileOutputStream(fx),  a);
		String fj = DEF_PATH + "output.json";
		IParser j = new JsonParser().setOutputStyle(OutputStyle.PRETTY);
		j.compose(new FileOutputStream(fj),  a);
		System.out.println("done. save as "+fx+" and "+fj);
	} catch (Exception e) {
		e.printStackTrace();
	}
	

}
 
Example 5
Source Project: org.hl7.fhir.core   Source File: LoincToDEConvertor.java    License: 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 6
Source Project: org.hl7.fhir.core   Source File: LoincToDEConvertor.java    License: Apache License 2.0 6 votes vote down vote up
public void process() throws FHIRFormatError, IOException, XmlPullParserException, SAXException, ParserConfigurationException {
	log("Begin. Produce Loinc CDEs in "+dest+" from "+definitions);
	loadLoinc();
	log("LOINC loaded");

	now = DateTimeType.now();

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

	processLoincCodes();
	if (dest != null) {
		log("Saving...");
		saveBundle();
	}
	log("Done");

}
 
Example 7
Source Project: org.hl7.fhir.core   Source File: FHIRToolingClient.java    License: Apache License 2.0 6 votes vote down vote up
public <T extends Resource> T getCanonical(Class<T> resourceClass, String canonicalURL) {
  ResourceRequest<T> result = null;
  try {
    result = utils.issueGetResourceRequest(resourceAddress.resolveGetUriFromResourceClassAndCanonical(resourceClass, canonicalURL), getPreferredResourceFormat());
    result.addErrorStatus(410);//gone
    result.addErrorStatus(404);//unknown
    result.addErrorStatus(405);//unknown
    result.addSuccessStatus(200);//Only one for now
    if(result.isUnsuccessfulRequest()) {
      throw new EFhirClientException("Server returned error code " + result.getHttpStatus(), (OperationOutcome)result.getPayload());
    }
  } catch (Exception e) {
    handleException("An error has occurred while trying to read this version of the resource", e);
  }
  Bundle bnd = (Bundle) result.getPayload();
  if (bnd.getEntry().size() == 0)
    throw new EFhirClientException("No matching resource found for canonical URL '"+canonicalURL+"'");
  if (bnd.getEntry().size() > 1)
    throw new EFhirClientException("Multiple matching resources found for canonical URL '"+canonicalURL+"'");
  return (T) bnd.getEntry().get(0).getResource();
}
 
Example 8
Source Project: org.hl7.fhir.core   Source File: NarrativeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
public XhtmlNode generateDocumentNarrative(Bundle feed) {
  /*
   When the document is presented for human consumption, applications must present the collated narrative portions of the following resources in order:
   * The Composition resource
   * The Subject resource
   * Resources referenced in the section.content
   */
  XhtmlNode root = new XhtmlNode(NodeType.Element, "div");
  Composition comp = (Composition) feed.getEntry().get(0).getResource();
  root.getChildNodes().add(comp.getText().getDiv());
  Resource subject = ResourceUtilities.getById(feed, null, comp.getSubject().getReference());
  if (subject != null && subject instanceof DomainResource) {
    root.hr();
    root.getChildNodes().add(((DomainResource)subject).getText().getDiv());
  }
  List<SectionComponent> sections = comp.getSection();
  renderSections(feed, root, sections, 1);
  return root;
}
 
Example 9
Source Project: org.hl7.fhir.core   Source File: NarrativeGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private void renderSections(Bundle feed, XhtmlNode node, List<SectionComponent> sections, int level) {
    for (SectionComponent section : sections) {
      node.hr();
      if (section.hasTitleElement())
        node.addTag("h"+Integer.toString(level)).addText(section.getTitle());
//      else if (section.hasCode())
//        node.addTag("h"+Integer.toString(level)).addText(displayCodeableConcept(section.getCode()));

//      if (section.hasText()) {
//        node.getChildNodes().add(section.getText().getDiv());
//      }
//
//      if (!section.getSection().isEmpty()) {
//        renderSections(feed, node.addTag("blockquote"), section.getSection(), level+1);
//      }
    }
  }
 
Example 10
Source Project: org.hl7.fhir.core   Source File: MessageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws FHIRException, IOException {
	// Create new Atom Feed
	Bundle feed = new Bundle();
	
	// Serialize Atom Feed
	IParser comp = new JsonParser();
	ByteArrayOutputStream os = new ByteArrayOutputStream();
	comp.compose(os, feed);
	os.close();
	String json = os.toString();
	
	// Deserialize Atom Feed
	JsonParser parser = new JsonParser();
	InputStream is = new ByteArrayInputStream(json.getBytes("UTF-8"));
	Resource result = parser.parse(is);
	if (result == null)
		throw new FHIRException("Bundle was null");
}
 
Example 11
Source Project: syndesis   Source File: FhirSearchCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterProducer(Exchange exchange) {
    Message in = exchange.getIn();
    Bundle bundle = in.getBody(Bundle.class);
    if (bundle == null) {
        return;
    }

    List<String> results = new ArrayList<>();
    for (Bundle.BundleEntryComponent entry: bundle.getEntry()) {
        String resource = fhirContext.newXmlParser().encodeResourceToString(entry.getResource());
        results.add(resource);
    }

    in.setBody(results);
}
 
Example 12
Source Project: syndesis   Source File: FhirSearchTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void searchTest() {
    Patient one = new Patient();
    one.setId("one");
    one.setGender(Enumerations.AdministrativeGender.UNKNOWN);
    Patient two = new Patient();
    two.setId("two");
    two.setGender(Enumerations.AdministrativeGender.UNKNOWN);

    Bundle bundle = new Bundle();
    bundle.getEntry().add(new Bundle.BundleEntryComponent().setResource(one));
    bundle.getEntry().add(new Bundle.BundleEntryComponent().setResource(two));

    stubFhirRequest(get(urlEqualTo("/Patient?gender=unknown&_format=xml")).willReturn(okXml(toXml(bundle))));

    FhirResourceQuery query = new FhirResourceQuery();
    query.setQuery("gender=unknown");

    String result = template.requestBody("direct:start", query, String.class);

    Assertions.assertThat(result).isEqualTo(
        "[<Patient xmlns=\"http://hl7.org/fhir\"><id value=\"one\"/><gender value=\"unknown\"/></Patient>, " +
        "<Patient xmlns=\"http://hl7.org/fhir\"><id value=\"two\"/><gender value=\"unknown\"/></Patient>]");
}
 
Example 13
Source Project: syndesis   Source File: FhirTransactionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("JdkObsolete")
public void transactionTest() {
    Bundle bundle = new Bundle();
    bundle.addEntry(new Bundle.BundleEntryComponent().setResource(new Account().setId("1").setMeta(new Meta().setLastUpdated(new Date()))));
    bundle.addEntry(new Bundle.BundleEntryComponent().setResource(new Patient().setId("2").setMeta(new Meta().setLastUpdated(new Date()))));
    stubFhirRequest(post(urlEqualTo("/?_format=xml")).withRequestBody(containing(
        "<type value=\"transaction\"/><total value=\"2\"/><link><relation value=\"fhir-base\"/></link>" +
            "<link><relation value=\"self\"/></link>" +
            "<entry><resource><Account xmlns=\"http://hl7.org/fhir\"><name value=\"Joe\"/></Account></resource>" +
            "<request><method value=\"POST\"/></request></entry><entry><resource>" +
            "<Patient xmlns=\"http://hl7.org/fhir\"><name><family value=\"Jackson\"/></name></Patient></resource>" +
            "<request><method value=\"POST\"/></request></entry>")).willReturn(okXml(toXml(bundle))));

    template.requestBody("direct:start",
        "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
            "<tns:Transaction xmlns:tns=\"http://hl7.org/fhir\">" +
            "<tns:Account><tns:name value=\"Joe\"/></tns:Account>" +
            "<tns:Patient><name><tns:family value=\"Jackson\"/></name></tns:Patient></tns:Transaction>");
}
 
Example 14
Source Project: synthea   Source File: FhirStu3.java    License: 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 15
Source Project: cqf-ruler   Source File: MeasureOperationsProvider.java    License: 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 16
Source Project: cqf-ruler   Source File: MeasureOperationsProvider.java    License: 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 17
Source Project: org.hl7.fhir.core   Source File: ObservationStatsBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static void vitals(Bundle b,  Calendar base, int minutes, int diastolic, int systolic, int sat, double temp) throws FHIRFormatError {
  Calendar when = (Calendar) base.clone();
  when.add(Calendar.MINUTE, minutes);
  
  baseVitals(b, when, minutes, "sat", "59408-5", "O2 Saturation").setValue(makeQty(sat, "%", "%"));
  baseVitals(b, when, minutes, "temp", "8310-5", "Body temperature").setValue(makeQty(temp, "\u00b0C", "Cel"));
  Observation obs = baseVitals(b, when, minutes, "bp", "85354-9", "Blood pressure");
  component(obs, "8480-6", "Systolic").setValue(makeQty(systolic, "mmhg", "mm[Hg]"));
  component(obs, "8462-4", "Diastolic").setValue(makeQty(diastolic, "mmhg", "mm[Hg]"));

}
 
Example 18
Source Project: org.hl7.fhir.core   Source File: ObservationStatsBuilder.java    License: Apache License 2.0 5 votes vote down vote up
private static Observation baseVitals(Bundle b, Calendar when, int min, String name, String lCode, String text) throws FHIRFormatError {
  Observation obs = new Observation();
  obs.setId("obs-vitals-"+name+"-"+Integer.toString(min));
  obs.setSubject(new Reference().setReference("Patient/123"));
  obs.setStatus(ObservationStatus.FINAL);
  obs.setEffective(new DateTimeType(when));
  obs.addCategory().setText("Vital Signs").addCoding().setSystem("http://hl7.org/fhir/observation-category").setCode("vital-signs").setDisplay("Vital Signs");
  obs.getCode().setText(text).addCoding().setCode(lCode).setSystem("http://loinc.org");
  b.addEntry().setFullUrl("http://hl7.org/fhir/Observation/"+obs.getId()).setResource(obs);
  return obs;
}
 
Example 19
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 20
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 21
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: Apache License 2.0 5 votes vote down vote up
public static String getLink(Bundle feed, String rel) {
for (BundleLinkComponent link : feed.getLink()) {
	if (link.getRelation().equals(rel))
		return link.getUrl();
}
 return null;
}
 
Example 22
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 23
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 24
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 25
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 26
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 27
Source Project: org.hl7.fhir.core   Source File: ResourceUtilities.java    License: 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 28
Source Project: org.hl7.fhir.core   Source File: ClientUtils.java    License: Apache License 2.0 5 votes vote down vote up
public Bundle issuePostFeedRequest(URI resourceUri, Map<String, String> parameters, String resourceName, Resource resource, String resourceFormat) throws IOException {
  HttpPost httppost = new HttpPost(resourceUri);
  String boundary = "----WebKitFormBoundarykbMUo6H8QaUnYtRy";
  httppost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);
  httppost.addHeader("Accept", resourceFormat);
  configureFhirRequest(httppost, null);
  HttpResponse response = sendPayload(httppost, encodeFormSubmission(parameters, resourceName, resource, boundary));
  return unmarshalFeed(response, resourceFormat);
}
 
Example 29
Source Project: org.hl7.fhir.core   Source File: FHIRToolingClient.java    License: Apache License 2.0 5 votes vote down vote up
public Bundle transaction(Bundle batch) {
	Bundle transactionResult = null;
	try {
		transactionResult = utils.postBatchRequest(resourceAddress.getBaseServiceUri(), utils.getFeedAsByteArray(batch, false, isJson(getPreferredResourceFormat())), getPreferredResourceFormat());
	} catch (Exception e) {
		handleException("An error occurred trying to process this transaction request", e);
	}
	return transactionResult;
}
 
Example 30
Source Project: org.hl7.fhir.core   Source File: FHIRToolingClient.java    License: Apache License 2.0 5 votes vote down vote up
public Bundle fetchFeed(String url) {
Bundle feed = null;
try {
	feed = utils.issueGetFeedRequest(new URI(url), getPreferredResourceFormat());
} catch (Exception e) {
	handleException("An error has occurred while trying to retrieve history since last update",e);
}
return feed;
}