Java Code Examples for ca.uhn.fhir.context.FhirContext#forDstu3()

The following examples show how to use ca.uhn.fhir.context.FhirContext#forDstu3() . 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: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
public static void step2_search_for_patients_named_test() {
	FhirContext ctx = FhirContext.forDstu3();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

	org.hl7.fhir.r4.model.Bundle results = client
		.search()
		.forResource(Patient.class)
		.where(Patient.NAME.matches().value("test"))
		.returnBundle(org.hl7.fhir.r4.model.Bundle.class)
		.execute();

	System.out.println("First page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(results));

	// Load the next page
	org.hl7.fhir.r4.model.Bundle nextPage = client
		.loadPage()
		.next(results)
		.execute();

	System.out.println("Next page: ");
	System.out.println(ctx.newXmlParser().encodeResourceToString(nextPage));

}
 
Example 2
Source File: Example08_ClientSearch.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
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 3
Source File: ValidationResources.java    From synthea with Apache License 2.0 6 votes vote down vote up
private void initializeSTU3() {
  FhirContext ctx = FhirContext.forDstu3();
  validatorSTU3 = ctx.newValidator();
  org.hl7.fhir.dstu3.hapi.validation.FhirInstanceValidator instanceValidator =
      new org.hl7.fhir.dstu3.hapi.validation.FhirInstanceValidator();
  ValidationSupportSTU3 validationSupport = new ValidationSupportSTU3();
  org.hl7.fhir.dstu3.hapi.validation.ValidationSupportChain support =
      new org.hl7.fhir.dstu3.hapi.validation.ValidationSupportChain(
          new org.hl7.fhir.dstu3.hapi.ctx.DefaultProfileValidationSupport(), validationSupport);
  instanceValidator.setValidationSupport(support);

  IValidatorModule schemaValidator = new SchemaBaseValidator(ctx);
  IValidatorModule schematronValidator = new SchematronBaseValidator(ctx);

  validatorSTU3.registerValidatorModule(schemaValidator);
  validatorSTU3.registerValidatorModule(schematronValidator);
  validatorSTU3.registerValidatorModule(instanceValidator);
}
 
Example 4
Source File: Example21_ValidateResourceString.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) {

      String input = "<Encounter xmlns=\"http://hl7.org/fhir\"></Encounter>";

      // Create a new validator
      FhirContext ctx = FhirContext.forDstu3();
      FhirValidator validator = ctx.newValidator();

      // Did we succeed?
      ValidationResult result = validator.validateWithResult(input);
      System.out.println("Success: " + result.isSuccessful());

      // What was the result
      OperationOutcome outcome = (OperationOutcome) result.toOperationOutcome();
      IParser parser = ctx.newXmlParser().setPrettyPrint(true);
      System.out.println(parser.encodeResourceToString(outcome));
   }
 
Example 5
Source File: Example20_ValidateResource.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] args) {
	
	// Create an incomplete encounter (status is required)
	Encounter enc = new Encounter();
	enc.addIdentifier().setSystem("http://acme.org/encNums").setValue("12345");
	
	// Create a new validator
	FhirContext ctx = FhirContext.forDstu3();
	FhirValidator validator = ctx.newValidator();
	
	// Did we succeed?
	ValidationResult result = validator.validateWithResult(enc);
	System.out.println("Success: " + result.isSuccessful());
	
	// What was the result
	OperationOutcome outcome = (OperationOutcome) result.toOperationOutcome();
	IParser parser = ctx.newXmlParser().setPrettyPrint(true);
	System.out.println(parser.encodeResourceToString(outcome));
}
 
Example 6
Source File: TestFhirLibrary.java    From cql_engine with Apache License 2.0 6 votes vote down vote up
public void TestCMS9v4_CQM() throws IOException, JAXBException {
      File xmlFile = new File(URLDecoder.decode(TestFhirLibrary.class.getResource("CMS9v4_CQM.xml").getFile(), "UTF-8"));
      Library library = CqlLibraryReader.read(xmlFile);

      Context context = new Context(library);

      FhirContext fhirContext = FhirContext.forDstu3();

Dstu3FhirModelResolver modelResolver = new Dstu3FhirModelResolver();
RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext),  fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"));
CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://fhir3.healthintersections.com.au/open/");
      //BaseFhirDataProvider provider = new FhirDataProviderStu3().setEndpoint("http://wildfhir.aegis.net/fhir");
      context.registerDataProvider("http://hl7.org/fhir", provider);

      Object result = context.resolveExpressionRef("Breastfeeding Intention Assessment").evaluate(context);
      assertThat(result, instanceOf(Iterable.class));
      for (Object element : (Iterable)result) {
          assertThat(element, instanceOf(RiskAssessment.class));
      }
  }
 
Example 7
Source File: TestFhirPath.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testFhirHelpersStu3() throws UcumException {
    String cql = getStringFromResourceStream("stu3/TestFHIRHelpers.cql");
    Library library = translate(cql);
    Context context = new Context(library);
    context.registerLibraryLoader(getLibraryLoader());

    Dstu3FhirModelResolver modelResolver = new Dstu3FhirModelResolver();
    FhirContext fhirContext = FhirContext.forDstu3();
    RestFhirRetrieveProvider retrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(fhirContext),
            fhirContext.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3"));
    CompositeDataProvider provider = new CompositeDataProvider(modelResolver, retrieveProvider);
    // BaseFhirDataProvider provider = new
    // FhirDataProviderStu3().setEndpoint("http://fhirtest.uhn.ca/baseDstu3");
    context.registerDataProvider("http://hl7.org/fhir", provider);

    Object result = context.resolveExpressionRef("TestPeriodToInterval").getExpression().evaluate(context);
    // TODO - fix
    // Assert.assertEquals(((DateTime)((Interval) result).getStart()).getPartial(),
    // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 18, 8, 0}));
    // Assert.assertEquals(((DateTime)((Interval) result).getEnd()).getPartial(),
    // new Partial(DateTime.getFields(6), new int[] {2017, 5, 6, 19, 8, 0}));
    result = context.resolveExpressionRef("TestToQuantity").getExpression().evaluate(context);
    // TODO: ModelInfo bug. Not aware of SimpleQuantity
    result = context.resolveExpressionRef("TestRangeToInterval").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToCode").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToConcept").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToString").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestRequestStatusToString").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToDateTime").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToTime").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToInteger").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToDecimal").getExpression().evaluate(context);
    result = context.resolveExpressionRef("TestToBoolean").getExpression().evaluate(context);
}
 
Example 8
Source File: TestApplicationHints.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void step3_create_patient() {
	// Create a patient
	Patient newPatient = new Patient();

	// Populate the patient with fake information
	newPatient
		.addName()
			.setFamily("DevDays2015")
			.addGiven("John")
			.addGiven("Q");
	newPatient
		.addIdentifier()
			.setSystem("http://acme.org/mrn")
			.setValue("1234567");
	newPatient.setGender(Enumerations.AdministrativeGender.MALE);
	newPatient.setBirthDateElement(new DateType("2015-11-18"));

	// Create a client
	FhirContext ctx = FhirContext.forDstu3();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu3");

	// Create the resource on the server
	MethodOutcome outcome = client
		.create()
		.resource(newPatient)
		.execute();

	// Log the ID that the server assigned
	IIdType id = outcome.getId();
	System.out.println("Created patient, got ID: " + id);
}
 
Example 9
Source File: FhirServerConfigDstu3.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Override
public FhirContext fhirContextDstu3() {
	FhirContext retVal = FhirContext.forDstu3();

	// Don't strip versions in some places
	ParserOptions parserOptions = retVal.getParserOptions();
	parserOptions.setDontStripVersionsFromReferencesAtPaths("AuditEvent.entity.reference");

	return retVal;
}
 
Example 10
Source File: TestSearchParameterResolver.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Test void testDstu3SearchParams() {
    SearchParameterResolver resolver = new SearchParameterResolver(FhirContext.forDstu3());

    RuntimeSearchParam param = resolver.getSearchParameterDefinition("Patient", "id");
    assertNotNull(param);
    assertEquals("_id", param.getName());

    
    param = resolver.getSearchParameterDefinition("MedicationAdministration", "medication", RestSearchParameterTypeEnum.TOKEN);
    assertNotNull(param);
    assertEquals("code", param.getName());

    param = resolver.getSearchParameterDefinition("MedicationAdministration", "medication", RestSearchParameterTypeEnum.REFERENCE);
    assertNotNull(param);
    assertEquals("medication", param.getName());


    param = resolver.getSearchParameterDefinition("Encounter", "period");
    assertNotNull(param);
    assertEquals("date", param.getName());

    param = resolver.getSearchParameterDefinition("Encounter", "reason");
    assertNotNull(param);
    assertEquals("reason", param.getName());

    param = resolver.getSearchParameterDefinition("Encounter", "subject");
    assertNotNull(param);
    assertEquals("patient", param.getName());

    param = resolver.getSearchParameterDefinition("Encounter", "type");
    assertNotNull(param);
    assertEquals("type", param.getName());
}
 
Example 11
Source File: TestSearchParameterResolver.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Test
public void testReturnsNullPathReturnsNull() {
    SearchParameterResolver resolver = new SearchParameterResolver(FhirContext.forDstu3());

    RuntimeSearchParam param = resolver.getSearchParameterDefinition("Patient", null);
    assertNull(param);
}
 
Example 12
Source File: TestHelper.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Get a FHIR STU3 Context for testing, but only initialize it once.
 * 
 * @return an STU3 FhirContext
 */
public static FhirContext getStu3FhirContext() {
  if (stu3FhirContext == null) {
    stu3FhirContext = FhirContext.forDstu3();
  }
  return stu3FhirContext;
}
 
Example 13
Source File: FhirContextRecorder.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
public RuntimeValue<FhirContext> createDstu3FhirContext(BeanContainer container, Collection<String> resourceDefinitions) {
    FhirContext fhirContext = FhirContext.forDstu3();
    initContext(resourceDefinitions, fhirContext);
    container.instance(FhirContextProducers.class).setDstu3(fhirContext);
    return new RuntimeValue<>(fhirContext);
}
 
Example 14
Source File: R4FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public R4FhirTerminologyProvider() {
    this.fhirContext = FhirContext.forDstu3();
}
 
Example 15
Source File: Dstu3FhirTerminologyProvider.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public Dstu3FhirTerminologyProvider() {
    this.fhirContext = FhirContext.forDstu3();
}
 
Example 16
Source File: Dstu3FhirModelResolver.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public Dstu3FhirModelResolver() {
    this(FhirContext.forDstu3());
}
 
Example 17
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 18
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 19
Source File: ExampleRestfulServlet.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * Constructor
 */
public ExampleRestfulServlet() {
	super(FhirContext.forDstu3()); // This is an STU3 server
}
 
Example 20
Source File: CCRIFHIRServer.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
@Bean(name="stu3ctx")
@Primary
public FhirContext getStu3FhirContext() {

    return FhirContext.forDstu3();
}