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

The following examples show how to use ca.uhn.fhir.context.FhirContext#forDstu2() . 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: TestHelper.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Get a FHIR DSTU2 Context for testing, but only initialize it once.
 * 
 * @return a DSTU2 FhirContext
 */
public static FhirContext getDstu2FhirContext() {
  if (dstu2FhirContext == null) {
    dstu2FhirContext = FhirContext.forDstu2();
  }
  return dstu2FhirContext;
}
 
Example 2
Source File: FhirExecutionTestBase.java    From cql_engine with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public void setup() {
    dstu2ModelResolver = new Dstu2FhirModelResolver();
    FhirContext dstu2Context = FhirContext.forDstu2();
    dstu2RetrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(dstu2Context),
            dstu2Context.newRestfulGenericClient("http://fhirtest.uhn.ca/baseDstu2"));
    dstu2Provider = new CompositeDataProvider(dstu2ModelResolver, dstu2RetrieveProvider);
    
    dstu3ModelResolver = new Dstu3FhirModelResolver();
    FhirContext dstu3Context = FhirContext.forDstu3();
    dstu3RetrieveProvider = new RestFhirRetrieveProvider(new SearchParameterResolver(dstu3Context), 
    dstu3Context.newRestfulGenericClient("http://measure.eval.kanvix.com/cqf-ruler/baseDstu3"));
    dstu3Provider = new CompositeDataProvider(dstu3ModelResolver, dstu3RetrieveProvider);

}
 
Example 3
Source File: Example99_NarrativeGenerator.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
	
	// Create an encounter with an invalid status and no class
	Patient pat = new Patient();
	pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("Jay");
	pat.addAddress().addLine("342 Evergreen Terrace").addLine("Springfield");
	pat.addIdentifier().setSystem("http://acme.org/mrns").setValue("12345");
	
	// Create a new context and enable the narrative generator
	FhirContext ctx = FhirContext.forDstu2();
	ctx.setNarrativeGenerator(new DefaultThymeleafNarrativeGenerator());
	
	String res = ctx.newJsonParser().setPrettyPrint(true).encodeResourceToString(pat);
	System.out.println(res);
}
 
Example 4
Source File: FhirContextRecorder.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
public RuntimeValue<FhirContext> createDstu2FhirContext(BeanContainer container, Collection<String> resourceDefinitions) {
    FhirContext fhirContext = FhirContext.forDstu2();
    initContext(resourceDefinitions, fhirContext);
    container.instance(FhirContextProducers.class).setDstu2(fhirContext);
    return new RuntimeValue<>(fhirContext);
}
 
Example 5
Source File: FHIRDSTU2ExporterTest.java    From synthea with Apache License 2.0 4 votes vote down vote up
@Test
public void testFHIRDSTU2Export() throws Exception {
  TestHelper.loadTestProperties();
  Generator.DEFAULT_STATE = Config.get("test_state.default", "Massachusetts");
  Config.set("exporter.baseDirectory", tempFolder.newFolder().toString());

  FhirContext ctx = FhirContext.forDstu2();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);

  FhirValidator validator = ctx.newValidator();
  validator.setValidateAgainstStandardSchema(true);
  validator.setValidateAgainstStandardSchematron(true);

  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);
    Config.set("exporter.fhir_dstu2.export", "true");
    FhirDstu2.TRANSACTION_BUNDLE = person.random.nextBoolean();
    String fhirJson = FhirDstu2.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.validateWithResult(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 (Entry entry : bundle.getEntry()) {
        ValidationResult eresult = validator.validateWithResult(entry.getResource());
        if (!eresult.isSuccessful()) {
          for (SingleValidationMessage emessage : eresult.getMessages()) {
            System.out.println(parser.encodeResourceToString(entry.getResource()));
            System.out.println("ERROR: " + emessage.getMessage());
            validationErrors.add(emessage.getMessage());
          }
        }
        if (entry.getResource() instanceof DiagnosticReport) {
          DiagnosticReport report = (DiagnosticReport) entry.getResource();
          if (report.getPerformer().isEmpty()) {
            validationErrors.add("Performer is a required field on DiagnosticReport!");
          }
        }
      }
    }
    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 6
Source File: FHIRDSTU2ExporterTest.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.forDstu2();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  String fhirJson = FhirDstu2.convertToFHIRJson(person, System.currentTimeMillis());
  Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
  
  for (Entry entry : bundle.getEntry()) {
    if (entry.getResource() instanceof Observation) {
      Observation obs = (Observation) entry.getResource();
      assertTrue(obs.getValue() instanceof SampledDataDt);
      SampledDataDt data = (SampledDataDt) obs.getValue();
      assertEquals(10, data.getPeriod().doubleValue(), 0.001); // 0.01s == 10ms
      assertEquals(3, (int) data.getDimensions());
    }
  }
}
 
Example 7
Source File: FHIRDSTU2ExporterTest.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.forDstu2();
  IParser parser = ctx.newJsonParser().setPrettyPrint(true);
  String fhirJson = FhirDstu2.convertToFHIRJson(person, System.currentTimeMillis());
  Bundle bundle = parser.parseResource(Bundle.class, fhirJson);
  
  for (Entry entry : bundle.getEntry()) {
    if (entry.getResource() instanceof Media) {
      Media media = (Media) entry.getResource();
      if (media.getContent().getData() != null) {
        assertEquals(400, (int)media.getWidth());
        assertEquals(200, (int)media.getHeight());
        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 8
Source File: HospitalExporterTestDstu2.java    From synthea with Apache License 2.0 4 votes vote down vote up
@Test
public void testFHIRExport() throws Exception {
  FhirContext ctx = FhirContext.forDstu2();
  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_dstu2.export", "true");
  Config.set("exporter.fhir.transaction_bundle", "true");
  FhirDstu2.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);
  HospitalExporterDstu2.export(0L);

  File expectedExportFolder = tempOutputFolder.toPath().resolve("fhir_dstu2").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 9
Source File: Dstu2FhirModelResolver.java    From cql_engine with Apache License 2.0 4 votes vote down vote up
public Dstu2FhirModelResolver() {
	this(FhirContext.forDstu2());
}