Java Code Examples for ca.uhn.fhir.validation.ValidationResult#isSuccessful()

The following examples show how to use ca.uhn.fhir.validation.ValidationResult#isSuccessful() . 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: 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 2
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 3
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 4
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 5
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());
}