Search in sources :

Example 21 with ValidationOptions

use of org.hl7.fhir.utilities.validation.ValidationOptions in project dpc-app by CMSgov.

the class ValidationHelpers method validateAgainstProfile.

/**
 * Validates the provided {@link Resource} against the given Profile
 *
 * @param validator  - {@link FhirValidator} to use for validation
 * @param params     - {@link Parameters} to get resource from
 * @param profileURL - {@link String} profile URL to use for validation
 * @return - {@link IBaseOperationOutcome} outcome with failures (if any)
 */
public static IBaseOperationOutcome validateAgainstProfile(FhirValidator validator, Parameters params, String profileURL) {
    final Resource resource = params.getParameterFirstRep().getResource();
    final ValidationOptions valOps = new ValidationOptions();
    final ValidationResult validationResult = validator.validateWithResult(resource, valOps.addProfile(profileURL));
    return validationResult.toOperationOutcome();
}
Also used : Resource(org.hl7.fhir.dstu3.model.Resource) ValidationOptions(ca.uhn.fhir.validation.ValidationOptions) ValidationResult(ca.uhn.fhir.validation.ValidationResult)

Example 22 with ValidationOptions

use of org.hl7.fhir.utilities.validation.ValidationOptions in project dpc-app by CMSgov.

the class FHIRValidatorProvider method initialize.

/**
 * Helper method that primes the Validator cache by creating a dummy patient and validating it.
 * This is really dumb, but it avoids issues where the tests timeout when running in CI.
 * Is necessary in order to address DPC-608
 * <p>
 * We may need to add more resources here in the future, if things continue to be slow.
 *
 * @param validator - {@link FhirValidator} validator to prime
 */
private static void initialize(FhirValidator validator) {
    logger.trace("Validating dummy patient");
    final Patient patient = new Patient();
    patient.addName().addGiven("Dummy").setFamily("Patient");
    patient.addIdentifier().setSystem(DPCIdentifierSystem.MBI.getSystem()).setValue("test-mbi");
    patient.setGender(Enumerations.AdministrativeGender.MALE);
    patient.setBirthDate(Date.valueOf("1990-01-01"));
    final ValidationOptions op = new ValidationOptions();
    op.addProfile(PatientProfile.PROFILE_URI);
    validator.validateWithResult(patient, op);
}
Also used : Patient(org.hl7.fhir.dstu3.model.Patient) ValidationOptions(ca.uhn.fhir.validation.ValidationOptions)

Example 23 with ValidationOptions

use of org.hl7.fhir.utilities.validation.ValidationOptions in project org.hl7.fhir.core by hapifhir.

the class BaseWorkerContext method validateCode.

@Override
public ValidationResult validateCode(ValidationOptions options, CodeableConcept code, ValueSet vs) {
    CacheToken cacheToken = txCache.generateValidationToken(options, code, vs);
    ValidationResult res = txCache.getValidation(cacheToken);
    if (res != null)
        return res;
    // ok, first we try to validate locally
    try {
        ValueSetCheckerSimple vsc = new ValueSetCheckerSimple(options, vs, this);
        res = vsc.validateCode(code);
        txCache.cacheValidation(cacheToken, res, TerminologyCache.TRANSIENT);
        return res;
    } catch (Exception e) {
    }
    // if that failed, we try to validate on the server
    if (noTerminologyServer)
        return new ValidationResult(IssueSeverity.ERROR, "Error validating code: running without terminology services", TerminologyServiceErrorClass.NOSERVICE);
    tlog("$validate " + txCache.summary(code) + " for " + txCache.summary(vs));
    try {
        Parameters pIn = new Parameters();
        pIn.addParameter().setName("codeableConcept").setValue(code);
        if (options != null)
            setTerminologyOptions(options, pIn);
        res = validateOnServer(vs, pIn);
    } catch (Exception e) {
        res = new ValidationResult(IssueSeverity.ERROR, e.getMessage() == null ? e.getClass().getName() : e.getMessage()).setTxLink(txLog.getLastId());
    }
    txCache.cacheValidation(cacheToken, res, TerminologyCache.PERMANENT);
    return res;
}
Also used : CacheToken(org.hl7.fhir.r4.context.TerminologyCache.CacheToken) ValueSetCheckerSimple(org.hl7.fhir.r4.terminologies.ValueSetCheckerSimple) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException) TerminologyServiceException(org.hl7.fhir.exceptions.TerminologyServiceException) FileNotFoundException(java.io.FileNotFoundException) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 24 with ValidationOptions

use of org.hl7.fhir.utilities.validation.ValidationOptions in project org.hl7.fhir.core by hapifhir.

the class SimpleWorkerContextTests method testValidateCodingWithValueSetChecker.

@Test
public void testValidateCodingWithValueSetChecker() throws IOException {
    ValidationOptions validationOptions = new ValidationOptions().guessSystem().setVersionFlexible(false);
    ValueSet valueSet = new ValueSet();
    Coding coding = new Coding();
    Mockito.doReturn(cacheToken).when(terminologyCache).generateValidationToken(validationOptions, coding, valueSet);
    Mockito.doReturn(valueSetCheckerSimple).when(context).constructValueSetCheckerSimple(any(), any(), any());
    Mockito.doReturn(expectedValidationResult).when(valueSetCheckerSimple).validateCode(any(Coding.class));
    ValidationContextCarrier ctxt = mock(ValidationContextCarrier.class);
    IWorkerContext.ValidationResult actualValidationResult = context.validateCode(validationOptions, coding, valueSet, ctxt);
    assertEquals(expectedValidationResult, actualValidationResult);
    Mockito.verify(valueSetCheckerSimple).validateCode(coding);
    Mockito.verify(terminologyCache).getValidation(cacheToken);
    Mockito.verify(terminologyCache).cacheValidation(cacheToken, expectedValidationResult, false);
}
Also used : Coding(org.hl7.fhir.r5.model.Coding) ValidationContextCarrier(org.hl7.fhir.r5.utils.validation.ValidationContextCarrier) ValidationOptions(org.hl7.fhir.utilities.validation.ValidationOptions) ValueSet(org.hl7.fhir.r5.model.ValueSet) Test(org.junit.jupiter.api.Test)

Example 25 with ValidationOptions

use of org.hl7.fhir.utilities.validation.ValidationOptions in project org.hl7.fhir.core by hapifhir.

the class InstanceValidator method checkPrimitiveBinding.

private void checkPrimitiveBinding(ValidatorHostContext hostContext, List<ValidationMessage> errors, String path, String type, ElementDefinition elementContext, Element element, StructureDefinition profile, NodeStack stack) {
    // We ignore bindings that aren't on string, uri or code
    if (!element.hasPrimitiveValue() || !("code".equals(type) || "string".equals(type) || "uri".equals(type) || "url".equals(type) || "canonical".equals(type))) {
        return;
    }
    if (noTerminologyChecks)
        return;
    String value = element.primitiveValue();
    // System.out.println("check "+value+" in "+path);
    // firstly, resolve the value set
    ElementDefinitionBindingComponent binding = elementContext.getBinding();
    if (binding.hasValueSet()) {
        ValueSet vs = resolveBindingReference(profile, binding.getValueSet(), profile.getUrl());
        if (vs == null) {
            CodeSystem cs = context.fetchCodeSystem(binding.getValueSet());
            if (rule(errors, IssueType.CODEINVALID, element.line(), element.col(), path, cs == null, I18nConstants.TERMINOLOGY_TX_VALUESET_NOTFOUND_CS, describeReference(binding.getValueSet()))) {
                warning(errors, IssueType.CODEINVALID, element.line(), element.col(), path, vs != null, I18nConstants.TERMINOLOGY_TX_VALUESET_NOTFOUND, describeReference(binding.getValueSet()));
            }
        } else {
            CodedContentValidationPolicy validationPolicy = getPolicyAdvisor() == null ? CodedContentValidationPolicy.VALUESET : getPolicyAdvisor().policyForCodedContent(this, hostContext, stack.getLiteralPath(), elementContext, profile, BindingKind.PRIMARY, vs, new ArrayList<>());
            if (validationPolicy != CodedContentValidationPolicy.IGNORE) {
                long t = System.nanoTime();
                ValidationResult vr = null;
                if (binding.getStrength() != BindingStrength.EXAMPLE) {
                    ValidationOptions options = baseOptions.setLanguage(stack.getWorkingLang()).guessSystem();
                    if (validationPolicy == CodedContentValidationPolicy.CODE) {
                        options = options.noCheckValueSetMembership();
                    }
                    vr = checkCodeOnServer(stack, vs, value, options);
                }
                timeTracker.tx(t, "vc " + value + "");
                if (binding.getStrength() == BindingStrength.REQUIRED) {
                    removeTrackedMessagesForLocation(errors, element, path);
                }
                if (vr != null && !vr.isOk()) {
                    if (vr.IsNoService())
                        txHint(errors, vr.getTxLink(), IssueType.CODEINVALID, element.line(), element.col(), path, false, I18nConstants.TERMINOLOGY_TX_NOVALID_15, value);
                    else if (binding.getStrength() == BindingStrength.REQUIRED)
                        txRule(errors, vr.getTxLink(), IssueType.CODEINVALID, element.line(), element.col(), path, false, I18nConstants.TERMINOLOGY_TX_NOVALID_16, value, describeValueSet(binding.getValueSet()), getErrorMessage(vr.getMessage()));
                    else if (binding.getStrength() == BindingStrength.EXTENSIBLE) {
                        if (binding.hasExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-maxValueSet"))
                            checkMaxValueSet(errors, path, element, profile, ToolingExtensions.readStringExtension(binding, "http://hl7.org/fhir/StructureDefinition/elementdefinition-maxValueSet"), value, stack);
                        else if (!noExtensibleWarnings && !isOkExtension(value, vs))
                            txWarningForLaterRemoval(element, errors, vr.getTxLink(), IssueType.CODEINVALID, element.line(), element.col(), path, false, I18nConstants.TERMINOLOGY_TX_NOVALID_17, value, describeValueSet(binding.getValueSet()), getErrorMessage(vr.getMessage()));
                    } else if (binding.getStrength() == BindingStrength.PREFERRED) {
                        if (baseOnly) {
                            txHint(errors, vr.getTxLink(), IssueType.CODEINVALID, element.line(), element.col(), path, false, I18nConstants.TERMINOLOGY_TX_NOVALID_18, value, describeValueSet(binding.getValueSet()), getErrorMessage(vr.getMessage()));
                        }
                    }
                }
            }
        }
    } else if (!noBindingMsgSuppressed)
        hint(errors, IssueType.CODEINVALID, element.line(), element.col(), path, !type.equals("code"), I18nConstants.TERMINOLOGY_TX_BINDING_NOSOURCE2);
}
Also used : ArrayList(java.util.ArrayList) ValidationResult(org.hl7.fhir.r5.context.IWorkerContext.ValidationResult) ValidationOptions(org.hl7.fhir.utilities.validation.ValidationOptions) ElementDefinitionBindingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent) ValueSet(org.hl7.fhir.r5.model.ValueSet) CodeSystem(org.hl7.fhir.r5.model.CodeSystem)

Aggregations

IOException (java.io.IOException)15 FHIRException (org.hl7.fhir.exceptions.FHIRException)12 FileNotFoundException (java.io.FileNotFoundException)8 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)8 TerminologyServiceException (org.hl7.fhir.exceptions.TerminologyServiceException)8 Parameters (org.hl7.fhir.r5.model.Parameters)7 ValueSet (org.hl7.fhir.r5.model.ValueSet)7 ValidationOptions (org.hl7.fhir.utilities.validation.ValidationOptions)7 NoTerminologyServiceException (org.hl7.fhir.exceptions.NoTerminologyServiceException)6 Test (org.junit.jupiter.api.Test)6 Coding (org.hl7.fhir.r5.model.Coding)5 ValidationOptions (ca.uhn.fhir.validation.ValidationOptions)4 Parameters (org.hl7.fhir.r4b.model.Parameters)4 ValidationContextCarrier (org.hl7.fhir.r5.utils.validation.ValidationContextCarrier)4 ValidationResult (ca.uhn.fhir.validation.ValidationResult)3 ValueSetCheckerSimple (org.hl7.fhir.r4b.terminologies.ValueSetCheckerSimple)3 OrganizationFactory.generateFakeOrganization (gov.cms.dpc.testing.factories.OrganizationFactory.generateFakeOrganization)2 HashSet (java.util.HashSet)2 Organization (org.hl7.fhir.dstu3.model.Organization)2 CacheToken (org.hl7.fhir.r4.context.TerminologyCache.CacheToken)2