ca.uhn.fhir.validation.FhirValidator Java Examples

The following examples show how to use ca.uhn.fhir.validation.FhirValidator. 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: 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 #2
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 #3
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 #4
Source File: CCRequestValidatingInterceptor.java    From careconnect-reference-implementation with Apache License 2.0 4 votes vote down vote up
public CCRequestValidatingInterceptor(Logger ourLog, FhirValidator fhirValidator, FhirContext ctx) {
    super();
    this.fhirValidator = fhirValidator;

    this.ctx = ctx;
}
 
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());
}
 
Example #9
Source File: Config.java    From careconnect-reference-implementation with Apache License 2.0 3 votes vote down vote up
@Bean(name="fhirValidatorSTU3")
public FhirValidator fhirValidatorSTU3 () {

    log.info("Creating FHIR Validator STU3");
    FhirValidator val = stu3ctx.newValidator();

    val.setValidateAgainstStandardSchema(true);

    // todo reactivate once this is fixed https://github.com/nhsconnect/careconnect-reference-implementation/issues/36
    val.setValidateAgainstStandardSchematron(false);

    DefaultProfileValidationSupport defaultProfileValidationSupport = new DefaultProfileValidationSupport();

    org.hl7.fhir.dstu3.hapi.validation.FhirInstanceValidator instanceValidator = new org.hl7.fhir.dstu3.hapi.validation.FhirInstanceValidator(defaultProfileValidationSupport);
    val.registerValidatorModule(instanceValidator);

    org.hl7.fhir.dstu3.hapi.validation.ValidationSupportChain validationSupportChain = new org.hl7.fhir.dstu3.hapi.validation.ValidationSupportChain();

    validationSupportChain.addValidationSupport(defaultProfileValidationSupport);
    validationSupportChain.addValidationSupport(new CareConnectProfileDbValidationSupportSTU3(stu3ctx));
    validationSupportChain.addValidationSupport(new SNOMEDUKDbValidationSupportSTU3(stu3ctx));

    instanceValidator.setValidationSupport(validationSupportChain);


    return val;
}
 
Example #10
Source File: Config.java    From careconnect-reference-implementation with Apache License 2.0 3 votes vote down vote up
@Bean(name="fhirValidatorR4")
public FhirValidator fhirValidatorR4 () {



    FhirValidator val = r4ctx.newValidator();

    val.setValidateAgainstStandardSchema(true);

    // todo reactivate once this is fixed https://github.com/nhsconnect/careconnect-reference-implementation/issues/36
    val.setValidateAgainstStandardSchematron(false);

    DefaultProfileValidationSupportStu3AsR4 defaultProfileValidationSupport = new DefaultProfileValidationSupportStu3AsR4();

    FhirInstanceValidator instanceValidator = new FhirInstanceValidator(defaultProfileValidationSupport);
    val.registerValidatorModule(instanceValidator);


    ValidationSupportChain validationSupportChain = new ValidationSupportChain();

    validationSupportChain.addValidationSupport(defaultProfileValidationSupport);
    validationSupportChain.addValidationSupport(new CareConnectProfileDbValidationSupportR4(r4ctx, stu3ctx, HapiProperties.getTerminologyServerSecondary()));
    validationSupportChain.addValidationSupport(new SNOMEDUKDbValidationSupportR4(r4ctx, stu3ctx));

    instanceValidator.setValidationSupport(validationSupportChain);


    return val;
}