Search in sources :

Example 46 with Rule

use of org.hl7.fhir.utilities.xml.SchematronWriter.Rule in project org.hl7.fhir.core by hapifhir.

the class StructureMapUtilitiesTest method testParseRuleName.

@Test
public void testParseRuleName() throws IOException, FHIRException {
    StructureMapUtilities scu = new StructureMapUtilities(context, this);
    String fileMap = TestingUtilities.loadTestResource("r5", "structure-mapping", "ActivityDefinition.map");
    StructureMap structureMap = scu.parse(fileMap, "ActivityDefinition3To4");
    // StructureMap/ActivityDefinition3to4: StructureMap.group[3].rule[2].name error id value '"expression"' is not valid
    Assertions.assertEquals("expression", structureMap.getGroup().get(2).getRule().get(1).getName());
}
Also used : StructureMap(org.hl7.fhir.r4b.model.StructureMap) StructureMapUtilities(org.hl7.fhir.r4b.utils.structuremap.StructureMapUtilities) Test(org.junit.jupiter.api.Test)

Example 47 with Rule

use of org.hl7.fhir.utilities.xml.SchematronWriter.Rule in project org.hl7.fhir.core by hapifhir.

the class MappingSheetParser method getStructureMap.

public StructureMap getStructureMap() throws FHIRException {
    StructureMap map = new StructureMap();
    loadMetadata(map);
    if (metadata.containsKey("copyright"))
        map.setCopyright(metadata.get("copyright"));
    StructureMapGroupComponent grp = map.addGroup();
    for (MappingRow row : rows) {
        StructureMapGroupRuleComponent rule = grp.addRule();
        rule.setName(row.getSequence());
        StructureMapGroupRuleSourceComponent src = rule.getSourceFirstRep();
        src.setContext("src");
        src.setElement(row.getIdentifier());
        src.setMin(row.getCardinalityMin());
        src.setMax(row.getCardinalityMax());
        src.setType(row.getDataType());
        src.addExtension(ToolingExtensions.EXT_MAPPING_NAME, new StringType(row.getName()));
        if (row.getCondition() != null) {
            src.setCheck(processCondition(row.getCondition()));
        }
        StructureMapGroupRuleTargetComponent tgt = rule.getTargetFirstRep();
        tgt.setContext("tgt");
        tgt.setElement(row.getAttribute());
        tgt.addExtension(ToolingExtensions.EXT_MAPPING_TGTTYPE, new StringType(row.getType()));
        tgt.addExtension(ToolingExtensions.EXT_MAPPING_TGTCARD, new StringType(row.getMinMax()));
        if (row.getDtMapping() != null) {
            src.setVariable("s");
            tgt.setVariable("t");
            tgt.setTransform(StructureMapTransform.CREATE);
            StructureMapGroupRuleDependentComponent dep = rule.addDependent();
            dep.setName(row.getDtMapping());
            dep.addParameter().setValue(new IdType("s"));
            dep.addParameter().setValue(new IdType("t"));
        } else if (row.getVocabMapping() != null) {
            tgt.setTransform(StructureMapTransform.TRANSLATE);
            tgt.addParameter().setValue(new StringType(row.getVocabMapping()));
            tgt.addParameter().setValue(new IdType("src"));
        } else {
            tgt.setTransform(StructureMapTransform.COPY);
        }
        rule.setDocumentation(row.getComments());
        if (row.getDerived() != null) {
            tgt = rule.addTarget();
            tgt.setContext("tgt");
            tgt.setElement(row.getDerived());
            tgt.setTransform(StructureMapTransform.COPY);
            tgt.addParameter().setValue(new StringType(row.getDerivedMapping()));
        }
    }
    return map;
}
Also used : StructureMap(org.hl7.fhir.r5.model.StructureMap) StructureMapGroupComponent(org.hl7.fhir.r5.model.StructureMap.StructureMapGroupComponent) StringType(org.hl7.fhir.r5.model.StringType) StructureMapGroupRuleDependentComponent(org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleDependentComponent) StructureMapGroupRuleComponent(org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleComponent) StructureMapGroupRuleSourceComponent(org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleSourceComponent) StructureMapGroupRuleTargetComponent(org.hl7.fhir.r5.model.StructureMap.StructureMapGroupRuleTargetComponent) IdType(org.hl7.fhir.r5.model.IdType)

Example 48 with Rule

use of org.hl7.fhir.utilities.xml.SchematronWriter.Rule in project org.hl7.fhir.core by hapifhir.

the class InstanceValidator method checkAddress.

private void checkAddress(List<ValidationMessage> errors, String path, Element focus, Address fixed, String fixedSource, boolean pattern) {
    checkFixedValue(errors, path + ".use", focus.getNamedChild("use"), fixed.getUseElement(), fixedSource, "use", focus, pattern);
    checkFixedValue(errors, path + ".text", focus.getNamedChild("text"), fixed.getTextElement(), fixedSource, "text", focus, pattern);
    checkFixedValue(errors, path + ".city", focus.getNamedChild("city"), fixed.getCityElement(), fixedSource, "city", focus, pattern);
    checkFixedValue(errors, path + ".state", focus.getNamedChild("state"), fixed.getStateElement(), fixedSource, "state", focus, pattern);
    checkFixedValue(errors, path + ".country", focus.getNamedChild("country"), fixed.getCountryElement(), fixedSource, "country", focus, pattern);
    checkFixedValue(errors, path + ".zip", focus.getNamedChild("zip"), fixed.getPostalCodeElement(), fixedSource, "postalCode", focus, pattern);
    List<Element> lines = new ArrayList<Element>();
    focus.getNamedChildren("line", lines);
    boolean lineSizeCheck;
    if (pattern) {
        lineSizeCheck = lines.size() >= fixed.getLine().size();
        if (rule(errors, IssueType.VALUE, focus.line(), focus.col(), path, lineSizeCheck, I18nConstants.FIXED_TYPE_CHECKS_DT_ADDRESS_LINE, Integer.toString(fixed.getLine().size()), Integer.toString(lines.size()))) {
            for (int i = 0; i < fixed.getLine().size(); i++) {
                StringType fixedLine = fixed.getLine().get(i);
                boolean found = false;
                List<ValidationMessage> allErrorsFixed = new ArrayList<>();
                List<ValidationMessage> errorsFixed = null;
                for (int j = 0; j < lines.size() && !found; ++j) {
                    errorsFixed = new ArrayList<>();
                    checkFixedValue(errorsFixed, path + ".line", lines.get(j), fixedLine, fixedSource, "line", focus, pattern);
                    if (!hasErrors(errorsFixed)) {
                        found = true;
                    } else {
                        errorsFixed.stream().filter(t -> t.getLevel().ordinal() >= IssueSeverity.ERROR.ordinal()).forEach(t -> allErrorsFixed.add(t));
                    }
                }
                if (!found) {
                    rule(errorsFixed, IssueType.VALUE, focus.line(), focus.col(), path, false, I18nConstants.PATTERN_CHECK_STRING, fixedLine.getValue(), fixedSource, allErrorsFixed);
                }
            }
        }
    } else if (!pattern) {
        lineSizeCheck = lines.size() == fixed.getLine().size();
        if (rule(errors, IssueType.VALUE, focus.line(), focus.col(), path, lineSizeCheck, I18nConstants.FIXED_TYPE_CHECKS_DT_ADDRESS_LINE, Integer.toString(fixed.getLine().size()), Integer.toString(lines.size()))) {
            for (int i = 0; i < lines.size(); i++) {
                checkFixedValue(errors, path + ".line", lines.get(i), fixed.getLine().get(i), fixedSource, "line", focus, pattern);
            }
        }
    }
}
Also used : TypedElementDefinition(org.hl7.fhir.r5.utils.FHIRPathEngine.TypedElementDefinition) XmlParser(org.hl7.fhir.r5.elementmodel.XmlParser) IntegerType(org.hl7.fhir.r5.model.IntegerType) VersionUtilities(org.hl7.fhir.utilities.VersionUtilities) ExtensionContextType(org.hl7.fhir.r5.model.StructureDefinition.ExtensionContextType) TimeType(org.hl7.fhir.r5.model.TimeType) TerminologyServiceErrorClass(org.hl7.fhir.r5.terminologies.ValueSetExpander.TerminologyServiceErrorClass) XhtmlNode(org.hl7.fhir.utilities.xhtml.XhtmlNode) CanonicalResource(org.hl7.fhir.r5.model.CanonicalResource) ConstraintSeverity(org.hl7.fhir.r5.model.ElementDefinition.ConstraintSeverity) StringUtils(org.apache.commons.lang3.StringUtils) SearchParameterValidator(org.hl7.fhir.validation.instance.type.SearchParameterValidator) BigDecimal(java.math.BigDecimal) Document(org.w3c.dom.Document) Map(java.util.Map) DateTimeType(org.hl7.fhir.r5.model.DateTimeType) JsonParser(org.hl7.fhir.r5.elementmodel.JsonParser) ImplementationGuide(org.hl7.fhir.r5.model.ImplementationGuide) Resource(org.hl7.fhir.r5.model.Resource) Source(org.hl7.fhir.utilities.validation.ValidationMessage.Source) ObjectConverter(org.hl7.fhir.r5.elementmodel.ObjectConverter) ConceptDefinitionComponent(org.hl7.fhir.r5.model.CodeSystem.ConceptDefinitionComponent) FormatUtilities(org.hl7.fhir.r5.formats.FormatUtilities) VersionURLInfo(org.hl7.fhir.utilities.VersionUtilities.VersionURLInfo) XVerExtensionManager(org.hl7.fhir.r5.utils.XVerExtensionManager) IssueSeverity(org.hl7.fhir.utilities.validation.ValidationMessage.IssueSeverity) Timing(org.hl7.fhir.r5.model.Timing) ValidatorHostContext(org.hl7.fhir.validation.instance.utils.ValidatorHostContext) ContactPoint(org.hl7.fhir.r5.model.ContactPoint) Set(java.util.Set) CommaSeparatedStringBuilder(org.hl7.fhir.utilities.CommaSeparatedStringBuilder) TerminologyServiceException(org.hl7.fhir.exceptions.TerminologyServiceException) ResourceValidationTracker(org.hl7.fhir.validation.instance.utils.ResourceValidationTracker) StandardCharsets(java.nio.charset.StandardCharsets) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) PropertyRepresentation(org.hl7.fhir.r5.model.ElementDefinition.PropertyRepresentation) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) Coding(org.hl7.fhir.r5.model.Coding) Utilities(org.hl7.fhir.utilities.Utilities) BooleanType(org.hl7.fhir.r5.model.BooleanType) ParserBase(org.hl7.fhir.r5.elementmodel.ParserBase) NamedElement(org.hl7.fhir.r5.elementmodel.ParserBase.NamedElement) ElementDefinitionSlicingDiscriminatorComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingDiscriminatorComponent) ElementDefinitionConstraintComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent) BindingStrength(org.hl7.fhir.r5.model.Enumerations.BindingStrength) StructureDefinitionContextComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionContextComponent) BaseValidator(org.hl7.fhir.validation.BaseValidator) BundleValidator(org.hl7.fhir.validation.instance.type.BundleValidator) ArrayList(java.util.ArrayList) ValidationPolicy(org.hl7.fhir.r5.elementmodel.ParserBase.ValidationPolicy) QuestionnaireValidator(org.hl7.fhir.validation.instance.type.QuestionnaireValidator) Calendar(java.util.Calendar) ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) Decimal(org.fhir.ucum.Decimal) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) ValidationLevel(org.hl7.fhir.validation.cli.utils.ValidationLevel) DataType(org.hl7.fhir.r5.model.DataType) IOException(java.io.IOException) InstantType(org.hl7.fhir.r5.model.InstantType) File(java.io.File) Base(org.hl7.fhir.r5.model.Base) Manager(org.hl7.fhir.r5.elementmodel.Manager) ElementInfo(org.hl7.fhir.validation.instance.utils.ElementInfo) CodeableConcept(org.hl7.fhir.r5.model.CodeableConcept) FHIRException(org.hl7.fhir.exceptions.FHIRException) ExpressionNode(org.hl7.fhir.r5.model.ExpressionNode) TypeDetails(org.hl7.fhir.r5.model.TypeDetails) JsonObject(com.google.gson.JsonObject) NodeType(org.hl7.fhir.utilities.xhtml.NodeType) IndexedElement(org.hl7.fhir.validation.instance.utils.IndexedElement) FHIRPathEngine(org.hl7.fhir.r5.utils.FHIRPathEngine) StructureDefinitionKind(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionKind) SampledData(org.hl7.fhir.r5.model.SampledData) Range(org.hl7.fhir.r5.model.Range) QuestionnaireMode(org.hl7.fhir.validation.cli.utils.QuestionnaireMode) I18nConstants(org.hl7.fhir.utilities.i18n.I18nConstants) ByteArrayInputStream(java.io.ByteArrayInputStream) StructureDefinitionMappingComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionMappingComponent) Gson(com.google.gson.Gson) CanonicalType(org.hl7.fhir.r5.model.CanonicalType) Identifier(org.hl7.fhir.r5.model.Identifier) AggregationMode(org.hl7.fhir.r5.model.ElementDefinition.AggregationMode) Period(org.hl7.fhir.r5.model.Period) ToolingExtensions(org.hl7.fhir.r5.utils.ToolingExtensions) Collection(java.util.Collection) Reference(org.hl7.fhir.r5.model.Reference) StructureDefinitionSnapshotComponent(org.hl7.fhir.r5.model.StructureDefinition.StructureDefinitionSnapshotComponent) UUID(java.util.UUID) Quantity(org.hl7.fhir.r5.model.Quantity) PrimitiveType(org.hl7.fhir.r5.model.PrimitiveType) ChildIterator(org.hl7.fhir.validation.instance.utils.ChildIterator) List(java.util.List) ValueSetExpansionContainsComponent(org.hl7.fhir.r5.model.ValueSet.ValueSetExpansionContainsComponent) CodeSystem(org.hl7.fhir.r5.model.CodeSystem) DateType(org.hl7.fhir.r5.model.DateType) ElementDefinitionBindingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent) Enumeration(org.hl7.fhir.r5.model.Enumeration) Base64InputStream(org.apache.commons.codec.binary.Base64InputStream) DecimalStatus(org.hl7.fhir.utilities.Utilities.DecimalStatus) ValidationResult(org.hl7.fhir.r5.context.IWorkerContext.ValidationResult) ImplementationGuideGlobalComponent(org.hl7.fhir.r5.model.ImplementationGuide.ImplementationGuideGlobalComponent) ResolvedReference(org.hl7.fhir.validation.instance.utils.ResolvedReference) NotImplementedException(org.apache.commons.lang3.NotImplementedException) org.hl7.fhir.r5.utils.validation.constants(org.hl7.fhir.r5.utils.validation.constants) ElementDefinitionMappingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent) ElementDefinitionSlicingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionSlicingComponent) ValueSet(org.hl7.fhir.r5.model.ValueSet) ProfileUtilities(org.hl7.fhir.r5.conformance.ProfileUtilities) HashMap(java.util.HashMap) TypeDerivationRule(org.hl7.fhir.r5.model.StructureDefinition.TypeDerivationRule) NodeStack(org.hl7.fhir.validation.instance.utils.NodeStack) DataRenderer(org.hl7.fhir.r5.renderers.DataRenderer) CodeSystemValidator(org.hl7.fhir.validation.instance.type.CodeSystemValidator) HashSet(java.util.HashSet) UriType(org.hl7.fhir.r5.model.UriType) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) StructureDefinitionValidator(org.hl7.fhir.validation.instance.type.StructureDefinitionValidator) BuildExtensions(org.hl7.fhir.r5.utils.BuildExtensions) SearchParameter(org.hl7.fhir.r5.model.SearchParameter) ValidationOptions(org.hl7.fhir.utilities.validation.ValidationOptions) DiscriminatorType(org.hl7.fhir.r5.model.ElementDefinition.DiscriminatorType) MeasureValidator(org.hl7.fhir.validation.instance.type.MeasureValidator) PathEngineException(org.hl7.fhir.exceptions.PathEngineException) Ratio(org.hl7.fhir.r5.model.Ratio) IssueType(org.hl7.fhir.utilities.validation.ValidationMessage.IssueType) Attachment(org.hl7.fhir.r5.model.Attachment) IWorkerContext(org.hl7.fhir.r5.context.IWorkerContext) SpecialElement(org.hl7.fhir.r5.elementmodel.Element.SpecialElement) StringType(org.hl7.fhir.r5.model.StringType) Address(org.hl7.fhir.r5.model.Address) SIDUtilities(org.hl7.fhir.utilities.SIDUtilities) FhirFormat(org.hl7.fhir.r5.elementmodel.Manager.FhirFormat) Element(org.hl7.fhir.r5.elementmodel.Element) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) Extension(org.hl7.fhir.r5.model.Extension) UnicodeUtilities(org.hl7.fhir.utilities.UnicodeUtilities) org.hl7.fhir.r5.utils.validation(org.hl7.fhir.r5.utils.validation) IEvaluationContext(org.hl7.fhir.r5.utils.FHIRPathEngine.IEvaluationContext) StringUtils.isBlank(org.apache.commons.lang3.StringUtils.isBlank) DecimalType(org.hl7.fhir.r5.model.DecimalType) ValueSetValidator(org.hl7.fhir.validation.instance.type.ValueSetValidator) FHIRLexerException(org.hl7.fhir.r5.utils.FHIRLexer.FHIRLexerException) InputStream(java.io.InputStream) HumanName(org.hl7.fhir.r5.model.HumanName) ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) StringType(org.hl7.fhir.r5.model.StringType) NamedElement(org.hl7.fhir.r5.elementmodel.ParserBase.NamedElement) IndexedElement(org.hl7.fhir.validation.instance.utils.IndexedElement) SpecialElement(org.hl7.fhir.r5.elementmodel.Element.SpecialElement) Element(org.hl7.fhir.r5.elementmodel.Element) ArrayList(java.util.ArrayList) ContactPoint(org.hl7.fhir.r5.model.ContactPoint)

Example 49 with Rule

use of org.hl7.fhir.utilities.xml.SchematronWriter.Rule in project org.hl7.fhir.core by hapifhir.

the class InstanceValidator method startInner.

public void startInner(ValidatorHostContext hostContext, List<ValidationMessage> errors, Element resource, Element element, StructureDefinition defn, NodeStack stack, boolean checkSpecials) {
    // the first piece of business is to see if we've validated this resource against this profile before.
    // if we have (*or if we still are*), then we'll just return our existing errors
    ResourceValidationTracker resTracker = getResourceTracker(element);
    List<ValidationMessage> cachedErrors = resTracker.getOutcomes(defn);
    if (cachedErrors != null) {
        for (ValidationMessage vm : cachedErrors) {
            if (!errors.contains(vm)) {
                errors.add(vm);
            }
        }
        return;
    }
    if (rule(errors, IssueType.STRUCTURE, element.line(), element.col(), stack.getLiteralPath(), defn.hasSnapshot(), I18nConstants.VALIDATION_VAL_PROFILE_NOSNAPSHOT, defn.getUrl())) {
        List<ValidationMessage> localErrors = new ArrayList<ValidationMessage>();
        resTracker.startValidating(defn);
        trackUsage(defn, hostContext, element);
        validateElement(hostContext, localErrors, defn, defn.getSnapshot().getElement().get(0), null, null, resource, element, element.getName(), stack, false, true, null);
        resTracker.storeOutcomes(defn, localErrors);
        for (ValidationMessage vm : localErrors) {
            if (!errors.contains(vm)) {
                errors.add(vm);
            }
        }
    }
    if (checkSpecials) {
        checkSpecials(hostContext, errors, element, stack, checkSpecials);
        validateResourceRules(errors, element, stack);
    }
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) ResourceValidationTracker(org.hl7.fhir.validation.instance.utils.ResourceValidationTracker) ArrayList(java.util.ArrayList)

Example 50 with Rule

use of org.hl7.fhir.utilities.xml.SchematronWriter.Rule in project org.hl7.fhir.core by hapifhir.

the class InstanceValidator method checkChildByDefinition.

public void checkChildByDefinition(ValidatorHostContext hostContext, List<ValidationMessage> errors, StructureDefinition profile, ElementDefinition definition, Element resource, Element element, String actualType, NodeStack stack, boolean inCodeableConcept, boolean checkDisplayInContext, ElementInfo ei, String extensionUrl, ElementDefinition checkDefn, boolean isSlice) {
    List<String> profiles = new ArrayList<String>();
    String type = null;
    ElementDefinition typeDefn = null;
    checkMustSupport(profile, ei);
    if (checkDefn.getType().size() == 1 && !"*".equals(checkDefn.getType().get(0).getWorkingCode()) && !"Element".equals(checkDefn.getType().get(0).getWorkingCode()) && !"BackboneElement".equals(checkDefn.getType().get(0).getWorkingCode())) {
        type = checkDefn.getType().get(0).getWorkingCode();
        String stype = ei.getElement().fhirType();
        if (checkDefn.isChoice() && !stype.equals(type)) {
            if ("Extension".equals(profile.getType())) {
            // error will be raised elsewhere
            } else {
                rule(errors, IssueType.STRUCTURE, element.line(), element.col(), ei.getPath(), false, I18nConstants.EXTENSION_PROF_TYPE, profile.getUrl(), type, stype);
            }
        }
        // Excluding reference is a kludge to get around versioning issues
        if (checkDefn.getType().get(0).hasProfile()) {
            for (CanonicalType p : checkDefn.getType().get(0).getProfile()) {
                profiles.add(p.getValue());
            }
        }
    } else if (checkDefn.getType().size() == 1 && "*".equals(checkDefn.getType().get(0).getWorkingCode())) {
        String prefix = tail(checkDefn.getPath());
        assert prefix.endsWith("[x]");
        type = ei.getName().substring(prefix.length() - 3);
        if (isPrimitiveType(type))
            type = Utilities.uncapitalize(type);
        if (checkDefn.getType().get(0).hasProfile()) {
            for (CanonicalType p : checkDefn.getType().get(0).getProfile()) {
                profiles.add(p.getValue());
            }
        }
    } else if (checkDefn.getType().size() > 1) {
        String prefix = tail(checkDefn.getPath());
        assert typesAreAllReference(checkDefn.getType()) || checkDefn.hasRepresentation(PropertyRepresentation.TYPEATTR) || prefix.endsWith("[x]") || isResourceAndTypes(checkDefn) : "Multiple Types allowed, but name is wrong @ " + checkDefn.getPath() + ": " + checkDefn.typeSummaryVB();
        if (checkDefn.hasRepresentation(PropertyRepresentation.TYPEATTR)) {
            type = ei.getElement().getType();
        } else if (ei.getElement().isResource()) {
            type = ei.getElement().fhirType();
        } else {
            prefix = prefix.substring(0, prefix.length() - 3);
            for (TypeRefComponent t : checkDefn.getType()) if ((prefix + Utilities.capitalize(t.getWorkingCode())).equals(ei.getName())) {
                type = t.getWorkingCode();
                // Excluding reference is a kludge to get around versioning issues
                if (t.hasProfile() && !type.equals("Reference"))
                    profiles.add(t.getProfile().get(0).getValue());
            }
        }
        if (type == null) {
            TypeRefComponent trc = checkDefn.getType().get(0);
            if (trc.getWorkingCode().equals("Reference"))
                type = "Reference";
            else
                rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), stack.getLiteralPath(), false, I18nConstants.VALIDATION_VAL_PROFILE_NOTYPE, ei.getName(), describeTypes(checkDefn.getType()));
        }
    } else if (checkDefn.getContentReference() != null) {
        typeDefn = resolveNameReference(profile.getSnapshot(), checkDefn.getContentReference());
    } else if (checkDefn.getType().size() == 1 && ("Element".equals(checkDefn.getType().get(0).getWorkingCode()) || "BackboneElement".equals(checkDefn.getType().get(0).getWorkingCode()))) {
        if (checkDefn.getType().get(0).hasProfile()) {
            CanonicalType pu = checkDefn.getType().get(0).getProfile().get(0);
            if (pu.hasExtension(ToolingExtensions.EXT_PROFILE_ELEMENT))
                profiles.add(pu.getValue() + "#" + pu.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT));
            else
                profiles.add(pu.getValue());
        }
    }
    if (type != null) {
        if (type.startsWith("@")) {
            checkDefn = findElement(profile, type.substring(1));
            if (isSlice) {
                ei.slice = ei.definition;
            } else {
                ei.definition = ei.definition;
            }
            type = null;
        }
    }
    NodeStack localStack = stack.push(ei.getElement(), "*".equals(ei.getDefinition().getBase().getMax()) && ei.count == -1 ? 0 : ei.count, checkDefn, type == null ? typeDefn : resolveType(type, checkDefn.getType()));
    // if (debug) {
    // System.out.println("  check " + localStack.getLiteralPath()+" against "+ei.getDefinition().getId()+" in profile "+profile.getUrl());
    // }
    String localStackLiteralPath = localStack.getLiteralPath();
    String eiPath = ei.getPath();
    if (!eiPath.equals(localStackLiteralPath)) {
        assert (eiPath.equals(localStackLiteralPath)) : "ei.path: " + ei.getPath() + "  -  localStack.getLiteralPath: " + localStackLiteralPath;
    }
    boolean thisIsCodeableConcept = false;
    String thisExtension = null;
    boolean checkDisplay = true;
    SpecialElement special = ei.getElement().getSpecial();
    if (special == SpecialElement.BUNDLE_ENTRY || special == SpecialElement.BUNDLE_OUTCOME || special == SpecialElement.PARAMETER) {
        checkInvariants(hostContext, errors, profile, typeDefn != null ? typeDefn : checkDefn, ei.getElement(), ei.getElement(), localStack, false);
    } else {
        checkInvariants(hostContext, errors, profile, typeDefn != null ? typeDefn : checkDefn, resource, ei.getElement(), localStack, false);
    }
    ei.getElement().markValidation(profile, checkDefn);
    boolean elementValidated = false;
    if (type != null) {
        if (isPrimitiveType(type)) {
            checkPrimitive(hostContext, errors, ei.getPath(), type, checkDefn, ei.getElement(), profile, stack);
        } else {
            if (checkDefn.hasFixed()) {
                checkFixedValue(errors, ei.getPath(), ei.getElement(), checkDefn.getFixed(), profile.getUrl(), checkDefn.getSliceName(), null, false);
            }
            if (checkDefn.hasPattern()) {
                checkFixedValue(errors, ei.getPath(), ei.getElement(), checkDefn.getPattern(), profile.getUrl(), checkDefn.getSliceName(), null, true);
            }
        }
        if (type.equals("Identifier")) {
            checkIdentifier(errors, ei.getPath(), ei.getElement(), checkDefn);
        } else if (type.equals("Coding")) {
            checkCoding(errors, ei.getPath(), ei.getElement(), profile, checkDefn, inCodeableConcept, checkDisplayInContext, stack);
        } else if (type.equals("Quantity")) {
            checkQuantity(errors, ei.getPath(), ei.getElement(), profile, checkDefn, stack);
        } else if (type.equals("Attachment")) {
            checkAttachment(errors, ei.getPath(), ei.getElement(), profile, checkDefn, inCodeableConcept, checkDisplayInContext, stack);
        } else if (type.equals("CodeableConcept")) {
            checkDisplay = checkCodeableConcept(errors, ei.getPath(), ei.getElement(), profile, checkDefn, stack);
            thisIsCodeableConcept = true;
        } else if (type.equals("Reference")) {
            checkReference(hostContext, errors, ei.getPath(), ei.getElement(), profile, checkDefn, actualType, localStack);
        // We only check extensions if we're not in a complex extension or if the element we're dealing with is not defined as part of that complex extension
        } else if (type.equals("Extension")) {
            Element eurl = ei.getElement().getNamedChild("url");
            if (rule(errors, IssueType.INVALID, ei.getPath(), eurl != null, I18nConstants.EXTENSION_EXT_URL_NOTFOUND)) {
                String url = eurl.primitiveValue();
                thisExtension = url;
                if (rule(errors, IssueType.INVALID, ei.getPath(), !Utilities.noString(url), I18nConstants.EXTENSION_EXT_URL_NOTFOUND)) {
                    if (rule(errors, IssueType.INVALID, ei.getPath(), (extensionUrl != null) || Utilities.isAbsoluteUrl(url), I18nConstants.EXTENSION_EXT_URL_ABSOLUTE)) {
                        checkExtension(hostContext, errors, ei.getPath(), resource, element, ei.getElement(), checkDefn, profile, localStack, stack, extensionUrl);
                    }
                }
            }
        } else if (type.equals("Resource") || isResource(type)) {
            validateContains(hostContext, errors, ei.getPath(), checkDefn, definition, resource, ei.getElement(), localStack, idStatusForEntry(element, ei), // if
            profile);
            elementValidated = true;
        // (str.matches(".*([.,/])work\\1$"))
        } else if (Utilities.isAbsoluteUrl(type)) {
            StructureDefinition defn = context.fetchTypeDefinition(type);
            if (defn != null && hasMapping("http://hl7.org/fhir/terminology-pattern", defn, defn.getSnapshot().getElementFirstRep())) {
                List<String> txtype = getMapping("http://hl7.org/fhir/terminology-pattern", defn, defn.getSnapshot().getElementFirstRep());
                if (txtype.contains("CodeableConcept")) {
                    checkTerminologyCodeableConcept(errors, ei.getPath(), ei.getElement(), profile, checkDefn, stack, defn);
                    thisIsCodeableConcept = true;
                } else if (txtype.contains("Coding")) {
                    checkTerminologyCoding(errors, ei.getPath(), ei.getElement(), profile, checkDefn, inCodeableConcept, checkDisplayInContext, stack, defn);
                }
            }
        }
    } else {
        if (rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), stack.getLiteralPath(), checkDefn != null, I18nConstants.VALIDATION_VAL_CONTENT_UNKNOWN, ei.getName()))
            validateElement(hostContext, errors, profile, checkDefn, null, null, resource, ei.getElement(), type, localStack, false, true, null);
    }
    StructureDefinition p = null;
    String tail = null;
    if (profiles.isEmpty()) {
        if (type != null) {
            p = getProfileForType(type, checkDefn.getType());
            // If dealing with a primitive type, then we need to check the current child against
            // the invariants (constraints) on the current element, because otherwise it only gets
            // checked against the primary type's invariants: LLoyd
            // if (p.getKind() == StructureDefinitionKind.PRIMITIVETYPE) {
            // checkInvariants(hostContext, errors, ei.path, profile, ei.definition, null, null, resource, ei.element);
            // }
            rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.getPath(), p != null, I18nConstants.VALIDATION_VAL_NOTYPE, type);
        }
    } else if (profiles.size() == 1) {
        String url = profiles.get(0);
        if (url.contains("#")) {
            tail = url.substring(url.indexOf("#") + 1);
            url = url.substring(0, url.indexOf("#"));
        }
        p = this.context.fetchResource(StructureDefinition.class, url);
        rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.getPath(), p != null, I18nConstants.VALIDATION_VAL_UNKNOWN_PROFILE, profiles.get(0));
    } else {
        elementValidated = true;
        HashMap<String, List<ValidationMessage>> goodProfiles = new HashMap<String, List<ValidationMessage>>();
        HashMap<String, List<ValidationMessage>> badProfiles = new HashMap<String, List<ValidationMessage>>();
        for (String typeProfile : profiles) {
            String url = typeProfile;
            tail = null;
            if (url.contains("#")) {
                tail = url.substring(url.indexOf("#") + 1);
                url = url.substring(0, url.indexOf("#"));
            }
            p = this.context.fetchResource(StructureDefinition.class, typeProfile);
            if (rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.getPath(), p != null, I18nConstants.VALIDATION_VAL_UNKNOWN_PROFILE, typeProfile)) {
                List<ValidationMessage> profileErrors = new ArrayList<ValidationMessage>();
                validateElement(hostContext, profileErrors, p, getElementByTail(p, tail), profile, checkDefn, resource, ei.getElement(), type, localStack, thisIsCodeableConcept, checkDisplay, thisExtension);
                if (hasErrors(profileErrors))
                    badProfiles.put(typeProfile, profileErrors);
                else
                    goodProfiles.put(typeProfile, profileErrors);
            }
        }
        if (goodProfiles.size() == 1) {
            errors.addAll(goodProfiles.values().iterator().next());
        } else if (goodProfiles.size() == 0) {
            rule(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.getPath(), false, I18nConstants.VALIDATION_VAL_PROFILE_NOMATCH, StringUtils.join("; ", profiles));
            for (String m : badProfiles.keySet()) {
                p = this.context.fetchResource(StructureDefinition.class, m);
                for (ValidationMessage message : badProfiles.get(m)) {
                    message.setMessage(message.getMessage() + " (validating against " + p.getUrl() + (p.hasVersion() ? "|" + p.getVersion() : "") + " [" + p.getName() + "])");
                    errors.add(message);
                }
            }
        } else {
            warning(errors, IssueType.STRUCTURE, ei.line(), ei.col(), ei.getPath(), false, I18nConstants.VALIDATION_VAL_PROFILE_MULTIPLEMATCHES, StringUtils.join("; ", goodProfiles.keySet()));
            for (String m : goodProfiles.keySet()) {
                p = this.context.fetchResource(StructureDefinition.class, m);
                for (ValidationMessage message : goodProfiles.get(m)) {
                    message.setMessage(message.getMessage() + " (validating against " + p.getUrl() + (p.hasVersion() ? "|" + p.getVersion() : "") + " [" + p.getName() + "])");
                    errors.add(message);
                }
            }
        }
    }
    if (p != null) {
        trackUsage(p, hostContext, element);
        if (!elementValidated) {
            if (ei.getElement().getSpecial() == SpecialElement.BUNDLE_ENTRY || ei.getElement().getSpecial() == SpecialElement.BUNDLE_OUTCOME || ei.getElement().getSpecial() == SpecialElement.PARAMETER)
                validateElement(hostContext, errors, p, getElementByTail(p, tail), profile, checkDefn, ei.getElement(), ei.getElement(), type, localStack.resetIds(), thisIsCodeableConcept, checkDisplay, thisExtension);
            else
                validateElement(hostContext, errors, p, getElementByTail(p, tail), profile, checkDefn, resource, ei.getElement(), type, localStack, thisIsCodeableConcept, checkDisplay, thisExtension);
        }
        int index = profile.getSnapshot().getElement().indexOf(checkDefn);
        if (index < profile.getSnapshot().getElement().size() - 1) {
            String nextPath = profile.getSnapshot().getElement().get(index + 1).getPath();
            if (!nextPath.equals(checkDefn.getPath()) && nextPath.startsWith(checkDefn.getPath()))
                validateElement(hostContext, errors, profile, checkDefn, null, null, resource, ei.getElement(), type, localStack, thisIsCodeableConcept, checkDisplay, thisExtension);
        }
    }
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) HashMap(java.util.HashMap) NamedElement(org.hl7.fhir.r5.elementmodel.ParserBase.NamedElement) IndexedElement(org.hl7.fhir.validation.instance.utils.IndexedElement) SpecialElement(org.hl7.fhir.r5.elementmodel.Element.SpecialElement) Element(org.hl7.fhir.r5.elementmodel.Element) ArrayList(java.util.ArrayList) SpecialElement(org.hl7.fhir.r5.elementmodel.Element.SpecialElement) NodeStack(org.hl7.fhir.validation.instance.utils.NodeStack) CanonicalType(org.hl7.fhir.r5.model.CanonicalType) ContactPoint(org.hl7.fhir.r5.model.ContactPoint) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) ArrayList(java.util.ArrayList) List(java.util.List) TypedElementDefinition(org.hl7.fhir.r5.utils.FHIRPathEngine.TypedElementDefinition) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition)

Aggregations

FHIRException (org.hl7.fhir.exceptions.FHIRException)76 ArrayList (java.util.ArrayList)46 Element (org.hl7.fhir.r5.elementmodel.Element)38 IOException (java.io.IOException)28 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)26 NodeStack (org.hl7.fhir.validation.instance.utils.NodeStack)23 PathEngineException (org.hl7.fhir.exceptions.PathEngineException)20 StructureDefinition (org.hl7.fhir.r5.model.StructureDefinition)20 ValidationMessage (org.hl7.fhir.utilities.validation.ValidationMessage)19 IndexedElement (org.hl7.fhir.validation.instance.utils.IndexedElement)17 NotImplementedException (org.apache.commons.lang3.NotImplementedException)16 FHIRFormatError (org.hl7.fhir.exceptions.FHIRFormatError)14 FHIRLexerException (org.hl7.fhir.r5.utils.FHIRLexer.FHIRLexerException)14 Complex (org.hl7.fhir.dstu3.utils.formats.Turtle.Complex)13 TerminologyServiceException (org.hl7.fhir.exceptions.TerminologyServiceException)13 NamedElement (org.hl7.fhir.r5.elementmodel.ParserBase.NamedElement)13 ContactPoint (org.hl7.fhir.r5.model.ContactPoint)13 ValueSet (org.hl7.fhir.r5.model.ValueSet)13 XhtmlNode (org.hl7.fhir.utilities.xhtml.XhtmlNode)13 SpecialElement (org.hl7.fhir.r5.elementmodel.Element.SpecialElement)12