Search in sources :

Example 81 with ValueSetExpansionOutcome

use of org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome in project org.hl7.fhir.core by hapifhir.

the class ProfileComparer method compareBindings.

private boolean compareBindings(ProfileComparison outcome, ElementDefinition subset, ElementDefinition superset, String path, ElementDefinition lDef, ElementDefinition rDef) {
    assert (lDef.hasBinding() || rDef.hasBinding());
    if (!lDef.hasBinding()) {
        subset.setBinding(rDef.getBinding());
        // technically, the super set is unbound, but that's not very useful - so we use the provided on as an example
        superset.setBinding(rDef.getBinding().copy());
        superset.getBinding().setStrength(BindingStrength.EXAMPLE);
        return true;
    }
    if (!rDef.hasBinding()) {
        subset.setBinding(lDef.getBinding());
        superset.setBinding(lDef.getBinding().copy());
        superset.getBinding().setStrength(BindingStrength.EXAMPLE);
        return true;
    }
    ElementDefinitionBindingComponent left = lDef.getBinding();
    ElementDefinitionBindingComponent right = rDef.getBinding();
    if (Base.compareDeep(left, right, false)) {
        subset.setBinding(left);
        superset.setBinding(right);
    }
    // superset:
    if (isPreferredOrExample(left) && isPreferredOrExample(right)) {
        if (right.getStrength() == BindingStrength.PREFERRED && left.getStrength() == BindingStrength.EXAMPLE && !Base.compareDeep(left.getValueSet(), right.getValueSet(), false)) {
            outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "Example/preferred bindings differ at " + path + " using binding from " + outcome.rightName(), IssueSeverity.INFORMATION));
            status(subset, ProfileUtilities.STATUS_HINT);
            subset.setBinding(right);
            superset.setBinding(unionBindings(superset, outcome, path, left, right));
        } else {
            if ((right.getStrength() != BindingStrength.EXAMPLE || left.getStrength() != BindingStrength.EXAMPLE) && !Base.compareDeep(left.getValueSet(), right.getValueSet(), false)) {
                outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "Example/preferred bindings differ at " + path + " using binding from " + outcome.leftName(), IssueSeverity.INFORMATION));
                status(subset, ProfileUtilities.STATUS_HINT);
            }
            subset.setBinding(left);
            superset.setBinding(unionBindings(superset, outcome, path, left, right));
        }
        return true;
    }
    // if either of them are extensible/required, then it wins
    if (isPreferredOrExample(left)) {
        subset.setBinding(right);
        superset.setBinding(unionBindings(superset, outcome, path, left, right));
        return true;
    }
    if (isPreferredOrExample(right)) {
        subset.setBinding(left);
        superset.setBinding(unionBindings(superset, outcome, path, left, right));
        return true;
    }
    // ok, both are extensible or required.
    ElementDefinitionBindingComponent subBinding = new ElementDefinitionBindingComponent();
    subset.setBinding(subBinding);
    ElementDefinitionBindingComponent superBinding = new ElementDefinitionBindingComponent();
    superset.setBinding(superBinding);
    subBinding.setDescription(mergeText(subset, outcome, path, "description", left.getDescription(), right.getDescription()));
    superBinding.setDescription(mergeText(subset, outcome, null, "description", left.getDescription(), right.getDescription()));
    if (left.getStrength() == BindingStrength.REQUIRED || right.getStrength() == BindingStrength.REQUIRED)
        subBinding.setStrength(BindingStrength.REQUIRED);
    else
        subBinding.setStrength(BindingStrength.EXTENSIBLE);
    if (left.getStrength() == BindingStrength.EXTENSIBLE || right.getStrength() == BindingStrength.EXTENSIBLE)
        superBinding.setStrength(BindingStrength.EXTENSIBLE);
    else
        superBinding.setStrength(BindingStrength.REQUIRED);
    if (Base.compareDeep(left.getValueSet(), right.getValueSet(), false)) {
        subBinding.setValueSet(left.getValueSet());
        superBinding.setValueSet(left.getValueSet());
        return true;
    } else if (!left.hasValueSet()) {
        outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "No left Value set at " + path, IssueSeverity.ERROR));
        return true;
    } else if (!right.hasValueSet()) {
        outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "No right Value set at " + path, IssueSeverity.ERROR));
        return true;
    } else {
        // ok, now we compare the value sets. This may be unresolvable.
        ValueSet lvs = resolveVS(outcome.left, left.getValueSet());
        ValueSet rvs = resolveVS(outcome.right, right.getValueSet());
        if (lvs == null) {
            outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "Unable to resolve left value set " + left.getValueSet().toString() + " at " + path, IssueSeverity.ERROR));
            return true;
        } else if (rvs == null) {
            outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "Unable to resolve right value set " + right.getValueSet().toString() + " at " + path, IssueSeverity.ERROR));
            return true;
        } else {
            // first, we'll try to do it by definition
            ValueSet cvs = intersectByDefinition(lvs, rvs);
            if (cvs == null) {
                // if that didn't work, we'll do it by expansion
                ValueSetExpansionOutcome le;
                ValueSetExpansionOutcome re;
                try {
                    le = context.expandVS(lvs, true);
                    re = context.expandVS(rvs, true);
                    if (!closed(le.getValueset()) || !closed(re.getValueset()))
                        throw new DefinitionException("unclosed value sets are not handled yet");
                    cvs = intersectByExpansion(lvs, rvs);
                    if (!cvs.getCompose().hasInclude()) {
                        outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "The value sets " + lvs.getUrl() + " and " + rvs.getUrl() + " do not intersect", IssueSeverity.ERROR));
                        status(subset, ProfileUtilities.STATUS_ERROR);
                        return false;
                    }
                } catch (Exception e) {
                    outcome.messages.add(new ValidationMessage(Source.ProfileComparer, IssueType.STRUCTURE, path, "Unable to expand or process value sets " + lvs.getUrl() + " and " + rvs.getUrl() + ": " + e.getMessage(), IssueSeverity.ERROR));
                    status(subset, ProfileUtilities.STATUS_ERROR);
                    return false;
                }
            }
            subBinding.setValueSet(new Reference().setReference("#" + addValueSet(cvs)));
            superBinding.setValueSet(new Reference().setReference("#" + addValueSet(unite(superset, outcome, path, lvs, rvs))));
        }
    }
    return false;
}
Also used : ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) Reference(org.hl7.fhir.dstu2.model.Reference) ValueSetExpansionOutcome(org.hl7.fhir.dstu2.terminologies.ValueSetExpander.ValueSetExpansionOutcome) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) ElementDefinitionBindingComponent(org.hl7.fhir.dstu2.model.ElementDefinition.ElementDefinitionBindingComponent) ValueSet(org.hl7.fhir.dstu2.model.ValueSet) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException)

Example 82 with ValueSetExpansionOutcome

use of org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome in project org.hl7.fhir.core by hapifhir.

the class NarrativeGenerator method countMembership.

private Integer countMembership(ValueSet vs) {
    int count = 0;
    if (vs.hasExpansion())
        count = count + conceptCount(vs.getExpansion().getContains());
    else {
        if (vs.hasCompose()) {
            if (vs.getCompose().hasExclude()) {
                try {
                    ValueSetExpansionOutcome vse = context.expandVS(vs, true);
                    count = 0;
                    count += conceptCount(vse.getValueset().getExpansion().getContains());
                    return count;
                } catch (Exception e) {
                    return null;
                }
            }
            for (ConceptSetComponent inc : vs.getCompose().getInclude()) {
                if (inc.hasFilter())
                    return null;
                if (!inc.hasConcept())
                    return null;
                count = count + inc.getConcept().size();
            }
        }
    }
    return count;
}
Also used : ConceptSetComponent(org.hl7.fhir.dstu2016may.model.ValueSet.ConceptSetComponent) ValueSetExpansionOutcome(org.hl7.fhir.dstu2016may.terminologies.ValueSetExpander.ValueSetExpansionOutcome) ContactPoint(org.hl7.fhir.dstu2016may.model.ContactPoint) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) NotImplementedException(org.apache.commons.lang3.NotImplementedException)

Example 83 with ValueSetExpansionOutcome

use of org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome in project org.hl7.fhir.core by hapifhir.

the class ProfileUtilities method updateFromDefinition.

private void updateFromDefinition(ElementDefinition dest, ElementDefinition source, String pn, boolean trimDifferential, String purl, StructureDefinition srcSD) throws DefinitionException, FHIRException {
    source.setUserData(GENERATED_IN_SNAPSHOT, dest);
    // we start with a clone of the base profile ('dest') and we copy from the profile ('source')
    // over the top for anything the source has
    ElementDefinition base = dest;
    ElementDefinition derived = source;
    derived.setUserData(DERIVATION_POINTER, base);
    boolean isExtension = checkExtensionDoco(base);
    // Before applying changes, apply them to what's in the profile
    StructureDefinition profile = null;
    if (base.hasSliceName())
        profile = base.getType().size() == 1 && base.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, base.getTypeFirstRep().getProfile().get(0).getValue()) : null;
    if (profile == null)
        profile = source.getType().size() == 1 && source.getTypeFirstRep().hasProfile() ? context.fetchResource(StructureDefinition.class, source.getTypeFirstRep().getProfile().get(0).getValue()) : null;
    if (profile != null) {
        ElementDefinition e = profile.getSnapshot().getElement().get(0);
        String webroot = profile.getUserString("webroot");
        if (e.hasDefinition()) {
            base.setDefinition(processRelativeUrls(e.getDefinition(), webroot, baseSpecUrl(), context.getResourceNames(), masterSourceFileNames, null, true));
        }
        base.setShort(e.getShort());
        if (e.hasCommentElement())
            base.setCommentElement(e.getCommentElement());
        if (e.hasRequirementsElement())
            base.setRequirementsElement(e.getRequirementsElement());
        base.getAlias().clear();
        base.getAlias().addAll(e.getAlias());
        base.getMapping().clear();
        base.getMapping().addAll(e.getMapping());
    }
    if (derived != null) {
        if (derived.hasSliceName()) {
            base.setSliceName(derived.getSliceName());
        }
        if (derived.hasShortElement()) {
            if (!Base.compareDeep(derived.getShortElement(), base.getShortElement(), false))
                base.setShortElement(derived.getShortElement().copy());
            else if (trimDifferential)
                derived.setShortElement(null);
            else if (derived.hasShortElement())
                derived.getShortElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasDefinitionElement()) {
            if (derived.getDefinition().startsWith("..."))
                base.setDefinition(base.getDefinition() + "\r\n" + derived.getDefinition().substring(3));
            else if (!Base.compareDeep(derived.getDefinitionElement(), base.getDefinitionElement(), false))
                base.setDefinitionElement(derived.getDefinitionElement().copy());
            else if (trimDifferential)
                derived.setDefinitionElement(null);
            else if (derived.hasDefinitionElement())
                derived.getDefinitionElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasCommentElement()) {
            if (derived.getComment().startsWith("..."))
                base.setComment(base.getComment() + "\r\n" + derived.getComment().substring(3));
            else if (derived.hasCommentElement() != base.hasCommentElement() || !Base.compareDeep(derived.getCommentElement(), base.getCommentElement(), false))
                base.setCommentElement(derived.getCommentElement().copy());
            else if (trimDifferential)
                base.setCommentElement(derived.getCommentElement().copy());
            else if (derived.hasCommentElement())
                derived.getCommentElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasLabelElement()) {
            if (derived.getLabel().startsWith("..."))
                base.setLabel(base.getLabel() + "\r\n" + derived.getLabel().substring(3));
            else if (!base.hasLabelElement() || !Base.compareDeep(derived.getLabelElement(), base.getLabelElement(), false))
                base.setLabelElement(derived.getLabelElement().copy());
            else if (trimDifferential)
                base.setLabelElement(derived.getLabelElement().copy());
            else if (derived.hasLabelElement())
                derived.getLabelElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasRequirementsElement()) {
            if (derived.getRequirements().startsWith("..."))
                base.setRequirements(base.getRequirements() + "\r\n" + derived.getRequirements().substring(3));
            else if (!base.hasRequirementsElement() || !Base.compareDeep(derived.getRequirementsElement(), base.getRequirementsElement(), false))
                base.setRequirementsElement(derived.getRequirementsElement().copy());
            else if (trimDifferential)
                base.setRequirementsElement(derived.getRequirementsElement().copy());
            else if (derived.hasRequirementsElement())
                derived.getRequirementsElement().setUserData(DERIVATION_EQUALS, true);
        }
        // sdf-9
        if (derived.hasRequirements() && !base.getPath().contains("."))
            derived.setRequirements(null);
        if (base.hasRequirements() && !base.getPath().contains("."))
            base.setRequirements(null);
        if (derived.hasAlias()) {
            if (!Base.compareDeep(derived.getAlias(), base.getAlias(), false))
                for (StringType s : derived.getAlias()) {
                    if (!base.hasAlias(s.getValue()))
                        base.getAlias().add(s.copy());
                }
            else if (trimDifferential)
                derived.getAlias().clear();
            else
                for (StringType t : derived.getAlias()) t.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMinElement()) {
            if (!Base.compareDeep(derived.getMinElement(), base.getMinElement(), false)) {
                if (// in a slice, minimum cardinality rules do not apply
                derived.getMin() < base.getMin() && !derived.hasSliceName())
                    messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + source.getPath(), "Element " + base.getPath() + ": derived min (" + Integer.toString(derived.getMin()) + ") cannot be less than base min (" + Integer.toString(base.getMin()) + ")", ValidationMessage.IssueSeverity.ERROR));
                base.setMinElement(derived.getMinElement().copy());
            } else if (trimDifferential)
                derived.setMinElement(null);
            else
                derived.getMinElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxElement()) {
            if (!Base.compareDeep(derived.getMaxElement(), base.getMaxElement(), false)) {
                if (isLargerMax(derived.getMax(), base.getMax()))
                    messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + source.getPath(), "Element " + base.getPath() + ": derived max (" + derived.getMax() + ") cannot be greater than base max (" + base.getMax() + ")", ValidationMessage.IssueSeverity.ERROR));
                base.setMaxElement(derived.getMaxElement().copy());
            } else if (trimDifferential)
                derived.setMaxElement(null);
            else
                derived.getMaxElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasFixed()) {
            if (!Base.compareDeep(derived.getFixed(), base.getFixed(), true)) {
                base.setFixed(derived.getFixed().copy());
            } else if (trimDifferential)
                derived.setFixed(null);
            else
                derived.getFixed().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasPattern()) {
            if (!Base.compareDeep(derived.getPattern(), base.getPattern(), false)) {
                base.setPattern(derived.getPattern().copy());
            } else if (trimDifferential)
                derived.setPattern(null);
            else
                derived.getPattern().setUserData(DERIVATION_EQUALS, true);
        }
        for (ElementDefinitionExampleComponent ex : derived.getExample()) {
            boolean found = false;
            for (ElementDefinitionExampleComponent exS : base.getExample()) if (Base.compareDeep(ex, exS, false))
                found = true;
            if (!found)
                base.addExample(ex.copy());
            else if (trimDifferential)
                derived.getExample().remove(ex);
            else
                ex.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxLengthElement()) {
            if (!Base.compareDeep(derived.getMaxLengthElement(), base.getMaxLengthElement(), false))
                base.setMaxLengthElement(derived.getMaxLengthElement().copy());
            else if (trimDifferential)
                derived.setMaxLengthElement(null);
            else
                derived.getMaxLengthElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMaxValue()) {
            if (!Base.compareDeep(derived.getMaxValue(), base.getMaxValue(), false))
                base.setMaxValue(derived.getMaxValue().copy());
            else if (trimDifferential)
                derived.setMaxValue(null);
            else
                derived.getMaxValue().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMinValue()) {
            if (!Base.compareDeep(derived.getMinValue(), base.getMinValue(), false))
                base.setMinValue(derived.getMinValue().copy());
            else if (trimDifferential)
                derived.setMinValue(null);
            else
                derived.getMinValue().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMustSupportElement()) {
            if (!(base.hasMustSupportElement() && Base.compareDeep(derived.getMustSupportElement(), base.getMustSupportElement(), false))) {
                if (base.hasMustSupport() && base.getMustSupport() && !derived.getMustSupport()) {
                    messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Illegal constraint [must-support = false] when [must-support = true] in the base profile", ValidationMessage.IssueSeverity.ERROR));
                }
                base.setMustSupportElement(derived.getMustSupportElement().copy());
            } else if (trimDifferential)
                derived.setMustSupportElement(null);
            else
                derived.getMustSupportElement().setUserData(DERIVATION_EQUALS, true);
        }
        // but extensions can change isModifier
        if (isExtension) {
            if (derived.hasIsModifierElement() && !(base.hasIsModifierElement() && Base.compareDeep(derived.getIsModifierElement(), base.getIsModifierElement(), false)))
                base.setIsModifierElement(derived.getIsModifierElement().copy());
            else if (trimDifferential)
                derived.setIsModifierElement(null);
            else if (derived.hasIsModifierElement())
                derived.getIsModifierElement().setUserData(DERIVATION_EQUALS, true);
            if (derived.hasIsModifierReasonElement() && !(base.hasIsModifierReasonElement() && Base.compareDeep(derived.getIsModifierReasonElement(), base.getIsModifierReasonElement(), false)))
                base.setIsModifierReasonElement(derived.getIsModifierReasonElement().copy());
            else if (trimDifferential)
                derived.setIsModifierReasonElement(null);
            else if (derived.hasIsModifierReasonElement())
                derived.getIsModifierReasonElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasBinding()) {
            if (!base.hasBinding() || !Base.compareDeep(derived.getBinding(), base.getBinding(), false)) {
                if (base.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && derived.getBinding().getStrength() != BindingStrength.REQUIRED)
                    messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "illegal attempt to change the binding on " + derived.getPath() + " from " + base.getBinding().getStrength().toCode() + " to " + derived.getBinding().getStrength().toCode(), ValidationMessage.IssueSeverity.ERROR));
                else // throw new DefinitionException("StructureDefinition "+pn+" at "+derived.getPath()+": illegal attempt to change a binding from "+base.getBinding().getStrength().toCode()+" to "+derived.getBinding().getStrength().toCode());
                if (base.hasBinding() && derived.hasBinding() && base.getBinding().getStrength() == BindingStrength.REQUIRED && base.getBinding().hasValueSet() && derived.getBinding().hasValueSet()) {
                    ValueSet baseVs = context.fetchResource(ValueSet.class, base.getBinding().getValueSet());
                    ValueSet contextVs = context.fetchResource(ValueSet.class, derived.getBinding().getValueSet());
                    if (baseVs == null) {
                        messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + base.getPath(), "Binding " + base.getBinding().getValueSet() + " could not be located", ValidationMessage.IssueSeverity.WARNING));
                    } else if (contextVs == null) {
                        messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Binding " + derived.getBinding().getValueSet() + " could not be located", ValidationMessage.IssueSeverity.WARNING));
                    } else {
                        ValueSetExpansionOutcome expBase = context.expandVS(baseVs, true, false);
                        ValueSetExpansionOutcome expDerived = context.expandVS(contextVs, true, false);
                        if (expBase.getValueset() == null)
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + base.getPath(), "Binding " + base.getBinding().getValueSet() + " could not be expanded", ValidationMessage.IssueSeverity.WARNING));
                        else if (expDerived.getValueset() == null)
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Binding " + derived.getBinding().getValueSet() + " could not be expanded", ValidationMessage.IssueSeverity.WARNING));
                        else if (ToolingExtensions.hasExtension(expBase.getValueset().getExpansion(), ToolingExtensions.EXT_EXP_TOOCOSTLY))
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Unable to check if " + derived.getBinding().getValueSet() + " is a proper subset of " + base.getBinding().getValueSet() + " - base value set is too large to check", ValidationMessage.IssueSeverity.WARNING));
                        else if (!isSubset(expBase.getValueset(), expDerived.getValueset()))
                            messages.add(new ValidationMessage(Source.ProfileValidator, ValidationMessage.IssueType.BUSINESSRULE, pn + "." + derived.getPath(), "Binding " + derived.getBinding().getValueSet() + " is not a subset of binding " + base.getBinding().getValueSet(), ValidationMessage.IssueSeverity.ERROR));
                    }
                }
                ElementDefinitionBindingComponent d = derived.getBinding();
                ElementDefinitionBindingComponent nb = base.getBinding().copy();
                if (!COPY_BINDING_EXTENSIONS) {
                    nb.getExtension().clear();
                }
                nb.setDescription(null);
                nb.getExtension().addAll(d.getExtension());
                if (d.hasStrength()) {
                    nb.setStrength(d.getStrength());
                }
                if (d.hasDescription()) {
                    nb.setDescription(d.getDescription());
                }
                if (d.hasValueSet()) {
                    nb.setValueSet(d.getValueSet());
                }
                base.setBinding(nb);
            } else if (trimDifferential)
                derived.setBinding(null);
            else
                derived.getBinding().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasIsSummaryElement()) {
            if (!Base.compareDeep(derived.getIsSummaryElement(), base.getIsSummaryElement(), false)) {
                if (// work around a known issue with some 1.4.0 cosntraints
                base.hasIsSummary() && !context.getVersion().equals("1.4.0"))
                    throw new Error(context.formatMessage(I18nConstants.ERROR_IN_PROFILE__AT__BASE_ISSUMMARY___DERIVED_ISSUMMARY__, purl, derived.getPath(), base.getIsSummaryElement().asStringValue(), derived.getIsSummaryElement().asStringValue()));
                base.setIsSummaryElement(derived.getIsSummaryElement().copy());
            } else if (trimDifferential)
                derived.setIsSummaryElement(null);
            else
                derived.getIsSummaryElement().setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasType()) {
            if (!Base.compareDeep(derived.getType(), base.getType(), false)) {
                if (base.hasType()) {
                    for (TypeRefComponent ts : derived.getType()) {
                        checkTypeDerivation(purl, srcSD, base, derived, ts);
                    }
                }
                base.getType().clear();
                for (TypeRefComponent t : derived.getType()) {
                    TypeRefComponent tt = t.copy();
                    // tt.setUserData(DERIVATION_EQUALS, true);
                    base.getType().add(tt);
                }
            } else if (trimDifferential)
                derived.getType().clear();
            else
                for (TypeRefComponent t : derived.getType()) t.setUserData(DERIVATION_EQUALS, true);
        }
        if (derived.hasMapping()) {
            // todo: mappings are not cumulative - one replaces another
            if (!Base.compareDeep(derived.getMapping(), base.getMapping(), false)) {
                for (ElementDefinitionMappingComponent s : derived.getMapping()) {
                    boolean found = false;
                    for (ElementDefinitionMappingComponent d : base.getMapping()) {
                        found = found || (d.getIdentity().equals(s.getIdentity()) && d.getMap().equals(s.getMap()));
                    }
                    if (!found) {
                        base.getMapping().add(s);
                    }
                }
            } else if (trimDifferential) {
                derived.getMapping().clear();
            } else {
                for (ElementDefinitionMappingComponent t : derived.getMapping()) {
                    t.setUserData(DERIVATION_EQUALS, true);
                }
            }
        }
        for (ElementDefinitionMappingComponent m : base.getMapping()) {
            if (m.hasMap()) {
                m.setMap(m.getMap().trim());
            }
        }
        // todo: constraints are cumulative. there is no replacing
        for (ElementDefinitionConstraintComponent s : base.getConstraint()) {
            s.setUserData(IS_DERIVED, true);
            if (!s.hasSource()) {
                s.setSource(srcSD.getUrl());
            }
        }
        if (derived.hasConstraint()) {
            for (ElementDefinitionConstraintComponent s : derived.getConstraint()) {
                if (!base.hasConstraint(s.getKey())) {
                    ElementDefinitionConstraintComponent inv = s.copy();
                    base.getConstraint().add(inv);
                }
            }
        }
        for (IdType id : derived.getCondition()) {
            if (!base.hasCondition(id)) {
                base.getCondition().add(id);
            }
        }
        // now, check that we still have a bindable type; if not, delete the binding - see task 8477
        if (dest.hasBinding() && !hasBindableType(dest)) {
            dest.setBinding(null);
        }
        // finally, we copy any extensions from source to dest
        for (Extension ex : derived.getExtension()) {
            StructureDefinition sd = context.fetchResource(StructureDefinition.class, ex.getUrl());
            if (sd == null || sd.getSnapshot() == null || sd.getSnapshot().getElementFirstRep().getMax().equals("1")) {
                ToolingExtensions.removeExtension(dest, ex.getUrl());
            }
            dest.addExtension(ex.copy());
        }
    }
    if (dest.hasFixed()) {
        checkTypeOk(dest, dest.getFixed().fhirType(), srcSD);
    }
    if (dest.hasPattern()) {
        checkTypeOk(dest, dest.getPattern().fhirType(), srcSD);
    }
}
Also used : ElementDefinitionExampleComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionExampleComponent) ValidationMessage(org.hl7.fhir.utilities.validation.ValidationMessage) StringType(org.hl7.fhir.r5.model.StringType) FHIRFormatError(org.hl7.fhir.exceptions.FHIRFormatError) ElementDefinitionConstraintComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionConstraintComponent) IdType(org.hl7.fhir.r5.model.IdType) Extension(org.hl7.fhir.r5.model.Extension) StructureDefinition(org.hl7.fhir.r5.model.StructureDefinition) TypeRefComponent(org.hl7.fhir.r5.model.ElementDefinition.TypeRefComponent) ValueSetExpansionOutcome(org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome) ElementDefinition(org.hl7.fhir.r5.model.ElementDefinition) ValueSet(org.hl7.fhir.r5.model.ValueSet) ElementDefinitionBindingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionBindingComponent) ElementDefinitionMappingComponent(org.hl7.fhir.r5.model.ElementDefinition.ElementDefinitionMappingComponent)

Example 84 with ValueSetExpansionOutcome

use of org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome in project org.hl7.fhir.core by hapifhir.

the class BaseWorkerContext method expandVS.

@Override
public ValueSetExpansionOutcome expandVS(ConceptSetComponent inc, boolean hierarchical, boolean noInactive) throws TerminologyServiceException {
    ValueSet vs = new ValueSet();
    vs.setStatus(PublicationStatus.ACTIVE);
    vs.setCompose(new ValueSetComposeComponent());
    vs.getCompose().setInactive(!noInactive);
    vs.getCompose().getInclude().add(inc);
    CacheToken cacheToken = txCache.generateExpandToken(vs, hierarchical);
    ValueSetExpansionOutcome res;
    res = txCache.getExpansion(cacheToken);
    if (res != null) {
        return res;
    }
    Parameters p = constructParameters(vs, hierarchical);
    for (ConceptSetComponent incl : vs.getCompose().getInclude()) {
        codeSystemsUsed.add(incl.getSystem());
    }
    for (ConceptSetComponent incl : vs.getCompose().getExclude()) {
        codeSystemsUsed.add(incl.getSystem());
    }
    if (noTerminologyServer) {
        return new ValueSetExpansionOutcome(formatMessage(I18nConstants.ERROR_EXPANDING_VALUESET_RUNNING_WITHOUT_TERMINOLOGY_SERVICES), TerminologyServiceErrorClass.NOSERVICE);
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("_limit", Integer.toString(expandCodesLimit));
    params.put("_incomplete", "true");
    txLog("$expand on " + txCache.summary(vs));
    try {
        ValueSet result = txClient.expandValueset(vs, p, params);
        res = new ValueSetExpansionOutcome(result).setTxLink(txLog.getLastId());
    } catch (Exception e) {
        res = new ValueSetExpansionOutcome(e.getMessage() == null ? e.getClass().getName() : e.getMessage(), TerminologyServiceErrorClass.UNKNOWN);
        if (txLog != null) {
            res.setTxLink(txLog.getLastId());
        }
    }
    txCache.cacheExpansion(cacheToken, res, TerminologyCache.PERMANENT);
    return res;
}
Also used : ConceptSetComponent(org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent) Parameters(org.hl7.fhir.r5.model.Parameters) HashMap(java.util.HashMap) CacheToken(org.hl7.fhir.r5.context.TerminologyCache.CacheToken) ValueSetExpansionOutcome(org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome) ValueSet(org.hl7.fhir.r5.model.ValueSet) ValueSetComposeComponent(org.hl7.fhir.r5.model.ValueSet.ValueSetComposeComponent) TerminologyServiceException(org.hl7.fhir.exceptions.TerminologyServiceException) FileNotFoundException(java.io.FileNotFoundException) NoTerminologyServiceException(org.hl7.fhir.exceptions.NoTerminologyServiceException) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException)

Example 85 with ValueSetExpansionOutcome

use of org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome in project org.hl7.fhir.core by hapifhir.

the class BaseWorkerContext method expandVS.

public ValueSetExpansionOutcome expandVS(ValueSet vs, boolean cacheOk, boolean hierarchical, boolean incompleteOk, Parameters pIn) {
    if (pIn == null) {
        throw new Error(formatMessage(I18nConstants.NO_PARAMETERS_PROVIDED_TO_EXPANDVS));
    }
    Parameters p = pIn.copy();
    if (vs.hasExpansion()) {
        return new ValueSetExpansionOutcome(vs.copy());
    }
    if (!vs.hasUrl()) {
        throw new Error(formatMessage(I18nConstants.NO_VALUE_SET_IN_URL));
    }
    for (ConceptSetComponent inc : vs.getCompose().getInclude()) {
        codeSystemsUsed.add(inc.getSystem());
    }
    for (ConceptSetComponent inc : vs.getCompose().getExclude()) {
        codeSystemsUsed.add(inc.getSystem());
    }
    CacheToken cacheToken = txCache.generateExpandToken(vs, hierarchical);
    ValueSetExpansionOutcome res;
    if (cacheOk) {
        res = txCache.getExpansion(cacheToken);
        if (res != null) {
            return res;
        }
    }
    p.setParameter("includeDefinition", false);
    p.setParameter("excludeNested", !hierarchical);
    if (incompleteOk) {
        p.setParameter("incomplete-ok", true);
    }
    List<String> allErrors = new ArrayList<>();
    // ok, first we try to expand locally
    ValueSetExpanderSimple vse = constructValueSetExpanderSimple();
    try {
        res = vse.expand(vs, p);
        allErrors.addAll(vse.getAllErrors());
        if (res.getValueset() != null) {
            if (!res.getValueset().hasUrl()) {
                throw new Error(formatMessage(I18nConstants.NO_URL_IN_EXPAND_VALUE_SET));
            }
            txCache.cacheExpansion(cacheToken, res, TerminologyCache.TRANSIENT);
            return res;
        }
    } catch (Exception e) {
        allErrors.addAll(vse.getAllErrors());
        e.printStackTrace();
    }
    // if that failed, we try to expand on the server
    if (addDependentResources(p, vs)) {
        p.addParameter().setName("cache-id").setValue(new StringType(cacheId));
    }
    if (noTerminologyServer) {
        return new ValueSetExpansionOutcome(formatMessage(I18nConstants.ERROR_EXPANDING_VALUESET_RUNNING_WITHOUT_TERMINOLOGY_SERVICES), TerminologyServiceErrorClass.NOSERVICE, allErrors);
    }
    Map<String, String> params = new HashMap<String, String>();
    params.put("_limit", Integer.toString(expandCodesLimit));
    params.put("_incomplete", "true");
    txLog("$expand on " + txCache.summary(vs));
    try {
        ValueSet result = txClient.expandValueset(vs, p, params);
        if (!result.hasUrl()) {
            result.setUrl(vs.getUrl());
        }
        if (!result.hasUrl()) {
            throw new Error(formatMessage(I18nConstants.NO_URL_IN_EXPAND_VALUE_SET_2));
        }
        res = new ValueSetExpansionOutcome(result).setTxLink(txLog.getLastId());
    } catch (Exception e) {
        res = new ValueSetExpansionOutcome(e.getMessage() == null ? e.getClass().getName() : e.getMessage(), TerminologyServiceErrorClass.UNKNOWN, allErrors).setTxLink(txLog == null ? null : txLog.getLastId());
    }
    txCache.cacheExpansion(cacheToken, res, TerminologyCache.PERMANENT);
    return res;
}
Also used : Parameters(org.hl7.fhir.r5.model.Parameters) StringType(org.hl7.fhir.r5.model.StringType) HashMap(java.util.HashMap) CacheToken(org.hl7.fhir.r5.context.TerminologyCache.CacheToken) ArrayList(java.util.ArrayList) TerminologyServiceException(org.hl7.fhir.exceptions.TerminologyServiceException) FileNotFoundException(java.io.FileNotFoundException) NoTerminologyServiceException(org.hl7.fhir.exceptions.NoTerminologyServiceException) DefinitionException(org.hl7.fhir.exceptions.DefinitionException) IOException(java.io.IOException) FHIRException(org.hl7.fhir.exceptions.FHIRException) ConceptSetComponent(org.hl7.fhir.r5.model.ValueSet.ConceptSetComponent) ValueSetExpansionOutcome(org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome) ValueSetExpanderSimple(org.hl7.fhir.r5.terminologies.ValueSetExpanderSimple) ValueSet(org.hl7.fhir.r5.model.ValueSet)

Aggregations

IOException (java.io.IOException)26 FHIRException (org.hl7.fhir.exceptions.FHIRException)25 TerminologyServiceException (org.hl7.fhir.exceptions.TerminologyServiceException)24 DefinitionException (org.hl7.fhir.exceptions.DefinitionException)22 FileNotFoundException (java.io.FileNotFoundException)16 ValueSet (org.hl7.fhir.r5.model.ValueSet)16 ValueSetExpansionOutcome (org.hl7.fhir.r5.terminologies.ValueSetExpander.ValueSetExpansionOutcome)16 HashMap (java.util.HashMap)11 ValueSetExpansionOutcome (org.hl7.fhir.dstu3.terminologies.ValueSetExpander.ValueSetExpansionOutcome)11 NoTerminologyServiceException (org.hl7.fhir.exceptions.NoTerminologyServiceException)11 ValueSet (org.hl7.fhir.r4b.model.ValueSet)11 ValidationMessage (org.hl7.fhir.utilities.validation.ValidationMessage)11 File (java.io.File)10 ValueSetExpansionOutcome (org.hl7.fhir.r4.terminologies.ValueSetExpander.ValueSetExpansionOutcome)10 ValueSetExpansionOutcome (org.hl7.fhir.r4b.terminologies.ValueSetExpander.ValueSetExpansionOutcome)10 NotImplementedException (org.apache.commons.lang3.NotImplementedException)9 ValueSet (org.hl7.fhir.r4.model.ValueSet)9 FileInputStream (java.io.FileInputStream)8 ValueSetExpansionOutcome (org.hl7.fhir.dstu2.terminologies.ValueSetExpander.ValueSetExpansionOutcome)8 ValueSetExpansionOutcome (org.hl7.fhir.dstu2016may.terminologies.ValueSetExpander.ValueSetExpansionOutcome)8