use of org.hl7.fhir.r4b.model.BackboneElement 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);
}
}
}
use of org.hl7.fhir.r4b.model.BackboneElement in project org.hl7.fhir.core by hapifhir.
the class ProfileUtilities method processPaths.
/**
* @param trimDifferential
* @param srcSD
* @throws DefinitionException, FHIRException
* @throws Exception
*/
private ElementDefinition processPaths(String indent, StructureDefinitionSnapshotComponent result, StructureDefinitionSnapshotComponent base, StructureDefinitionDifferentialComponent differential, int baseCursor, int diffCursor, int baseLimit, int diffLimit, String url, String webUrl, String profileName, String contextPathSrc, String contextPathDst, boolean trimDifferential, String contextName, String resultPathBase, boolean slicingDone, List<ElementRedirection> redirector, StructureDefinition srcSD) throws DefinitionException, FHIRException {
if (debug)
System.out.println(indent + "PP @ " + resultPathBase + " / " + contextPathSrc + " : base = " + baseCursor + " to " + baseLimit + ", diff = " + diffCursor + " to " + diffLimit + " (slicing = " + slicingDone + ", redirector = " + (redirector == null ? "null" : redirector.toString()) + ")");
ElementDefinition res = null;
List<TypeSlice> typeList = new ArrayList<>();
// just repeat processing entries until we run out of our allowed scope (1st entry, the allowed scope is all the entries)
while (baseCursor <= baseLimit) {
// get the current focus of the base, and decide what to do
ElementDefinition currentBase = base.getElement().get(baseCursor);
String cpath = fixedPathSource(contextPathSrc, currentBase.getPath(), redirector);
if (debug)
System.out.println(indent + " - " + cpath + ": base = " + baseCursor + " (" + descED(base.getElement(), baseCursor) + ") to " + baseLimit + " (" + descED(base.getElement(), baseLimit) + "), diff = " + diffCursor + " (" + descED(differential.getElement(), diffCursor) + ") to " + diffLimit + " (" + descED(differential.getElement(), diffLimit) + ") " + "(slicingDone = " + slicingDone + ") (diffpath= " + (differential.getElement().size() > diffCursor ? differential.getElement().get(diffCursor).getPath() : "n/a") + ")");
// get a list of matching elements in scope
List<ElementDefinition> diffMatches = getDiffMatches(differential, cpath, diffCursor, diffLimit, profileName);
// in the simple case, source is not sliced.
if (!currentBase.hasSlicing()) {
if (diffMatches.isEmpty()) {
// the differential doesn't say anything about this item
// so we just copy it in
ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
updateFromBase(outcome, currentBase);
markDerived(outcome);
if (resultPathBase == null)
resultPathBase = outcome.getPath();
else if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
result.getElement().add(outcome);
if (hasInnerDiffMatches(differential, cpath, diffCursor, diffLimit, base.getElement(), true)) {
// did we implicitly step into a new type?
if (baseHasChildren(base, currentBase)) {
// not a new type here
processPaths(indent + " ", result, base, differential, baseCursor + 1, diffCursor, baseLimit, diffLimit, url, webUrl, profileName, contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
baseCursor = indexOfFirstNonChild(base, currentBase, baseCursor + 1, baseLimit);
} else {
if (outcome.getType().size() == 0) {
throw new DefinitionException(diffMatches.get(0).getPath() + " has no children (" + differential.getElement().get(diffCursor).getPath() + ") and no types in profile " + profileName);
}
if (outcome.getType().size() > 1) {
for (TypeRefComponent t : outcome.getType()) {
if (!t.getWorkingCode().equals("Reference"))
throw new DefinitionException(diffMatches.get(0).getPath() + " has children (" + differential.getElement().get(diffCursor).getPath() + ") and multiple types (" + typeCode(outcome.getType()) + ") in profile " + profileName);
}
}
StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
if (dt == null)
throw new DefinitionException("Unknown type " + outcome.getType().get(0) + " at " + diffMatches.get(0).getPath());
contextName = dt.getUrl();
int start = diffCursor;
while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), cpath + ".")) diffCursor++;
processPaths(indent + " ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, webUrl, profileName, cpath, outcome.getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
}
}
baseCursor++;
} else if (diffMatches.size() == 1 && (slicingDone || (!isImplicitSlicing(diffMatches.get(0), cpath) && !(diffMatches.get(0).hasSlicing() || (isExtension(diffMatches.get(0)) && diffMatches.get(0).hasSliceName()))))) {
// one matching element in the differential
ElementDefinition template = null;
if (diffMatches.get(0).hasType() && diffMatches.get(0).getType().size() == 1 && diffMatches.get(0).getType().get(0).hasProfile() && !"Reference".equals(diffMatches.get(0).getType().get(0).getWorkingCode())) {
CanonicalType p = diffMatches.get(0).getType().get(0).getProfile().get(0);
StructureDefinition sd = context.fetchResource(StructureDefinition.class, p.getValue());
if (sd != null) {
if (!sd.hasSnapshot()) {
StructureDefinition sdb = context.fetchResource(StructureDefinition.class, sd.getBaseDefinition());
if (sdb == null)
throw new DefinitionException("no base for " + sd.getBaseDefinition());
generateSnapshot(sdb, sd, sd.getUrl(), (sdb.hasUserData("path")) ? Utilities.extractBaseUrl(sdb.getUserString("path")) : webUrl, sd.getName());
}
ElementDefinition src;
if (p.hasExtension(ToolingExtensions.EXT_PROFILE_ELEMENT)) {
src = null;
String eid = p.getExtensionString(ToolingExtensions.EXT_PROFILE_ELEMENT);
for (ElementDefinition t : sd.getSnapshot().getElement()) {
if (eid.equals(t.getId()))
src = t;
}
if (src == null)
throw new DefinitionException("Unable to find element " + eid + " in " + p.getValue());
} else
src = sd.getSnapshot().getElement().get(0);
template = src.copy().setPath(currentBase.getPath());
template.setSliceName(null);
// temporary work around
if (!"Extension".equals(diffMatches.get(0).getType().get(0).getCode())) {
template.setMin(currentBase.getMin());
template.setMax(currentBase.getMax());
}
}
}
if (template == null)
template = currentBase.copy();
else
// some of what's in currentBase overrides template
template = overWriteWithCurrent(template, currentBase);
ElementDefinition outcome = updateURLs(url, webUrl, template);
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
if (res == null)
res = outcome;
updateFromBase(outcome, currentBase);
if (diffMatches.get(0).hasSliceName())
outcome.setSliceName(diffMatches.get(0).getSliceName());
updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
removeStatusExtensions(outcome);
// if (outcome.getPath().endsWith("[x]") && outcome.getType().size() == 1 && !outcome.getType().get(0).getCode().equals("*") && !diffMatches.get(0).hasSlicing()) // if the base profile allows multiple types, but the profile only allows one, rename it
// outcome.setPath(outcome.getPath().substring(0, outcome.getPath().length()-3)+Utilities.capitalize(outcome.getType().get(0).getCode()));
outcome.setSlicing(null);
if (resultPathBase == null)
resultPathBase = outcome.getPath();
else if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
result.getElement().add(outcome);
baseCursor++;
diffCursor = differential.getElement().indexOf(diffMatches.get(0)) + 1;
if (differential.getElement().size() > diffCursor && outcome.getPath().contains(".") && (isDataType(outcome.getType()) || outcome.hasContentReference())) {
// don't want to do this for the root, since that's base, and we're already processing it
if (pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".") && !baseWalksInto(base.getElement(), baseCursor)) {
if (outcome.getType().size() > 1) {
if (outcome.getPath().endsWith("[x]") && !diffMatches.get(0).getPath().endsWith("[x]")) {
String en = tail(outcome.getPath());
String tn = tail(diffMatches.get(0).getPath());
String t = tn.substring(en.length() - 3);
if (isPrimitive(Utilities.uncapitalize(t)))
t = Utilities.uncapitalize(t);
// keep any additional information
List<TypeRefComponent> ntr = getByTypeName(outcome.getType(), t);
if (ntr.isEmpty())
ntr.add(new TypeRefComponent().setCode(t));
outcome.getType().clear();
outcome.getType().addAll(ntr);
}
if (outcome.getType().size() > 1)
for (TypeRefComponent t : outcome.getType()) {
if (!t.getCode().equals("Reference")) {
boolean nonExtension = false;
for (ElementDefinition ed : diffMatches) if (ed != diffMatches.get(0) && !ed.getPath().endsWith(".extension"))
nonExtension = true;
if (nonExtension)
throw new DefinitionException(diffMatches.get(0).getPath() + " has children (" + differential.getElement().get(diffCursor).getPath() + ") and multiple types (" + typeCode(outcome.getType()) + ") in profile " + profileName);
}
}
}
int start = diffCursor;
while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
if (outcome.hasContentReference()) {
ElementDefinition tgt = getElementById(base.getElement(), outcome.getContentReference());
if (tgt == null)
throw new DefinitionException("Unable to resolve reference to " + outcome.getContentReference());
replaceFromContentReference(outcome, tgt);
int nbc = base.getElement().indexOf(tgt) + 1;
int nbl = nbc;
while (nbl < base.getElement().size() && base.getElement().get(nbl).getPath().startsWith(tgt.getPath() + ".")) nbl++;
processPaths(indent + " ", result, base, differential, nbc, start - 1, nbl - 1, diffCursor - 1, url, webUrl, profileName, tgt.getPath(), diffMatches.get(0).getPath(), trimDifferential, contextName, resultPathBase, false, redirectorStack(redirector, outcome, cpath), srcSD);
} else {
StructureDefinition dt = outcome.getType().size() == 1 ? getProfileForDataType(outcome.getType().get(0)) : getProfileForDataType("Element");
if (dt == null)
throw new DefinitionException(diffMatches.get(0).getPath() + " has children (" + differential.getElement().get(diffCursor).getPath() + ") for type " + typeCode(outcome.getType()) + " in profile " + profileName + ", but can't find type");
contextName = dt.getUrl();
processPaths(indent + " ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
start, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, webUrl, profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, new ArrayList<ElementRedirection>(), srcSD);
}
}
}
} else if (diffsConstrainTypes(diffMatches, cpath, typeList)) {
int start = 0;
int nbl = findEndOfElement(base, baseCursor);
int ndc = differential.getElement().indexOf(diffMatches.get(0));
ElementDefinition elementToRemove = null;
// we come here whether they are sliced in the diff, or whether the short cut is used.
if (typeList.get(0).type != null) {
// in R3 (and unpatched R4, as a workaround right now...
if (!FHIRVersion.isR4Plus(context.getVersion()) || !newSlicingProcessing) {
// newSlicingProcessing is a work around for editorial loop dependency
// we insert a cloned element with the right types at the start of the diffMatches
ElementDefinition ed = new ElementDefinition();
ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
for (TypeSlice ts : typeList) ed.addType().setCode(ts.type);
ed.setSlicing(new ElementDefinitionSlicingComponent());
ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
ed.getSlicing().setRules(SlicingRules.CLOSED);
ed.getSlicing().setOrdered(false);
diffMatches.add(0, ed);
differential.getElement().add(ndc, ed);
elementToRemove = ed;
} else {
// as of R4, this changed; if there's no slice, there's no constraint on the slice types, only one the type.
// so the element we insert specifies no types (= all types) allowed in the base, not just the listed type.
// see also discussion here: https://chat.fhir.org/#narrow/stream/179177-conformance/topic/Slicing.20a.20non-repeating.20element
ElementDefinition ed = new ElementDefinition();
ed.setPath(determineTypeSlicePath(diffMatches.get(0).getPath(), cpath));
ed.setSlicing(new ElementDefinitionSlicingComponent());
ed.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
ed.getSlicing().setRules(SlicingRules.CLOSED);
ed.getSlicing().setOrdered(false);
diffMatches.add(0, ed);
differential.getElement().add(ndc, ed);
elementToRemove = ed;
}
}
int ndl = findEndOfElement(differential, ndc);
// the first element is setting up the slicing
if (diffMatches.get(0).getSlicing().hasRules())
if (diffMatches.get(0).getSlicing().getRules() != SlicingRules.CLOSED)
throw new FHIRException("Error at path " + contextPathSrc + ": Type slicing with slicing.rules != closed");
if (diffMatches.get(0).getSlicing().hasOrdered())
if (diffMatches.get(0).getSlicing().getOrdered())
throw new FHIRException("Error at path " + contextPathSrc + ": Type slicing with slicing.ordered = true");
if (diffMatches.get(0).getSlicing().hasDiscriminator()) {
if (diffMatches.get(0).getSlicing().getDiscriminator().size() != 1)
throw new FHIRException("Error at path " + contextPathSrc + ": Type slicing with slicing.discriminator.count() > 1");
if (!"$this".equals(diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getPath()))
throw new FHIRException("Error at path " + contextPathSrc + ": Type slicing with slicing.discriminator.path != '$this'");
if (diffMatches.get(0).getSlicing().getDiscriminatorFirstRep().getType() != DiscriminatorType.TYPE)
throw new FHIRException("Error at path " + contextPathSrc + ": Type slicing with slicing.discriminator.type != 'type'");
}
// check the slice names too while we're at it...
for (TypeSlice ts : typeList) if (ts.type != null) {
String tn = rootName(cpath) + Utilities.capitalize(ts.type);
if (!ts.defn.hasSliceName())
ts.defn.setSliceName(tn);
else if (!ts.defn.getSliceName().equals(tn))
throw new FHIRException("Error at path " + (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath) + ": Slice name must be '" + tn + "' but is '" + ts.defn.getSliceName() + "'");
if (!ts.defn.hasType())
ts.defn.addType().setCode(ts.type);
else if (ts.defn.getType().size() > 1)
throw new FHIRException("Error at path " + (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath) + ": Slice for type '" + tn + "' has more than one type '" + ts.defn.typeSummary() + "'");
else if (!ts.defn.getType().get(0).getCode().equals(ts.type))
throw new FHIRException("Error at path " + (!Utilities.noString(contextPathSrc) ? contextPathSrc : cpath) + ": Slice for type '" + tn + "' has wrong type '" + ts.defn.typeSummary() + "'");
}
// ok passed the checks.
// copy the root diff, and then process any children it has
ElementDefinition e = processPaths(indent + " ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
if (e == null)
throw new FHIRException("Did not find type root: " + diffMatches.get(0).getPath());
// now set up slicing on the e (cause it was wiped by what we called.
e.setSlicing(new ElementDefinitionSlicingComponent());
e.getSlicing().addDiscriminator().setType(DiscriminatorType.TYPE).setPath("$this");
e.getSlicing().setRules(SlicingRules.CLOSED);
e.getSlicing().setOrdered(false);
start++;
// now we process the base scope repeatedly for each instance of the item in the differential list
for (int i = start; i < diffMatches.size(); i++) {
// our processing scope for the differential is the item in the list, and all the items before the next one in the list
ndc = differential.getElement().indexOf(diffMatches.get(i));
ndl = findEndOfElement(differential, ndc);
processPaths(indent + " ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
}
if (elementToRemove != null) {
differential.getElement().remove(elementToRemove);
ndl--;
}
// ok, done with that - next in the base list
baseCursor = nbl + 1;
diffCursor = ndl + 1;
} else {
// ok, the differential slices the item. Let's check our pre-conditions to ensure that this is correct
if (!unbounded(currentBase) && !isSlicedToOneOnly(diffMatches.get(0)))
// (but you might do that in order to split up constraints by type)
throw new DefinitionException("Attempt to a slice an element that does not repeat: " + currentBase.getPath() + "/" + currentBase.getPath() + " from " + contextName + " in " + url);
if (// well, the diff has set up a slice, but hasn't defined it. this is an error
!diffMatches.get(0).hasSlicing() && !isExtension(currentBase))
throw new DefinitionException("Differential does not have a slice: " + currentBase.getPath() + "/ (b:" + baseCursor + " of " + baseLimit + " / " + diffCursor + "/ " + diffLimit + ") in profile " + url);
// well, if it passed those preconditions then we slice the dest.
int start = 0;
int nbl = findEndOfElement(base, baseCursor);
// if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0))+1) {
if (diffMatches.size() > 1 && diffMatches.get(0).hasSlicing() && (nbl > baseCursor || differential.getElement().indexOf(diffMatches.get(1)) > differential.getElement().indexOf(diffMatches.get(0)) + 1)) {
// there's a default set before the slices
int ndc = differential.getElement().indexOf(diffMatches.get(0));
int ndl = findEndOfElement(differential, ndc);
ElementDefinition e = processPaths(indent + " ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
if (e == null)
throw new FHIRException("Did not find single slice: " + diffMatches.get(0).getPath());
e.setSlicing(diffMatches.get(0).getSlicing());
start++;
} else {
// we're just going to accept the differential slicing at face value
ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
updateFromBase(outcome, currentBase);
if (!diffMatches.get(0).hasSlicing())
outcome.setSlicing(makeExtensionSlicing());
else
outcome.setSlicing(diffMatches.get(0).getSlicing().copy());
if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
result.getElement().add(outcome);
// differential - if the first one in the list has a name, we'll process it. Else we'll treat it as the base definition of the slice.
if (!diffMatches.get(0).hasSliceName()) {
updateFromDefinition(outcome, diffMatches.get(0), profileName, trimDifferential, url, srcSD);
removeStatusExtensions(outcome);
if (!outcome.hasContentReference() && !outcome.hasType()) {
throw new DefinitionException("not done yet");
}
start++;
// result.getElement().remove(result.getElement().size()-1);
} else
checkExtensionDoco(outcome);
}
// now, for each entry in the diff matches, we're going to process the base item
// our processing scope for base is all the children of the current path
int ndc = diffCursor;
int ndl = diffCursor;
for (int i = start; i < diffMatches.size(); i++) {
// our processing scope for the differential is the item in the list, and all the items before the next one in the list
ndc = differential.getElement().indexOf(diffMatches.get(i));
ndl = findEndOfElement(differential, ndc);
/* if (skipSlicingElement && i == 0) {
ndc = ndc + 1;
if (ndc > ndl)
continue;
}*/
// now we process the base scope repeatedly for each instance of the item in the differential list
processPaths(indent + " ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, i), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, true, redirector, srcSD);
}
// ok, done with that - next in the base list
baseCursor = nbl + 1;
diffCursor = ndl + 1;
}
} else {
// the item is already sliced in the base profile.
// here's the rules
// 1. irrespective of whether the slicing is ordered or not, the definition order must be maintained
// 2. slice element names have to match.
// 3. new slices must be introduced at the end
// corallory: you can't re-slice existing slices. is that ok?
// we're going to need this:
String path = currentBase.getPath();
ElementDefinition original = currentBase;
if (diffMatches.isEmpty()) {
// copy across the currentbase, and all of its children and siblings
while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path)) {
ElementDefinition outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path in profile " + profileName + ": " + outcome.getPath() + " vs " + resultPathBase);
// so we just copy it in
result.getElement().add(outcome);
baseCursor++;
}
} else {
// first - check that the slicing is ok
boolean closed = currentBase.getSlicing().getRules() == SlicingRules.CLOSED;
int diffpos = 0;
boolean isExtension = cpath.endsWith(".extension") || cpath.endsWith(".modifierExtension");
if (diffMatches.get(0).hasSlicing()) {
// it might be null if the differential doesn't want to say anything about slicing
// if (!isExtension)
// diffpos++; // if there's a slice on the first, we'll ignore any content it has
ElementDefinitionSlicingComponent dSlice = diffMatches.get(0).getSlicing();
ElementDefinitionSlicingComponent bSlice = currentBase.getSlicing();
if (dSlice.hasOrderedElement() && bSlice.hasOrderedElement() && !orderMatches(dSlice.getOrderedElement(), bSlice.getOrderedElement()))
throw new DefinitionException("Slicing rules on differential (" + summarizeSlicing(dSlice) + ") do not match those on base (" + summarizeSlicing(bSlice) + ") - order @ " + path + " (" + contextName + ")");
if (!discriminatorMatches(dSlice.getDiscriminator(), bSlice.getDiscriminator()))
throw new DefinitionException("Slicing rules on differential (" + summarizeSlicing(dSlice) + ") do not match those on base (" + summarizeSlicing(bSlice) + ") - disciminator @ " + path + " (" + contextName + ")");
if (!ruleMatches(dSlice.getRules(), bSlice.getRules()))
throw new DefinitionException("Slicing rules on differential (" + summarizeSlicing(dSlice) + ") do not match those on base (" + summarizeSlicing(bSlice) + ") - rule @ " + path + " (" + contextName + ")");
}
ElementDefinition outcome = updateURLs(url, webUrl, currentBase.copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
updateFromBase(outcome, currentBase);
if (diffMatches.get(0).hasSlicing() || !diffMatches.get(0).hasSliceName()) {
updateFromSlicing(outcome.getSlicing(), diffMatches.get(0).getSlicing());
// if there's no slice, we don't want to update the unsliced description
updateFromDefinition(outcome, diffMatches.get(0), profileName, closed, url, srcSD);
removeStatusExtensions(outcome);
} else if (!diffMatches.get(0).hasSliceName())
// because of updateFromDefinition isn't called
diffMatches.get(0).setUserData(GENERATED_IN_SNAPSHOT, outcome);
result.getElement().add(outcome);
if (!diffMatches.get(0).hasSliceName()) {
// it's not real content, just the slice
diffpos++;
}
if (hasInnerDiffMatches(differential, cpath, diffpos, diffLimit, base.getElement(), false)) {
int nbl = findEndOfElement(base, baseCursor);
int ndc = differential.getElement().indexOf(diffMatches.get(0)) + 1;
int ndl = findEndOfElement(differential, ndc);
processPaths(indent + " ", result, base, differential, baseCursor + 1, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, 0), contextPathSrc, contextPathDst, trimDifferential, contextName, resultPathBase, false, null, srcSD);
// throw new Error("Not done yet");
// } else if (currentBase.getType().get(0).getCode().equals("BackboneElement") && diffMatches.size() > 0 && diffMatches.get(0).hasSliceName()) {
} else if (currentBase.getType().get(0).getCode().equals("BackboneElement")) {
// We need to copy children of the backbone element before we start messing around with slices
int nbl = findEndOfElement(base, baseCursor);
for (int i = baseCursor + 1; i <= nbl; i++) {
outcome = updateURLs(url, webUrl, base.getElement().get(i).copy());
result.getElement().add(outcome);
}
}
// now, we have two lists, base and diff. we're going to work through base, looking for matches in diff.
List<ElementDefinition> baseMatches = getSiblings(base.getElement(), currentBase);
for (ElementDefinition baseItem : baseMatches) {
baseCursor = base.getElement().indexOf(baseItem);
outcome = updateURLs(url, webUrl, baseItem.copy());
updateFromBase(outcome, currentBase);
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
outcome.setSlicing(null);
if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
if (diffpos < diffMatches.size() && diffMatches.get(diffpos).getSliceName().equals(outcome.getSliceName())) {
// if there's a diff, we update the outcome with diff
// no? updateFromDefinition(outcome, diffMatches.get(diffpos), profileName, closed, url);
// then process any children
int nbl = findEndOfElement(base, baseCursor);
int ndc = differential.getElement().indexOf(diffMatches.get(diffpos));
int ndl = findEndOfElement(differential, ndc);
// now we process the base scope repeatedly for each instance of the item in the differential list
processPaths(indent + " ", result, base, differential, baseCursor, ndc, nbl, ndl, url, webUrl, profileName + pathTail(diffMatches, diffpos), contextPathSrc, contextPathDst, closed, contextName, resultPathBase, true, redirector, srcSD);
// ok, done with that - now set the cursors for if this is the end
baseCursor = nbl;
diffCursor = ndl + 1;
diffpos++;
} else {
result.getElement().add(outcome);
baseCursor++;
// just copy any children on the base
while (baseCursor < base.getElement().size() && base.getElement().get(baseCursor).getPath().startsWith(path) && !base.getElement().get(baseCursor).getPath().equals(path)) {
outcome = updateURLs(url, webUrl, base.getElement().get(baseCursor).copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
result.getElement().add(outcome);
baseCursor++;
}
// Lloyd - add this for test T15
baseCursor--;
}
}
// finally, we process any remaining entries in diff, which are new (and which are only allowed if the base wasn't closed
if (closed && diffpos < diffMatches.size())
throw new DefinitionException("The base snapshot marks a slicing as closed, but the differential tries to extend it in " + profileName + " at " + path + " (" + cpath + ")");
if (diffpos == diffMatches.size()) {
// Lloyd This was causing problems w/ Telus
// diffCursor++;
} else {
while (diffpos < diffMatches.size()) {
ElementDefinition diffItem = diffMatches.get(diffpos);
for (ElementDefinition baseItem : baseMatches) if (baseItem.getSliceName().equals(diffItem.getSliceName()))
throw new DefinitionException("Named items are out of order in the slice");
outcome = updateURLs(url, webUrl, currentBase.copy());
// outcome = updateURLs(url, diffItem.copy());
outcome.setPath(fixedPathDest(contextPathDst, outcome.getPath(), redirector, contextPathSrc));
updateFromBase(outcome, currentBase);
outcome.setSlicing(null);
if (!outcome.getPath().startsWith(resultPathBase))
throw new DefinitionException("Adding wrong path");
result.getElement().add(outcome);
updateFromDefinition(outcome, diffItem, profileName, trimDifferential, url, srcSD);
removeStatusExtensions(outcome);
// --- LM Added this
diffCursor = differential.getElement().indexOf(diffItem) + 1;
if (!outcome.getType().isEmpty() && (/*outcome.getType().get(0).getCode().equals("Extension") || */
differential.getElement().size() > diffCursor) && outcome.getPath().contains(".") && isDataType(outcome.getType())) {
// don't want to do this for the root, since that's base, and we're already processing it
if (!baseWalksInto(base.getElement(), baseCursor)) {
if (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) {
if (outcome.getType().size() > 1)
for (TypeRefComponent t : outcome.getType()) {
if (!t.getCode().equals("Reference"))
throw new DefinitionException(diffMatches.get(0).getPath() + " has children (" + differential.getElement().get(diffCursor).getPath() + ") and multiple types (" + typeCode(outcome.getType()) + ") in profile " + profileName);
}
TypeRefComponent t = outcome.getType().get(0);
if (t.getCode().equals("BackboneElement")) {
int baseStart = base.getElement().indexOf(currentBase) + 1;
int baseMax = baseStart + 1;
while (baseMax < base.getElement().size() && base.getElement().get(baseMax).getPath().startsWith(currentBase.getPath() + ".")) baseMax++;
int start = diffCursor;
while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
processPaths(indent + " ", result, base, differential, baseStart, start - 1, baseMax - 1, diffCursor - 1, url, webUrl, profileName + pathTail(diffMatches, 0), base.getElement().get(0).getPath(), base.getElement().get(0).getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
} else {
StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
// }
if (dt == null)
throw new DefinitionException(diffMatches.get(0).getPath() + " has children (" + differential.getElement().get(diffCursor).getPath() + ") for type " + typeCode(outcome.getType()) + " in profile " + profileName + ", but can't find type");
contextName = dt.getUrl();
int start = diffCursor;
while (differential.getElement().size() > diffCursor && pathStartsWith(differential.getElement().get(diffCursor).getPath(), diffMatches.get(0).getPath() + ".")) diffCursor++;
processPaths(indent + " ", result, dt.getSnapshot(), differential, 1, /* starting again on the data type, but skip the root */
start - 1, dt.getSnapshot().getElement().size() - 1, diffCursor - 1, url, webUrl, profileName + pathTail(diffMatches, 0), diffMatches.get(0).getPath(), outcome.getPath(), trimDifferential, contextName, resultPathBase, false, redirector, srcSD);
}
} else if (outcome.getType().get(0).getCode().equals("Extension")) {
// Force URL to appear if we're dealing with an extension. (This is a kludge - may need to drill down in other cases where we're slicing and the type has a profile declaration that could be setting the fixed value)
StructureDefinition dt = getProfileForDataType(outcome.getType().get(0));
for (ElementDefinition extEd : dt.getSnapshot().getElement()) {
// We only want the children that aren't the root
if (extEd.getPath().contains(".")) {
ElementDefinition extUrlEd = updateURLs(url, webUrl, extEd.copy());
extUrlEd.setPath(fixedPathDest(outcome.getPath(), extUrlEd.getPath(), redirector, null));
// updateFromBase(extUrlEd, currentBase);
markDerived(extUrlEd);
result.getElement().add(extUrlEd);
}
}
}
}
}
// ---
diffpos++;
}
}
baseCursor++;
}
}
}
int i = 0;
for (ElementDefinition e : result.getElement()) {
i++;
if (e.hasMinElement() && e.getMinElement().getValue() == null)
throw new Error("null min");
}
return res;
}
use of org.hl7.fhir.r4b.model.BackboneElement in project org.hl7.fhir.core by hapifhir.
the class FHIRPathEngine method getChildTypesByName.
private void getChildTypesByName(String type, String name, TypeDetails result, ExpressionNode expr) throws PathEngineException, DefinitionException {
if (Utilities.noString(type)) {
throw makeException(expr, I18nConstants.FHIRPATH_NO_TYPE, "", "getChildTypesByName");
}
if (type.equals("http://hl7.org/fhir/StructureDefinition/xhtml")) {
return;
}
if (type.startsWith(Constants.NS_SYSTEM_TYPE)) {
return;
}
if (type.equals(TypeDetails.FP_SimpleTypeInfo)) {
getSimpleTypeChildTypesByName(name, result);
} else if (type.equals(TypeDetails.FP_ClassInfo)) {
getClassInfoChildTypesByName(name, result);
} else {
String url = null;
if (type.contains("#")) {
url = type.substring(0, type.indexOf("#"));
} else {
url = type;
}
String tail = "";
StructureDefinition sd = worker.fetchResource(StructureDefinition.class, url);
if (sd == null) {
throw makeException(expr, I18nConstants.FHIRPATH_NO_TYPE, url, "getChildTypesByName");
}
List<StructureDefinition> sdl = new ArrayList<StructureDefinition>();
ElementDefinitionMatch m = null;
if (type.contains("#"))
m = getElementDefinition(sd, type.substring(type.indexOf("#") + 1), false, expr);
if (m != null && hasDataType(m.definition)) {
if (m.fixedType != null) {
StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(m.fixedType, worker.getOverrideVersionNs()));
if (dt == null) {
throw makeException(expr, I18nConstants.FHIRPATH_NO_TYPE, ProfileUtilities.sdNs(m.fixedType, worker.getOverrideVersionNs()), "getChildTypesByName");
}
sdl.add(dt);
} else
for (TypeRefComponent t : m.definition.getType()) {
StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(t.getCode(), worker.getOverrideVersionNs()));
if (dt == null) {
throw makeException(expr, I18nConstants.FHIRPATH_NO_TYPE, ProfileUtilities.sdNs(t.getCode(), worker.getOverrideVersionNs()), "getChildTypesByName");
}
sdl.add(dt);
}
} else {
sdl.add(sd);
if (type.contains("#")) {
tail = type.substring(type.indexOf("#") + 1);
tail = tail.substring(tail.indexOf("."));
}
}
for (StructureDefinition sdi : sdl) {
String path = sdi.getSnapshot().getElement().get(0).getPath() + tail + ".";
if (name.equals("**")) {
assert (result.getCollectionStatus() == CollectionStatus.UNORDERED);
for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
if (ed.getPath().startsWith(path))
for (TypeRefComponent t : ed.getType()) {
if (t.hasCode() && t.getCodeElement().hasValue()) {
String tn = null;
if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) {
tn = sdi.getType() + "#" + ed.getPath();
} else {
tn = t.getCode();
}
if (t.getCode().equals("Resource")) {
for (String rn : worker.getResourceNames()) {
if (!result.hasType(worker, rn)) {
getChildTypesByName(result.addType(rn), "**", result, expr);
}
}
} else if (!result.hasType(worker, tn)) {
getChildTypesByName(result.addType(tn), "**", result, expr);
}
}
}
}
} else if (name.equals("*")) {
assert (result.getCollectionStatus() == CollectionStatus.UNORDERED);
for (ElementDefinition ed : sdi.getSnapshot().getElement()) {
if (ed.getPath().startsWith(path) && !ed.getPath().substring(path.length()).contains("."))
for (TypeRefComponent t : ed.getType()) {
if (Utilities.noString(t.getCode())) {
// Element.id or Extension.url
result.addType("System.string");
} else if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) {
result.addType(sdi.getType() + "#" + ed.getPath());
} else if (t.getCode().equals("Resource")) {
result.addTypes(worker.getResourceNames());
} else {
result.addType(t.getCode());
}
}
}
} else {
path = sdi.getSnapshot().getElement().get(0).getPath() + tail + "." + name;
ElementDefinitionMatch ed = getElementDefinition(sdi, path, isAllowPolymorphicNames(), expr);
if (ed != null) {
if (!Utilities.noString(ed.getFixedType()))
result.addType(ed.getFixedType());
else {
for (TypeRefComponent t : ed.getDefinition().getType()) {
if (Utilities.noString(t.getCode())) {
if (Utilities.existsInList(ed.getDefinition().getId(), "Element.id", "Extension.url") || Utilities.existsInList(ed.getDefinition().getBase().getPath(), "Resource.id", "Element.id", "Extension.url")) {
result.addType(TypeDetails.FP_NS, "string");
}
// throw new PathEngineException("Illegal reference to primitive value attribute @ "+path);
break;
}
ProfiledType pt = null;
if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) {
pt = new ProfiledType(sdi.getUrl() + "#" + path);
} else if (t.getCode().equals("Resource")) {
result.addTypes(worker.getResourceNames());
} else {
pt = new ProfiledType(t.getCode());
}
if (pt != null) {
if (t.hasProfile()) {
pt.addProfiles(t.getProfile());
}
if (ed.getDefinition().hasBinding()) {
pt.addBinding(ed.getDefinition().getBinding());
}
result.addType(pt);
}
}
}
}
}
}
}
}
use of org.hl7.fhir.r4b.model.BackboneElement in project kindling by HL7.
the class ProfileGenerator method defineElement.
/**
* note: snapshot implies that we are generating a resource or a data type; for other profiles, the snapshot is generated elsewhere
* @param isInterface
*/
private ElementDefinition defineElement(Profile ap, StructureDefinition p, List<ElementDefinition> elements, ElementDefn e, String path, Set<String> slices, List<SliceHandle> parentSlices, SnapShotMode snapshot, boolean root, String defType, String inheritedType, boolean defaults) throws Exception {
boolean handleDiscriminator = true;
if (!Utilities.noString(e.getProfileName()) && !e.getDiscriminator().isEmpty() && !slices.contains(path)) {
handleDiscriminator = false;
// hey, we jumped straight into the slices with setting up the slicing (allowed in the spreadsheets, but not otherwise)
ElementDefinition slicer = new ElementDefinition();
elements.add(slicer);
slicer.setId(path);
slicer.setPath(path);
processDiscriminator(e, path, slicer);
if (e.getMaxCardinality() != null)
slicer.setMax(e.getMaxCardinality() == Integer.MAX_VALUE ? "*" : e.getMaxCardinality().toString());
slices.add(path);
}
// todo for task 12259
// if (ap != null) {
// String base = isImplicitTypeConstraint(path);
// if (base != null) {
// ElementDefinition typeConstrainer = new ElementDefinition(ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
// elements.add(typeConstrainer);
// typeConstrainer.setId(base);
// typeConstrainer.setPath(base);
// String type = path.substring(base.length()-3);
// if (definitions.hasPrimitiveType(Utilities.uncapitalize(type)))
// type = Utilities.uncapitalize(type);
// typeConstrainer.addType().setCode(type);
// }
// }
ElementDefinition ce = new ElementDefinition(defaults, ElementDefinition.NOT_MODIFIER, ElementDefinition.NOT_IN_SUMMARY);
elements.add(ce);
if (e.getStandardsStatus() != null)
ToolingExtensions.setStandardsStatus(ce, e.getStandardsStatus(), e.getNormativeVersion());
ce.setId(path);
ce.setPath(path);
if (e.isXmlAttribute())
ce.addRepresentation(PropertyRepresentation.XMLATTR);
List<SliceHandle> myParents = new ArrayList<ProfileGenerator.SliceHandle>();
myParents.addAll(parentSlices);
// which holds Slicing information)
if (e.hasDescriminator() || !Utilities.noString(e.getProfileName())) {
if (e.getDiscriminator().size() > 0 && !slices.contains(path) && handleDiscriminator) {
processDiscriminator(e, path, ce);
slices.add(path);
}
if (!Utilities.noString(e.getProfileName())) {
SliceHandle hnd = new SliceHandle();
// though this it not used?
hnd.name = path;
myParents.add(hnd);
if (path.contains(".")) {
// We don't want a slice name on the root
ce.setSliceName(e.getProfileName());
ce.setId(ce.getId() + ":" + e.getProfileName());
}
}
}
if (e.isTranslatable()) {
ce.addExtension(BuildExtensions.EXT_TRANSLATABLE, new BooleanType(true));
}
if (Utilities.existsInList(ce.getPath(), "Element.extension", "DomainResource.extension", "DomainResource.modifierExtension") && !ce.hasSlicing() && !ce.hasSliceName()) {
ce.getSlicing().setDescription("Extensions are always sliced by (at least) url").setRules(SlicingRules.OPEN).addDiscriminator().setType(DiscriminatorType.VALUE).setPath("url");
}
if (!Utilities.noString(inheritedType) && snapshot != SnapShotMode.None) {
ElementDefn inh = definitions.getElementDefn(inheritedType);
buildDefinitionFromElement(path, ce, inh, ap, p, inheritedType, definitions.getBaseResources().containsKey(inheritedType) && definitions.getBaseResources().get(inheritedType).isInterface());
} else if (path.contains(".") && Utilities.noString(e.typeCode()) && snapshot != SnapShotMode.None) {
addElementConstraints(defType, ce);
}
buildDefinitionFromElement(path, ce, e, ap, p, null, false);
if (!Utilities.noString(e.getStatedType())) {
ToolingExtensions.addStringExtension(ce, "http://hl7.org/fhir/StructureDefinition/structuredefinition-explicit-type-name", e.getStatedType());
}
if (e.isNoBindingAllowed()) {
ToolingExtensions.addBooleanExtension(ce, BuildExtensions.EXT_NO_BINDING, true);
}
if (!root) {
if (e.typeCode().startsWith("@")) {
ce.setContentReference("#" + getIdForPath(elements, e.typeCode().substring(1)));
} else if (Utilities.existsInList(path, "Element.id", "Extension.url") || path.endsWith(".id")) {
TypeRefComponent tr = ce.addType();
tr.getFormatCommentsPre().add("Note: special primitive values have a FHIRPath system type. e.g. this is compiler magic (j)");
tr.setCode(Constants.NS_SYSTEM_TYPE + "String");
if (path.equals("Extension.url")) {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "uri");
} else if (p.getKind() == StructureDefinitionKind.RESOURCE) {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "id");
} else {
ToolingExtensions.addUriExtension(tr, ToolingExtensions.EXT_FHIR_TYPE, "string");
}
} else {
List<TypeRef> expandedTypes = new ArrayList<TypeRef>();
for (TypeRef t : e.getTypes()) {
// Expand any Resource(A|B|C) references
if (t.hasParams() && !Utilities.existsInList(t.getName(), "Reference", "canonical", "CodeableReference")) {
throw new Exception("Only resource types can specify parameters. Path " + path + " in profile " + p.getName());
}
if (t.getParams().size() > 1) {
if (t.getProfile() != null && t.getParams().size() != 1) {
throw new Exception("Cannot declare profile on a resource reference declaring multiple resource types. Path " + path + " in profile " + p.getName());
}
for (String param : t.getParams()) {
if (definitions.hasLogicalModel(param)) {
for (String pn : definitions.getLogicalModel(param).getImplementations()) {
TypeRef childType = new TypeRef(t.getName());
childType.getParams().add(pn);
childType.getAggregations().addAll(t.getAggregations());
expandedTypes.add(childType);
}
} else {
TypeRef childType = new TypeRef(t.getName());
childType.getParams().add(param);
childType.getAggregations().addAll(t.getAggregations());
expandedTypes.add(childType);
}
}
} else if (t.isWildcardType()) {
// this list is filled out manually because it may be running before the types referred to have been loaded
for (String n : TypesUtilities.wildcardTypes(version.toString())) expandedTypes.add(new TypeRef(n));
} else if (!t.getName().startsWith("=")) {
if (definitions.isLoaded() && (!definitions.hasResource(t.getName()) && !definitions.hasType(t.getName()) && !definitions.hasElementDefn(t.getName()) && !definitions.getBaseResources().containsKey(t.getName()) && !t.getName().equals("xhtml"))) {
throw new Exception("Bad Type '" + t.getName() + "' at " + path + " in profile " + p.getUrl());
}
expandedTypes.add(t);
}
}
if (expandedTypes.isEmpty()) {
if (defType != null)
ce.addType().setCode(defType);
} else
for (TypeRef t : expandedTypes) {
String profile = null;
String tc = null;
if (definitions.getConstraints().containsKey(t.getName())) {
ProfiledType pt = definitions.getConstraints().get(t.getName());
tc = pt.getBaseType();
profile = "http://hl7.org/fhir/StructureDefinition/" + pt.getName();
} else {
tc = t.getName();
profile = t.getProfile();
}
TypeRefComponent type = ce.getType(tc);
if (profile == null && t.hasParams()) {
profile = t.getParams().get(0);
}
if (t.getPatterns() != null) {
for (String s : t.getPatterns()) {
type.addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-pattern", new CanonicalType("http://hl7.org/fhir/StructureDefinition/" + s));
}
}
if (profile != null) {
if (type.getWorkingCode().equals("Extension")) {
// check that the extension is being used correctly:
StructureDefinition ext = context.getExtensionStructure(null, profile);
if (ext == null) {
throw new Exception("Unable to resolve extension definition: " + profile);
}
boolean srcMod = ext.getSnapshot().getElement().get(0).getIsModifier();
boolean tgtMod = e.isModifier();
if (srcMod && !tgtMod)
throw new Exception("The extension '" + profile + "' is a modifier extension, but is being used as if it is not a modifier extension");
if (!srcMod && tgtMod)
throw new Exception("The extension '" + profile + "' is not a modifier extension, but is being used as if it is a modifier extension");
}
List<String> pr = new ArrayList<>();
if (profile.startsWith("http:") || profile.startsWith("#")) {
pr.add(profile);
} else if (definitions.hasLogicalModel(profile)) {
for (String pn : definitions.getLogicalModel(profile).getImplementations()) pr.add("http://hl7.org/fhir/StructureDefinition/" + pn);
} else
pr.add("http://hl7.org/fhir/StructureDefinition/" + (profile.equals("Any") ? "Resource" : profile));
if (type.getWorkingCode().equals("Reference") || type.getWorkingCode().equals("canonical") || type.getWorkingCode().equals("CodeableReference")) {
for (String pn : pr) {
type.addTargetProfile(pn);
if (e.hasHierarchy())
ToolingExtensions.addBooleanExtension(type, ToolingExtensions.EXT_HIERARCHY, e.getHierarchy());
}
} else
for (String pn : pr) {
type.addProfile(pn);
}
}
for (String aggregation : t.getAggregations()) {
type.addAggregation(AggregationMode.fromCode(aggregation));
}
}
}
}
String w5 = translateW5(e.getW5());
if (w5 != null)
addMapping(p, ce, "http://hl7.org/fhir/fivews", w5, ap);
if (e.isTranslatable())
ce.addExtension("http://hl7.org/fhir/StructureDefinition/elementdefinition-translatable", new BooleanType(true));
if (!Utilities.noString(e.getOrderMeaning()))
ce.setOrderMeaning(e.getOrderMeaning());
if (e.hasBinding()) {
ce.setBinding(generateBinding(e.getBinding()));
}
if (snapshot != SnapShotMode.None && !e.getElements().isEmpty()) {
// makeExtensionSlice("extension", p, c, e, path);
// if (snapshot == SnapShotMode.Resource) {
// makeExtensionSlice("modifierExtension", p, c, e, path);
// if (!path.contains(".")) {
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("Resource").getRoot().getElementByName("language")));
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("DomainResource").getRoot().getElementByName("text")));
// c.getElement().add(createBaseDefinition(p, path, definitions.getBaseResources().get("DomainResource").getRoot().getElementByName("contained")));
// }
// }
}
if (defaults)
ce.makeBase();
Set<String> containedSlices = new HashSet<String>();
if (snapshot != SnapShotMode.None) {
if (!root && Utilities.noString(e.typeCode())) {
if (snapshot == SnapShotMode.Resource)
defineAncestorElements("BackboneElement", path, snapshot, containedSlices, p, elements, defType, defaults);
else
defineAncestorElements("Element", path, snapshot, containedSlices, p, elements, defType, defaults);
} else if (root && !Utilities.noString(e.typeCode()))
defineAncestorElements(e.typeCode(), path, snapshot, containedSlices, p, elements, defType, defaults);
}
for (ElementDefn child : e.getElements()) defineElement(ap, p, elements, child, path + "." + child.getName(), containedSlices, myParents, snapshot, false, defType, null, defaults);
return ce;
}
use of org.hl7.fhir.r4b.model.BackboneElement in project kindling by HL7.
the class ProfileGenerator method generateElementDefinition.
private void generateElementDefinition(StructureDefinition source, ElementDefinition ed, ElementDefinition parent) throws Exception {
String id = ed.getPath().replace("[x]", "X");
if (id.length() > 64)
id = id.substring(0, 64);
if (!id.contains("."))
// throw new Exception("Don't generate data element for root of resources or types");
return;
if (!ed.hasType())
// throw new Exception("Don't generate data element for reference elements");
return;
if (Utilities.existsInList(ed.getType().get(0).getCode(), "Element", "BackboneElement"))
// throw new Exception("Don't generate data element for elements that are not leaves");
return;
StructureDefinition de;
if (des.containsKey(id)) {
de = des.get("de-" + id);
// do it again because we now have more information to generate with
de.getSnapshot().getElement().clear();
de.getExtension().clear();
} else {
de = new StructureDefinition();
de.setId("de-" + id);
des.put(id, de);
de.setUrl("http://hl7.org/fhir/StructureDefinition/" + de.getId());
if (de.getId().contains("."))
definitions.addNs(de.getUrl(), "Data Element " + ed.getPath(), definitions.getSrcFile(id.substring(0, id.indexOf("."))) + "-definitions.html#" + id);
if (dataElements != null)
dataElements.addEntry().setResource(de).setFullUrl(de.getUrl());
}
if (!de.hasMeta())
de.setMeta(new Meta());
de.getMeta().setLastUpdatedElement(new InstantType(genDate));
de.setVersion(version.toCode());
de.setName(ed.getPath());
de.setStatus(PublicationStatus.DRAFT);
de.setExperimental(true);
de.setTitle(de.getName());
de.setDate(genDate.getTime());
de.setPublisher("HL7 FHIR Standard");
de.addContact().getTelecom().add(Factory.newContactPoint(ContactPointSystem.URL, "http://hl7.org/fhir"));
de.setDescription("Data Element for " + ed.getPath());
de.setPurpose("Data Elements are defined for each element to assist in questionnaire construction etc");
de.setFhirVersion(version);
de.setKind(StructureDefinitionKind.LOGICAL);
de.setType("DataElement");
de.setAbstract(false);
de.setType(de.getName());
de.setBaseDefinition("http://hl7.org/fhir/StructureDefinition/Element");
de.setDerivation(TypeDerivationRule.SPECIALIZATION);
de.getMapping().addAll(source.getMapping());
ElementDefinition ted = ed.copy();
de.getSnapshot().addElement(ted);
ted.makeBase();
}
Aggregations