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

The following examples show how to use ca.uhn.fhir.context.FhirContext#newValidator() . 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: 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 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: 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 4
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 5
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 6
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 7
Source File: HospitalExporterTestStu3.java    From synthea with Apache License 2.0 4 votes vote down vote up
@Test
public void testFHIRExport() throws Exception {
  FhirContext ctx = FhirContext.forDstu3();
  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_stu3.export", "true");
  Config.set("exporter.fhir.transaction_bundle", "true");
  FhirStu3.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);
  HospitalExporterStu3.export(0L);

  File expectedExportFolder = tempOutputFolder.toPath().resolve("fhir_stu3").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 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());
}