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

The following examples show how to use ca.uhn.fhir.context.FhirContext#forR4() . 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: TestApplication.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
/**
 * This is the Java main method, which gets executed
 */
public static void main(String[] args) {

   // Create a context
   FhirContext ctx = FhirContext.forR4();

   // Create a client
   IGenericClient client = ctx.newRestfulGenericClient("https://hapi.fhir.org/baseR4");

   // Read a patient with the given ID
   Patient patient = client.read().resource(Patient.class).withId("example").execute();

   // Print the output
   String string = ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(patient);
   System.out.println(string);

}
 
Example 2
Source File: ValidationResources.java    From synthea with Apache License 2.0 6 votes vote down vote up
private void initializeR4() {
  FhirContext ctx = FhirContext.forR4();
  validatorR4 = ctx.newValidator();
  org.hl7.fhir.r4.hapi.validation.FhirInstanceValidator instanceValidator =
      new org.hl7.fhir.r4.hapi.validation.FhirInstanceValidator();
  ValidationSupportR4 validationSupport = new ValidationSupportR4();
  org.hl7.fhir.r4.hapi.validation.ValidationSupportChain support =
      new org.hl7.fhir.r4.hapi.validation.ValidationSupportChain(
          new org.hl7.fhir.r4.hapi.ctx.DefaultProfileValidationSupport(), validationSupport);
  instanceValidator.setValidationSupport(support);
  instanceValidator.setNoTerminologyChecks(true);

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

  validatorR4.registerValidatorModule(schemaValidator);
  validatorR4.registerValidatorModule(schematronValidator);
  validatorR4.registerValidatorModule(instanceValidator);
}
 
Example 3
Source File: Example07_ClientReadAndUpdate.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {
   // Create a client
	FhirContext ctx = FhirContext.forR4();
	IGenericClient client = ctx.newRestfulGenericClient("http://fhirtest.uhn.ca/R4");

	Patient patient = new Patient();
	patient.setId("Patient/example"); // Give the patient an ID
	patient.addName().setFamily("Simpson").addGiven("Homer");
	patient.setGender(Enumerations.AdministrativeGender.MALE);

	// Update the patient
	MethodOutcome outcome = client
        .update()
        .resource(patient)
        .execute();
	
	System.out.println("Now have ID: " + outcome.getId());
}
 
Example 4
Source File: Example06_ClientCreate.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static void main(String[] theArgs) {

      Patient pat = new Patient();
      pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");
      pat.addIdentifier().setSystem("http://acme.org/MRNs").setValue("7000135");
      pat.setGender(AdministrativeGender.MALE);

      // Create a context
      FhirContext ctx = FhirContext.forR4();

      // Create a client
      String serverBaseUrl = "http://hapi.fhir.org/baseR4";
      IGenericClient client = ctx.newRestfulGenericClient(serverBaseUrl);

      // Use the client to store a new resource instance
      MethodOutcome outcome = client
         .create()
         .resource(pat)
         .execute();

      // Print the ID of the newly created resource
      System.out.println(outcome.getId());
   }
 
Example 5
Source File: FHIRParserValidatorGeneratorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() {
    context = FhirContext.forR4();
    context.setParserErrorHandler(new StrictErrorHandler());
    fhirValidator = context.newValidator();
    validator = FHIRValidator.validator();
    jsonParser = FHIRParser.parser(Format.JSON);
    jsonGenerator = FHIRGenerator.generator(Format.JSON);
    xmlParser = FHIRParser.parser(Format.XML);
    xmlGenerator = FHIRGenerator.generator(Format.XML);
}
 
Example 6
Source File: FHIRValidatorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() throws Exception {
    context = FhirContext.forR4();
    fhirValidator = context.newValidator();
    baseResource = context.newJsonParser().parseResource(new StringReader(JSON_SPEC_EXAMPLE));
    validator = FHIRValidator.validator();
    resource = FHIRParser.parser(Format.JSON).parse(new StringReader(JSON_SPEC_EXAMPLE));
    evaluationContext = new EvaluationContext(resource);
}
 
Example 7
Source File: FHIRGeneratorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() throws Exception {
    if (exampleName == null) {
        System.err.println("exampleName is null; if you're in Eclipse then make sure annotation processing is on and you've ran 'mvn clean package'.");
        System.exit(1);
    }
    
    // us
    String JSON_SPEC_EXAMPLE = BenchmarkUtil.getSpecExample(Format.JSON, exampleName);
    resource = FHIRParser.parser(Format.JSON).parse(new StringReader(JSON_SPEC_EXAMPLE));
    
    // HAPI
    context = FhirContext.forR4();
    baseResource = context.newJsonParser().parseResource(new StringReader(JSON_SPEC_EXAMPLE));
}
 
Example 8
Source File: TestHelper.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Get an R4 FHIR Context for testing, but only initialize it once.
 * 
 * @return an R4 FhirContext
 */
public static FhirContext getR4FhirContext() {
  if (r4FhirContext == null) {
    r4FhirContext = FhirContext.forR4();
  }
  return r4FhirContext;
}
 
Example 9
Source File: FhirChCrlDocumentBundle.java    From elexis-3-core with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Write the FHIR bundle including the document to the provided file.
 * 
 * @param file
 * @throws IOException
 */
public void writeTo(File file) throws IOException{
	FhirContext ctx = FhirContext.forR4();
	String serialized = ctx.newXmlParser().encodeResourceToString(bundle);
	try (FileWriter out = new FileWriter(file)) {
		out.write(serialized);
	}
}
 
Example 10
Source File: TestSearchParameterResolver.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@Test void testR4SearchParams() {
    SearchParameterResolver resolver = new SearchParameterResolver(FhirContext.forR4());

    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", "reasonCode");
    assertNotNull(param);
    assertEquals("reason-code", param.getName());

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

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

    param = resolver.getSearchParameterDefinition("Observation", "code");
    assertNotNull(param);
    assertEquals("code", param.getName());

    param = resolver.getSearchParameterDefinition("Observation", "subject");
    assertNotNull(param);
    assertEquals("subject", param.getName());
}
 
Example 11
Source File: FhirServerConfigR4.java    From cqf-ruler with Apache License 2.0 5 votes vote down vote up
@Override
public FhirContext fhirContextR4() {
	FhirContext retVal = FhirContext.forR4();

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

	return retVal;
}
 
Example 12
Source File: FHIRParserBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() throws IOException {
    if (exampleName == null) {
        System.err.println("exampleName is null; if you're in Eclipse then make sure annotation processing is on and you've ran 'mvn clean package'.");
        System.exit(1);
    }
    System.out.println("Setting up for example " + exampleName);
    context = FhirContext.forR4();
    context.setParserErrorHandler(new StrictErrorHandler());
    JSON_SPEC_EXAMPLE = BenchmarkUtil.getSpecExample(Format.JSON, exampleName);
    XML_SPEC_EXAMPLE = BenchmarkUtil.getSpecExample(Format.XML, exampleName);
}
 
Example 13
Source File: FHIRPathEvaluatorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
public static void testRun(String exampleName, String expression) throws Exception {
    String specExample = BenchmarkUtil.getSpecExample(Format.JSON, exampleName);

    FhirContext context = FhirContext.forR4();
    IBaseResource baseResource = context.newJsonParser().parseResource(new StringReader(specExample));
    IFluentPath fluentPath = context.newFluentPath();
    System.out.println(fluentPath.evaluate(baseResource, expression, IBase.class));

    Resource resource = FHIRParser.parser(Format.JSON).parse(new StringReader(specExample));
    FHIRPathEvaluator evaluator = FHIRPathEvaluator.evaluator();
    EvaluationContext evaluationContext = new EvaluationContext(resource);
    System.out.println(evaluator.evaluate(evaluationContext, expression, singleton(evaluationContext.getTree().getRoot())));
}
 
Example 14
Source File: FHIRPathEvaluatorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Setup
public void setUp() throws Exception {
    context = FhirContext.forR4();
    fluentPath = context.newFluentPath();
    resource = FHIRParser.parser(Format.JSON).parse(new StringReader(JSON_SPEC_EXAMPLE));
    evaluator = FHIRPathEvaluator.evaluator();
    evaluationContext = new EvaluationContext(resource);
    initialContext = singleton(evaluationContext.getTree().getRoot());
    baseResource = context.newJsonParser().parseResource(new StringReader(JSON_SPEC_EXAMPLE));
}
 
Example 15
Source File: CCRIFHIRServer.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
@Bean(name="r4ctx")
public FhirContext getR4FhirContext() {

    return FhirContext.forR4();
}
 
Example 16
Source File: HospitalExporterTestR4.java    From synthea with Apache License 2.0 4 votes vote down vote up
@Test
public void testFHIRExport() throws Exception {
  FhirContext ctx = FhirContext.forR4();
  FhirValidator validator = ctx.newValidator();
  validator.setValidateAgainstStandardSchema(true);
  validator.setValidateAgainstStandardSchematron(true);

  File tempOutputFolder = tempFolder.newFolder();
  Config.set("exporter.baseDirectory", tempOutputFolder.toString());
  Config.set("exporter.hospital.fhir.export", "true");
  Config.set("exporter.fhir.transaction_bundle", "true");
  FhirR4.TRANSACTION_BUNDLE = true; // set this manually, in case it has already been loaded.
  TestHelper.loadTestProperties();
  Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
  Location location = new Location(Generator.DEFAULT_STATE, null);
  Provider.clear();
  Provider.loadProviders(location, 1L);
  assertNotNull(Provider.getProviderList());
  assertFalse(Provider.getProviderList().isEmpty());

  Provider.getProviderList().get(0).incrementEncounters(EncounterType.WELLNESS, 0);
  HospitalExporterR4.export(0L);

  File expectedExportFolder = tempOutputFolder.toPath().resolve("fhir").toFile();
  assertTrue(expectedExportFolder.exists() && expectedExportFolder.isDirectory());

  File expectedExportFile = expectedExportFolder.toPath().resolve("hospitalInformation0.json")
      .toFile();
  assertTrue(expectedExportFile.exists() && expectedExportFile.isFile());

  FileReader fileReader = new FileReader(expectedExportFile.getPath());
  BufferedReader bufferedReader = new BufferedReader(fileReader);
  StringBuilder fhirJson = new StringBuilder();
  String line = null;
  while ((line = bufferedReader.readLine()) != null) {
    fhirJson.append(line);
  }
  bufferedReader.close();
  IBaseResource resource = ctx.newJsonParser().parseResource(fhirJson.toString());
  ValidationResult result = validator.validateWithResult(resource);
  if (result.isSuccessful() == false) {
    for (SingleValidationMessage message : result.getMessages()) {
      System.out.println(message.getSeverity().toString() + ": " + message.getMessage());
    }
  }
  assertTrue(result.isSuccessful());
}
 
Example 17
Source File: FhirContextRecorder.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
public RuntimeValue<FhirContext> createR4FhirContext(BeanContainer container, Collection<String> resourceDefinitions) {
    FhirContext fhirContext = FhirContext.forR4();
    initContext(resourceDefinitions, fhirContext);
    container.instance(FhirContextProducers.class).setR4(fhirContext);
    return new RuntimeValue<>(fhirContext);
}
 
Example 18
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 19
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 20
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");
      }
    }
  }
}