ca.uhn.fhir.parser.IParser Java Examples

The following examples show how to use ca.uhn.fhir.parser.IParser. 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: Example30_AddSomeExtensions.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");

// Add an extension on the resource
pat.addExtension()
		.setUrl("http://hl7.org/fhir/StructureDefinition/patient-importance")
		.setValue(new CodeableConcept().setText("Patient is a VIP"));

// Add an extension on a primitive
pat.getBirthDateElement().setValueAsString("1955-02-22");
pat.getBirthDateElement().addExtension()
		.setUrl("http://hl7.org/fhir/StructureDefinition/patient-birthTime")
		.setValue(new TimeType("23:30"));

    IParser parser = FhirContext.forDstu3().newJsonParser().setPrettyPrint(true);
    System.out.println(parser.encodeResourceToString(pat));
 }
 
Example #2
Source File: FhirTransactionCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    String body = in.getBody(String.class);

    if (body != null) {
        List<IBaseResource> resources = new ArrayList<>();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(body.getBytes("UTF-8")));
            Node transactionElement = doc.getFirstChild();
            NodeList childNodes = transactionElement.getChildNodes();
            IParser parser = fhirContext.newXmlParser();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node resourceNode = childNodes.item(i);
                Document resourceDocument = toDocument(resourceNode, dbf);
                String resourceXml = toXml(resourceDocument);
                IBaseResource resource = parser.parseResource(resourceXml);
                resources.add(resource);
            }
        } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
            throw new RuntimeExchangeException("Cannot convert Transaction to a list of resources", exchange, e);
        }

        in.setHeader("CamelFhir.resources", resources);
    }
}
 
Example #3
Source File: FhirTransactionCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    @SuppressWarnings("unchecked")
    List<IBaseResource> body = in.getBody(List.class);

    StringBuilder transaction = new StringBuilder("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" +
        "<Transaction xmlns=\"http://hl7.org/fhir\">");
    IParser parser = fhirContext.newXmlParser();
    for (IBaseResource resource: body) {
        String encodedResource = parser.encodeResourceToString(resource);
        transaction.append(encodedResource);
    }
    transaction.append("</Transaction>");

    in.setBody(transaction.toString());
}
 
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: ValidationSupportR4.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Loads the structure definitions from the given directory.
 * @param rootDir the directory to load structure definitions from
 * @return a list of structure definitions
 * @throws Throwable when there is an error reading the structure definitions.
 */
private void loadFromDirectory(String rootDir) throws Throwable {

  IParser jsonParser = FhirContext.forR4().newJsonParser();
  jsonParser.setParserErrorHandler(new StrictErrorHandler());

  URL profilesFolder = ClassLoader.getSystemClassLoader().getResource(rootDir);
  Path path = Paths.get(profilesFolder.toURI());
  Files.walk(path, Integer.MAX_VALUE).filter(Files::isReadable).filter(Files::isRegularFile)
      .filter(p -> p.toString().endsWith(".json")).forEach(f -> {
        try {
          IBaseResource resource = jsonParser.parseResource(new FileReader(f.toFile()));
          handleResource(resource);
        } catch (FileNotFoundException e) {
          throw new RuntimeException(e);
        }
      });
}
 
Example #6
Source File: UsCoreStu3ProfileProvider.java    From bunsen with Apache License 2.0 6 votes vote down vote up
private static void load(PrePopulatedValidationSupport support,
    IParser jsonParser,
    String resource) {

  try (InputStream input = UsCoreStu3ProfileProvider.class
      .getClassLoader()
      .getResourceAsStream(resource)) {

    StructureDefinition definition = (StructureDefinition)
        jsonParser.parseResource(new InputStreamReader(input));

    support.addStructureDefinition(definition);

  } catch (IOException exception) {

    throw new RuntimeException(exception);
  }
}
 
Example #7
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 #8
Source File: Example04_EncodeResource.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 Patient
		Patient pat = new Patient();
		pat.addName().setFamily("Simpson").addGiven("Homer").addGiven("J");
		pat.addIdentifier().setSystem("http://acme.org/MRNs").setValue("7000135");
		pat.addTelecom().setUse(ContactPointUse.HOME).setSystem(ContactPointSystem.PHONE).setValue("1 (416) 340-4800");
		pat.setGender(AdministrativeGender.MALE);

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

		// Create a JSON parser
		IParser parser = ctx.newJsonParser();
		parser.setPrettyPrint(true);

		String encode = parser.encodeResourceToString(pat);
		System.out.println(encode);

	}
 
Example #9
Source File: BunsenTestStu3ProfileProvider.java    From bunsen with Apache License 2.0 6 votes vote down vote up
private static void addBunsenTestStu3ProfileDefinitions(PrePopulatedValidationSupport support,
    FhirContext context) {

  IParser parser = context.newJsonParser();

  load(support, parser, "definitions/StructureDefinition-bunsen-test-profile-booleanfield.json");
  load(support, parser, "definitions/StructureDefinition-bunsen-test-profile-integerfield.json");
  load(support, parser, "definitions/StructureDefinition-bunsen-test-profile-Patient.json");
  load(support, parser,
      "definitions/StructureDefinition-bunsen-test-profile-integerArrayField.json");
  load(support, parser,
      "definitions/StructureDefinition-bunsen-test-profile-nested-extension.json");
  load(support, parser,
      "definitions/StructureDefinition-bunsen-test-profile-codeableconcept-ext.json");
  load(support, parser,
      "definitions/StructureDefinition-bunsen-test-codeableConcept-modifierExt.json");
  load(support, parser,
      "definitions/StructureDefinition-bunsen-test-string-modifierExt.json");
}
 
Example #10
Source File: Example22_ValidateResourceInstanceValidator.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
   FhirValidator validator = FhirContext.forDstu3().newValidator();

   // Cache this object! Supplies structure definitions
   DefaultProfileValidationSupport support = new DefaultProfileValidationSupport();

   // Create the validator
   FhirInstanceValidator module = new FhirInstanceValidator(support);
   validator.registerValidatorModule(module);

   // Did we succeed?
   IParser parser = FhirContext.forDstu3().newXmlParser().setPrettyPrint(true);
   System.out.println(parser.encodeResourceToString(validator.validateWithResult(enc).toOperationOutcome()));
}
 
Example #11
Source File: ValidationSupportSTU3.java    From synthea with Apache License 2.0 5 votes vote down vote up
/**
 * Loads the structure definitions from the given directory.
 * @param rootDir the directory to load structure definitions from
 * @return a list of structure definitions
 * @throws Throwable when there is an error reading the structure definitions.
 */
private void loadFromDirectory(String rootDir) throws Throwable {

  IParser jsonParser = FhirContext.forDstu3().newJsonParser();
  jsonParser.setParserErrorHandler(new StrictErrorHandler());

  URL profilesFolder = ClassLoader.getSystemClassLoader().getResource(rootDir);
  Path path = Paths.get(profilesFolder.toURI());
  Files.walk(path, Integer.MAX_VALUE).filter(Files::isReadable).filter(Files::isRegularFile)
      .filter(p -> p.toString().endsWith(".json")).forEach(f -> {
        try {
          IBaseResource resource = jsonParser.parseResource(new FileReader(f.toFile()));
          resources.add(resource);
          if (resource instanceof CodeSystem) {
            CodeSystem cs = (CodeSystem) resource;
            resourcesMap.put(cs.getUrl(), cs);
            codeSystemMap.put(cs.getUrl(), cs);
          } else if (resource instanceof ValueSet) {
            ValueSet vs = (ValueSet) resource;
            resourcesMap.put(vs.getUrl(), vs);
          } else if (resource instanceof StructureDefinition) {
            StructureDefinition sd = (StructureDefinition) resource;
            resourcesMap.put(sd.getUrl(), sd);
            definitions.add(sd);
            definitionsMap.put(sd.getUrl(), sd);
          }
        } catch (FileNotFoundException e) {
          throw new RuntimeException(e);
        }
      });
}
 
Example #12
Source File: Example33_UseExtendedPatient.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
     Example32_ExtendedPatient pat = new Example32_ExtendedPatient();
	pat.addName().setFamily("Simpson").addGiven("Homer");

	pat.setEyeColour(new CodeType("blue"));

	IParser p = FhirContext.forDstu3().newXmlParser().setPrettyPrint(true);
	String encoded = p.encodeResourceToString(pat);
	
	System.out.println(encoded);
}
 
Example #13
Source File: Example35_ParserErrorHandler.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {

      String input =
         "{" +
            "\"resourceType\": \"Patient\"," +
            "\"foo\": \"bar\"" +
            "}";

      FhirContext ctx = FhirContext.forDstu3();
      IParser parser = ctx.newJsonParser();
      parser.setParserErrorHandler(new StrictErrorHandler());
      IBaseResource output = parser.parseResource(input);
   }
 
Example #14
Source File: Example12_ParserErrorHandler.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static void main(String[] args) {
	String input = "<Encounter xmlns=\"http://hl7.org/fhir\"><AAAA value=\"foo\"/></Encounter>";

	IParser p = FhirContext.forDstu3().newXmlParser();
	
	// Parse with (default) lenient error handler
	p.setParserErrorHandler(new LenientErrorHandler());
	p.parseResource(input);

	// Parse with strict error handler
	p.setParserErrorHandler(new StrictErrorHandler());
	p.parseResource(input);
}
 
Example #15
Source File: UsCoreStu3ProfileProvider.java    From bunsen with Apache License 2.0 5 votes vote down vote up
private static void addUsCoreDefinitions(PrePopulatedValidationSupport support,
    FhirContext context) {

  IParser parser = context.newJsonParser();

  load(support, parser, "definitions/StructureDefinition-us-core-allergyintolerance.json");
  load(support, parser, "definitions/StructureDefinition-us-core-birthsex.json");
  load(support, parser, "definitions/StructureDefinition-us-core-careplan.json");
  load(support, parser, "definitions/StructureDefinition-us-core-careteam.json");
  load(support, parser, "definitions/StructureDefinition-us-core-condition.json");
  load(support, parser, "definitions/StructureDefinition-us-core-device.json");
  load(support, parser, "definitions/StructureDefinition-us-core-diagnosticreport.json");
  load(support, parser, "definitions/StructureDefinition-us-core-direct.json");
  load(support, parser, "definitions/StructureDefinition-us-core-documentreference.json");
  load(support, parser, "definitions/StructureDefinition-us-core-encounter.json");
  load(support, parser, "definitions/StructureDefinition-us-core-ethnicity.json");
  load(support, parser, "definitions/StructureDefinition-us-core-goal.json");
  load(support, parser, "definitions/StructureDefinition-us-core-immunization.json");
  load(support, parser, "definitions/StructureDefinition-us-core-location.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medication.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medicationrequest.json");
  load(support, parser, "definitions/StructureDefinition-us-core-medicationstatement.json");
  load(support, parser, "definitions/StructureDefinition-us-core-observationresults.json");
  load(support, parser, "definitions/StructureDefinition-us-core-organization.json");
  load(support, parser, "definitions/StructureDefinition-us-core-patient.json");
  load(support, parser, "definitions/StructureDefinition-us-core-practitioner.json");
  load(support, parser, "definitions/StructureDefinition-us-core-practitionerrole.json");
  load(support, parser, "definitions/StructureDefinition-us-core-procedure.json");
  load(support, parser, "definitions/StructureDefinition-us-core-profile-link.json");
  load(support, parser, "definitions/StructureDefinition-us-core-race.json");
  load(support, parser, "definitions/StructureDefinition-us-core-smokingstatus.json");

}
 
Example #16
Source File: FHIRParserValidatorGeneratorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void benchmarkHAPIXMLParserValidatorGenerator(FHIRParserValidatorGeneratorBenchmarkState state) throws Exception {
    IParser parser = state.context.newXmlParser();
    IBaseResource baseResource = parser.parseResource(new StringReader(FHIRParserValidatorGeneratorBenchmarkState.XML_SPEC_EXAMPLE));
    state.fhirValidator.validateWithResult(baseResource);
    parser.encodeResourceToWriter(baseResource, FHIRParserValidatorGeneratorBenchmarkState.NOP_WRITER);
}
 
Example #17
Source File: FHIRParserValidatorGeneratorBenchmark.java    From FHIR with Apache License 2.0 5 votes vote down vote up
@Benchmark
public void benchmarkHAPIJsonParserValidatorGenerator(FHIRParserValidatorGeneratorBenchmarkState state) throws Exception {
    IParser parser = state.context.newJsonParser();
    IBaseResource resource = parser.parseResource(new StringReader(FHIRParserValidatorGeneratorBenchmarkState.JSON_SPEC_EXAMPLE));
    state.fhirValidator.validateWithResult(resource);
    parser.encodeResourceToWriter(resource, FHIRParserValidatorGeneratorBenchmarkState.NOP_WRITER);
}
 
Example #18
Source File: Example05_ParseResource.java    From fhirstarters with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public static void main(String[] theArgs) {
	
	String resourceBody = "{\"resourceType\":\"Patient\",\"identifier\":[{\"system\":\"http://acme.org/MRNs\",\"value\":\"7000135\"}],\"name\":[{\"family\":[\"Simpson\"],\"given\":[\"Homer\",\"J\"]}]}";

	// Create a context
	FhirContext ctx = FhirContext.forDstu3();
	
	// Create a JSON parser
	IParser parser = ctx.newJsonParser();
	Patient pat = parser.parseResource(Patient.class, resourceBody);
	
	List<Identifier> identifiers = pat.getIdentifier();
	String idSystemString = identifiers.get(0).getSystem();
	String idValueString = identifiers.get(0).getValue();
	
	System.out.println(idSystemString + " " + idValueString);
	
}
 
Example #19
Source File: ModelUtil.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
private static IParser getJsonParser() {
	return context.newJsonParser();
}
 
Example #20
Source File: FhirUtil.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
private static IParser getJsonParser() {
	return context.newJsonParser();
}
 
Example #21
Source File: FhirContextSubstitution.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@Substitute
public IParser newRDFParser() {
    throw new UnsupportedOperationException();
}
 
Example #22
Source File: AllTests.java    From elexis-3-core with Eclipse Public License 1.0 4 votes vote down vote up
public static IParser getJsonParser() {
	return context.newJsonParser();
}
 
Example #23
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 #24
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 #25
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 #26
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");
      }
    }
  }
}
 
Example #27
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 #28
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 #29
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 #30
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());
    }
  }
}