001package ca.uhn.fhir.parser; 002 003/* 004 * #%L 005 * HAPI FHIR - Core Library 006 * %% 007 * Copyright (C) 2014 - 2020 University Health Network 008 * %% 009 * Licensed under the Apache License, Version 2.0 (the "License"); 010 * you may not use this file except in compliance with the License. 011 * You may obtain a copy of the License at 012 * 013 * http://www.apache.org/licenses/LICENSE-2.0 014 * 015 * Unless required by applicable law or agreed to in writing, software 016 * distributed under the License is distributed on an "AS IS" BASIS, 017 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 018 * See the License for the specific language governing permissions and 019 * limitations under the License. 020 * #L% 021 */ 022 023import ca.uhn.fhir.context.BaseRuntimeChildDefinition; 024import ca.uhn.fhir.context.BaseRuntimeDeclaredChildDefinition; 025import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition; 026import ca.uhn.fhir.context.BaseRuntimeElementDefinition; 027import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum; 028import ca.uhn.fhir.context.ConfigurationException; 029import ca.uhn.fhir.context.FhirContext; 030import ca.uhn.fhir.context.FhirVersionEnum; 031import ca.uhn.fhir.context.RuntimeChildChoiceDefinition; 032import ca.uhn.fhir.context.RuntimeChildContainedResources; 033import ca.uhn.fhir.context.RuntimeChildDirectResource; 034import ca.uhn.fhir.context.RuntimeChildNarrativeDefinition; 035import ca.uhn.fhir.context.RuntimeResourceDefinition; 036import ca.uhn.fhir.model.api.IIdentifiableElement; 037import ca.uhn.fhir.model.api.IResource; 038import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions; 039import ca.uhn.fhir.model.api.ResourceMetadataKeyEnum; 040import ca.uhn.fhir.model.api.Tag; 041import ca.uhn.fhir.model.api.TagList; 042import ca.uhn.fhir.model.primitive.IdDt; 043import ca.uhn.fhir.parser.path.EncodeContextPath; 044import ca.uhn.fhir.rest.api.Constants; 045import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; 046import ca.uhn.fhir.util.BundleUtil; 047import ca.uhn.fhir.util.UrlUtil; 048import com.google.common.base.Charsets; 049import org.apache.commons.lang3.StringUtils; 050import org.apache.commons.lang3.Validate; 051import org.hl7.fhir.instance.model.api.IAnyResource; 052import org.hl7.fhir.instance.model.api.IBase; 053import org.hl7.fhir.instance.model.api.IBaseBundle; 054import org.hl7.fhir.instance.model.api.IBaseCoding; 055import org.hl7.fhir.instance.model.api.IBaseElement; 056import org.hl7.fhir.instance.model.api.IBaseHasExtensions; 057import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions; 058import org.hl7.fhir.instance.model.api.IBaseMetaType; 059import org.hl7.fhir.instance.model.api.IBaseReference; 060import org.hl7.fhir.instance.model.api.IBaseResource; 061import org.hl7.fhir.instance.model.api.IDomainResource; 062import org.hl7.fhir.instance.model.api.IIdType; 063import org.hl7.fhir.instance.model.api.IPrimitiveType; 064 065import javax.annotation.Nullable; 066import java.io.IOException; 067import java.io.InputStream; 068import java.io.InputStreamReader; 069import java.io.Reader; 070import java.io.StringReader; 071import java.io.StringWriter; 072import java.io.Writer; 073import java.lang.reflect.Modifier; 074import java.util.ArrayList; 075import java.util.Arrays; 076import java.util.Collection; 077import java.util.Collections; 078import java.util.HashMap; 079import java.util.HashSet; 080import java.util.IdentityHashMap; 081import java.util.List; 082import java.util.Map; 083import java.util.Objects; 084import java.util.Set; 085import java.util.stream.Collectors; 086 087import static org.apache.commons.lang3.StringUtils.isBlank; 088import static org.apache.commons.lang3.StringUtils.isNotBlank; 089 090@SuppressWarnings("WeakerAccess") 091public abstract class BaseParser implements IParser { 092 093 /** 094 * Any resources that were created by the parser (i.e. by parsing a serialized resource) will have 095 * a {@link IBaseResource#getUserData(String) user data} property with this key. 096 * 097 * @since 5.0.0 098 */ 099 public static final String RESOURCE_CREATED_BY_PARSER = BaseParser.class.getName() + "_" + "RESOURCE_CREATED_BY_PARSER"; 100 101 private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(BaseParser.class); 102 103 private static final Set<String> notEncodeForContainedResource = new HashSet<>(Arrays.asList("security", "versionId", "lastUpdated")); 104 105 private ContainedResources myContainedResources; 106 private boolean myEncodeElementsAppliesToChildResourcesOnly; 107 private FhirContext myContext; 108 private List<EncodeContextPath> myDontEncodeElements; 109 private List<EncodeContextPath> myEncodeElements; 110 private Set<String> myEncodeElementsAppliesToResourceTypes; 111 private IIdType myEncodeForceResourceId; 112 private IParserErrorHandler myErrorHandler; 113 private boolean myOmitResourceId; 114 private List<Class<? extends IBaseResource>> myPreferTypes; 115 private String myServerBaseUrl; 116 private Boolean myStripVersionsFromReferences; 117 private Boolean myOverrideResourceIdWithBundleEntryFullUrl; 118 private boolean mySummaryMode; 119 private boolean mySuppressNarratives; 120 private Set<String> myDontStripVersionsFromReferencesAtPaths; 121 122 /** 123 * Constructor 124 */ 125 public BaseParser(FhirContext theContext, IParserErrorHandler theParserErrorHandler) { 126 myContext = theContext; 127 myErrorHandler = theParserErrorHandler; 128 } 129 130 List<EncodeContextPath> getDontEncodeElements() { 131 return myDontEncodeElements; 132 } 133 134 @Override 135 public IParser setDontEncodeElements(Set<String> theDontEncodeElements) { 136 if (theDontEncodeElements == null || theDontEncodeElements.isEmpty()) { 137 myDontEncodeElements = null; 138 } else { 139 myDontEncodeElements = theDontEncodeElements 140 .stream() 141 .map(EncodeContextPath::new) 142 .collect(Collectors.toList()); 143 } 144 return this; 145 } 146 147 List<EncodeContextPath> getEncodeElements() { 148 return myEncodeElements; 149 } 150 151 @Override 152 public IParser setEncodeElements(Set<String> theEncodeElements) { 153 154 if (theEncodeElements == null || theEncodeElements.isEmpty()) { 155 myEncodeElements = null; 156 myEncodeElementsAppliesToResourceTypes = null; 157 } else { 158 myEncodeElements = theEncodeElements 159 .stream() 160 .map(EncodeContextPath::new) 161 .collect(Collectors.toList()); 162 163 myEncodeElementsAppliesToResourceTypes = new HashSet<>(); 164 for (String next : myEncodeElements.stream().map(t -> t.getPath().get(0).getName()).collect(Collectors.toList())) { 165 if (next.startsWith("*")) { 166 myEncodeElementsAppliesToResourceTypes = null; 167 break; 168 } 169 int dotIdx = next.indexOf('.'); 170 if (dotIdx == -1) { 171 myEncodeElementsAppliesToResourceTypes.add(next); 172 } else { 173 myEncodeElementsAppliesToResourceTypes.add(next.substring(0, dotIdx)); 174 } 175 } 176 177 } 178 179 return this; 180 } 181 182 protected Iterable<CompositeChildElement> compositeChildIterator(IBase theCompositeElement, final boolean theContainedResource, final CompositeChildElement theParent, EncodeContext theEncodeContext) { 183 BaseRuntimeElementCompositeDefinition<?> elementDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theCompositeElement.getClass()); 184 return theEncodeContext.getCompositeChildrenCache().computeIfAbsent(new Key(elementDef, theContainedResource, theParent, theEncodeContext), (k) -> { 185 186 final List<BaseRuntimeChildDefinition> children = elementDef.getChildrenAndExtension(); 187 final List<CompositeChildElement> result = new ArrayList<>(children.size()); 188 189 for (final BaseRuntimeChildDefinition child : children) { 190 CompositeChildElement myNext = new CompositeChildElement(theParent, child, theEncodeContext); 191 192 /* 193 * There are lots of reasons we might skip encoding a particular child 194 */ 195 if (myNext.getDef().getElementName().equals("id")) { 196 continue; 197 } else if (!myNext.shouldBeEncoded(theContainedResource)) { 198 continue; 199 } else if (myNext.getDef() instanceof RuntimeChildNarrativeDefinition) { 200 if (isSuppressNarratives() || isSummaryMode()) { 201 continue; 202 } else if (theContainedResource) { 203 continue; 204 } 205 } else if (myNext.getDef() instanceof RuntimeChildContainedResources) { 206 if (theContainedResource) { 207 continue; 208 } 209 } 210 result.add(myNext); 211 } 212 return result; 213 }); 214 } 215 216 private void containResourcesForEncoding(ContainedResources theContained, IBaseResource theResource, IBaseResource theTarget) { 217 List<IBaseReference> allReferences = getAllBaseReferences(theResource); 218 for (IBaseReference next : allReferences) { 219 IBaseResource resource = next.getResource(); 220 if (resource == null && next.getReferenceElement().isLocal()) { 221 if (theContained.hasExistingIdToContainedResource()) { 222 IBaseResource potentialTarget = theContained.getExistingIdToContainedResource().remove(next.getReferenceElement().getValue()); 223 if (potentialTarget != null) { 224 theContained.addContained(next.getReferenceElement(), potentialTarget); 225 containResourcesForEncoding(theContained, potentialTarget, theTarget); 226 } 227 } 228 } 229 } 230 231 for (IBaseReference next : allReferences) { 232 IBaseResource resource = next.getResource(); 233 if (resource != null) { 234 if (resource.getIdElement().isEmpty() || resource.getIdElement().isLocal()) { 235 if (theContained.getResourceId(resource) != null) { 236 // Prevent infinite recursion if there are circular loops in the contained resources 237 continue; 238 } 239 theContained.addContained(resource); 240 if (resource.getIdElement().isLocal() && theContained.hasExistingIdToContainedResource()) { 241 theContained.getExistingIdToContainedResource().remove(resource.getIdElement().getValue()); 242 } 243 } else { 244 continue; 245 } 246 247 containResourcesForEncoding(theContained, resource, theTarget); 248 } 249 250 } 251 252 } 253 254 protected void containResourcesForEncoding(IBaseResource theResource) { 255 ContainedResources contained = new ContainedResources(); 256 257 if (theResource instanceof IResource) { 258 List<? extends IResource> containedResources = ((IResource) theResource).getContained().getContainedResources(); 259 for (IResource next : containedResources) { 260 String nextId = next.getId().getValue(); 261 if (StringUtils.isNotBlank(nextId)) { 262 if (!nextId.startsWith("#")) { 263 nextId = '#' + nextId; 264 } 265 contained.getExistingIdToContainedResource().put(nextId, next); 266 } 267 } 268 } else if (theResource instanceof IDomainResource) { 269 List<? extends IAnyResource> containedResources = ((IDomainResource) theResource).getContained(); 270 for (IAnyResource next : containedResources) { 271 String nextId = next.getIdElement().getValue(); 272 if (StringUtils.isNotBlank(nextId)) { 273 if (!nextId.startsWith("#")) { 274 nextId = '#' + nextId; 275 } 276 contained.getExistingIdToContainedResource().put(nextId, next); 277 } 278 } 279 } 280 281 containResourcesForEncoding(contained, theResource, theResource); 282 contained.assignIdsToContainedResources(); 283 myContainedResources = contained; 284 285 } 286 287 protected List<IBaseReference> getAllBaseReferences(IBaseResource theResource) { 288 final ArrayList<IBaseReference> retVal = new ArrayList<IBaseReference>(); 289 findBaseReferences(retVal, theResource, myContext.getResourceDefinition(theResource)); 290 return retVal; 291 } 292 293 /** 294 * A customised traversal of the tree to find the 'top level' base references. Nested references are found via the recursive traversal 295 * of contained resources. 296 */ 297 protected void findBaseReferences(List<IBaseReference> allElements, IBase theElement, BaseRuntimeElementDefinition<?> theDefinition) { 298 if (theElement instanceof IBaseReference) { 299 allElements.add((IBaseReference) theElement); 300 } 301 302 BaseRuntimeElementDefinition<?> def = theDefinition; 303 if (def.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) { 304 def = myContext.getElementDefinition(theElement.getClass()); 305 } 306 307 switch (def.getChildType()) { 308 case ID_DATATYPE: 309 case PRIMITIVE_XHTML_HL7ORG: 310 case PRIMITIVE_XHTML: 311 case PRIMITIVE_DATATYPE: 312 // These are primitive types 313 break; 314 case RESOURCE: 315 case RESOURCE_BLOCK: 316 case COMPOSITE_DATATYPE: { 317 BaseRuntimeElementCompositeDefinition<?> childDef = (BaseRuntimeElementCompositeDefinition<?>) def; 318 for (BaseRuntimeChildDefinition nextChild : childDef.getChildrenAndExtension()) { 319 320 List<?> values = nextChild.getAccessor().getValues(theElement); 321 if (values != null) { 322 for (Object nextValueObject : values) { 323 IBase nextValue; 324 try { 325 nextValue = (IBase) nextValueObject; 326 } catch (ClassCastException e) { 327 String s = "Found instance of " + nextValueObject.getClass() + " - Did you set a field value to the incorrect type? Expected " + IBase.class.getName(); 328 throw new ClassCastException(s); 329 } 330 if (nextValue == null) { 331 continue; 332 } 333 if (nextValue.isEmpty()) { 334 continue; 335 } 336 BaseRuntimeElementDefinition<?> childElementDef; 337 childElementDef = nextChild.getChildElementDefinitionByDatatype(nextValue.getClass()); 338 339 if (childElementDef == null) { 340 childElementDef = myContext.getElementDefinition(nextValue.getClass()); 341 } 342 343 if (nextChild instanceof RuntimeChildDirectResource) { 344 // Don't descend into embedded resources 345 if (nextValue instanceof IBaseReference) { 346 allElements.add((IBaseReference) nextValue); 347 } 348 } else { 349 findBaseReferences(allElements, nextValue, childElementDef); 350 } 351 } 352 } 353 } 354 break; 355 } 356 case CONTAINED_RESOURCES: 357 // skip contained resources when looking for resources to contain 358 break; 359 case CONTAINED_RESOURCE_LIST: 360 case EXTENSION_DECLARED: 361 case UNDECL_EXT: { 362 throw new IllegalStateException("state should not happen: " + def.getChildType()); 363 } 364 } 365 } 366 367 private String determineReferenceText(IBaseReference theRef, CompositeChildElement theCompositeChildElement) { 368 IIdType ref = theRef.getReferenceElement(); 369 if (isBlank(ref.getIdPart())) { 370 String reference = ref.getValue(); 371 if (theRef.getResource() != null) { 372 IIdType containedId = getContainedResources().getResourceId(theRef.getResource()); 373 if (containedId != null && !containedId.isEmpty()) { 374 if (containedId.isLocal()) { 375 reference = containedId.getValue(); 376 } else { 377 reference = "#" + containedId.getValue(); 378 } 379 } else { 380 IIdType refId = theRef.getResource().getIdElement(); 381 if (refId != null) { 382 if (refId.hasIdPart()) { 383 if (refId.getValue().startsWith("urn:")) { 384 reference = refId.getValue(); 385 } else { 386 if (!refId.hasResourceType()) { 387 refId = refId.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName()); 388 } 389 if (isStripVersionsFromReferences(theCompositeChildElement)) { 390 reference = refId.toVersionless().getValue(); 391 } else { 392 reference = refId.getValue(); 393 } 394 } 395 } 396 } 397 } 398 } 399 return reference; 400 } 401 if (!ref.hasResourceType() && !ref.isLocal() && theRef.getResource() != null) { 402 ref = ref.withResourceType(myContext.getResourceDefinition(theRef.getResource()).getName()); 403 } 404 if (isNotBlank(myServerBaseUrl) && StringUtils.equals(myServerBaseUrl, ref.getBaseUrl())) { 405 if (isStripVersionsFromReferences(theCompositeChildElement)) { 406 return ref.toUnqualifiedVersionless().getValue(); 407 } 408 return ref.toUnqualified().getValue(); 409 } 410 if (isStripVersionsFromReferences(theCompositeChildElement)) { 411 return ref.toVersionless().getValue(); 412 } 413 return ref.getValue(); 414 } 415 416 protected abstract void doEncodeResourceToWriter(IBaseResource theResource, Writer theWriter, EncodeContext theEncodeContext) throws IOException, DataFormatException; 417 418 protected abstract <T extends IBaseResource> T doParseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException; 419 420 @Override 421 public String encodeResourceToString(IBaseResource theResource) throws DataFormatException { 422 Writer stringWriter = new StringWriter(); 423 try { 424 encodeResourceToWriter(theResource, stringWriter); 425 } catch (IOException e) { 426 throw new Error("Encountered IOException during write to string - This should not happen!"); 427 } 428 return stringWriter.toString(); 429 } 430 431 @Override 432 public final void encodeResourceToWriter(IBaseResource theResource, Writer theWriter) throws IOException, DataFormatException { 433 EncodeContext encodeContext = new EncodeContext(); 434 435 encodeResourceToWriter(theResource, theWriter, encodeContext); 436 } 437 438 protected void encodeResourceToWriter(IBaseResource theResource, Writer theWriter, EncodeContext theEncodeContext) throws IOException { 439 Validate.notNull(theResource, "theResource can not be null"); 440 Validate.notNull(theWriter, "theWriter can not be null"); 441 Validate.notNull(theEncodeContext, "theEncodeContext can not be null"); 442 443 if (theResource.getStructureFhirVersionEnum() != myContext.getVersion().getVersion()) { 444 throw new IllegalArgumentException( 445 "This parser is for FHIR version " + myContext.getVersion().getVersion() + " - Can not encode a structure for version " + theResource.getStructureFhirVersionEnum()); 446 } 447 448 String resourceName = myContext.getResourceType(theResource); 449 theEncodeContext.pushPath(resourceName, true); 450 451 doEncodeResourceToWriter(theResource, theWriter, theEncodeContext); 452 453 theEncodeContext.popPath(); 454 } 455 456 private void filterCodingsWithNoCodeOrSystem(List<? extends IBaseCoding> tagList) { 457 for (int i = 0; i < tagList.size(); i++) { 458 if (isBlank(tagList.get(i).getCode()) && isBlank(tagList.get(i).getSystem())) { 459 tagList.remove(i); 460 i--; 461 } 462 } 463 } 464 465 protected IIdType fixContainedResourceId(String theValue) { 466 IIdType retVal = (IIdType) myContext.getElementDefinition("id").newInstance(); 467 if (StringUtils.isNotBlank(theValue) && theValue.charAt(0) == '#') { 468 retVal.setValue(theValue.substring(1)); 469 } else { 470 retVal.setValue(theValue); 471 } 472 return retVal; 473 } 474 475 @SuppressWarnings("unchecked") 476 ChildNameAndDef getChildNameAndDef(BaseRuntimeChildDefinition theChild, IBase theValue) { 477 Class<? extends IBase> type = theValue.getClass(); 478 String childName = theChild.getChildNameByDatatype(type); 479 BaseRuntimeElementDefinition<?> childDef = theChild.getChildElementDefinitionByDatatype(type); 480 if (childDef == null) { 481 // if (theValue instanceof IBaseExtension) { 482 // return null; 483 // } 484 485 /* 486 * For RI structures Enumeration class, this replaces the child def 487 * with the "code" one. This is messy, and presumably there is a better 488 * way.. 489 */ 490 BaseRuntimeElementDefinition<?> elementDef = myContext.getElementDefinition(type); 491 if (elementDef.getName().equals("code")) { 492 Class<? extends IBase> type2 = myContext.getElementDefinition("code").getImplementingClass(); 493 childDef = theChild.getChildElementDefinitionByDatatype(type2); 494 childName = theChild.getChildNameByDatatype(type2); 495 } 496 497 // See possibly the user has extended a built-in type without 498 // declaring it anywhere, as in XmlParserDstu3Test#testEncodeUndeclaredBlock 499 if (childDef == null) { 500 Class<?> nextSuperType = theValue.getClass(); 501 while (IBase.class.isAssignableFrom(nextSuperType) && childDef == null) { 502 if (Modifier.isAbstract(nextSuperType.getModifiers()) == false) { 503 BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition((Class<? extends IBase>) nextSuperType); 504 Class<?> nextChildType = def.getImplementingClass(); 505 childDef = theChild.getChildElementDefinitionByDatatype((Class<? extends IBase>) nextChildType); 506 childName = theChild.getChildNameByDatatype((Class<? extends IBase>) nextChildType); 507 } 508 nextSuperType = nextSuperType.getSuperclass(); 509 } 510 } 511 512 if (childDef == null) { 513 throwExceptionForUnknownChildType(theChild, type); 514 } 515 } 516 517 return new ChildNameAndDef(childName, childDef); 518 } 519 520 protected String getCompositeElementId(IBase theElement) { 521 String elementId = null; 522 if (!(theElement instanceof IBaseResource)) { 523 if (theElement instanceof IBaseElement) { 524 elementId = ((IBaseElement) theElement).getId(); 525 } else if (theElement instanceof IIdentifiableElement) { 526 elementId = ((IIdentifiableElement) theElement).getElementSpecificId(); 527 } 528 } 529 return elementId; 530 } 531 532 ContainedResources getContainedResources() { 533 return myContainedResources; 534 } 535 536 @Override 537 public Set<String> getDontStripVersionsFromReferencesAtPaths() { 538 return myDontStripVersionsFromReferencesAtPaths; 539 } 540 541 @Override 542 public IIdType getEncodeForceResourceId() { 543 return myEncodeForceResourceId; 544 } 545 546 @Override 547 public BaseParser setEncodeForceResourceId(IIdType theEncodeForceResourceId) { 548 myEncodeForceResourceId = theEncodeForceResourceId; 549 return this; 550 } 551 552 protected IParserErrorHandler getErrorHandler() { 553 return myErrorHandler; 554 } 555 556 protected List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> getExtensionMetadataKeys(IResource resource) { 557 List<Map.Entry<ResourceMetadataKeyEnum<?>, Object>> extensionMetadataKeys = new ArrayList<>(); 558 for (Map.Entry<ResourceMetadataKeyEnum<?>, Object> entry : resource.getResourceMetadata().entrySet()) { 559 if (entry.getKey() instanceof ResourceMetadataKeyEnum.ExtensionResourceMetadataKey) { 560 extensionMetadataKeys.add(entry); 561 } 562 } 563 564 return extensionMetadataKeys; 565 } 566 567 protected String getExtensionUrl(final String extensionUrl) { 568 String url = extensionUrl; 569 if (StringUtils.isNotBlank(extensionUrl) && StringUtils.isNotBlank(myServerBaseUrl)) { 570 url = !UrlUtil.isValid(extensionUrl) && extensionUrl.startsWith("/") ? myServerBaseUrl + extensionUrl : extensionUrl; 571 } 572 return url; 573 } 574 575 protected TagList getMetaTagsForEncoding(IResource theIResource, EncodeContext theEncodeContext) { 576 TagList tags = ResourceMetadataKeyEnum.TAG_LIST.get(theIResource); 577 if (shouldAddSubsettedTag(theEncodeContext)) { 578 tags = new TagList(tags); 579 tags.add(new Tag(getSubsettedCodeSystem(), Constants.TAG_SUBSETTED_CODE, subsetDescription())); 580 } 581 582 return tags; 583 } 584 585 @Override 586 public List<Class<? extends IBaseResource>> getPreferTypes() { 587 return myPreferTypes; 588 } 589 590 @Override 591 public void setPreferTypes(List<Class<? extends IBaseResource>> thePreferTypes) { 592 if (thePreferTypes != null) { 593 ArrayList<Class<? extends IBaseResource>> types = new ArrayList<>(); 594 for (Class<? extends IBaseResource> next : thePreferTypes) { 595 if (Modifier.isAbstract(next.getModifiers()) == false) { 596 types.add(next); 597 } 598 } 599 myPreferTypes = Collections.unmodifiableList(types); 600 } else { 601 myPreferTypes = thePreferTypes; 602 } 603 } 604 605 @SuppressWarnings("deprecation") 606 protected <T extends IPrimitiveType<String>> List<T> getProfileTagsForEncoding(IBaseResource theResource, List<T> theProfiles) { 607 switch (myContext.getAddProfileTagWhenEncoding()) { 608 case NEVER: 609 return theProfiles; 610 case ONLY_FOR_CUSTOM: 611 RuntimeResourceDefinition resDef = myContext.getResourceDefinition(theResource); 612 if (resDef.isStandardType()) { 613 return theProfiles; 614 } 615 break; 616 case ALWAYS: 617 break; 618 } 619 620 RuntimeResourceDefinition nextDef = myContext.getResourceDefinition(theResource); 621 String profile = nextDef.getResourceProfile(myServerBaseUrl); 622 if (isNotBlank(profile)) { 623 for (T next : theProfiles) { 624 if (profile.equals(next.getValue())) { 625 return theProfiles; 626 } 627 } 628 629 List<T> newList = new ArrayList<>(theProfiles); 630 631 BaseRuntimeElementDefinition<?> idElement = myContext.getElementDefinition("id"); 632 @SuppressWarnings("unchecked") 633 T newId = (T) idElement.newInstance(); 634 newId.setValue(profile); 635 636 newList.add(newId); 637 return newList; 638 } 639 640 return theProfiles; 641 } 642 643 protected String getServerBaseUrl() { 644 return myServerBaseUrl; 645 } 646 647 @Override 648 public Boolean getStripVersionsFromReferences() { 649 return myStripVersionsFromReferences; 650 } 651 652 /** 653 * If set to <code>true</code> (default is <code>false</code>), narratives will not be included in the encoded 654 * values. 655 * 656 * @deprecated Use {@link #isSuppressNarratives()} 657 */ 658 @Deprecated 659 public boolean getSuppressNarratives() { 660 return mySuppressNarratives; 661 } 662 663 protected boolean isChildContained(BaseRuntimeElementDefinition<?> childDef, boolean theIncludedResource) { 664 return (childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCES || childDef.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) && getContainedResources().isEmpty() == false 665 && theIncludedResource == false; 666 } 667 668 @Override 669 public boolean isEncodeElementsAppliesToChildResourcesOnly() { 670 return myEncodeElementsAppliesToChildResourcesOnly; 671 } 672 673 @Override 674 public void setEncodeElementsAppliesToChildResourcesOnly(boolean theEncodeElementsAppliesToChildResourcesOnly) { 675 myEncodeElementsAppliesToChildResourcesOnly = theEncodeElementsAppliesToChildResourcesOnly; 676 } 677 678 @Override 679 public boolean isOmitResourceId() { 680 return myOmitResourceId; 681 } 682 683 private boolean isOverrideResourceIdWithBundleEntryFullUrl() { 684 Boolean overrideResourceIdWithBundleEntryFullUrl = myOverrideResourceIdWithBundleEntryFullUrl; 685 if (overrideResourceIdWithBundleEntryFullUrl != null) { 686 return overrideResourceIdWithBundleEntryFullUrl; 687 } 688 689 return myContext.getParserOptions().isOverrideResourceIdWithBundleEntryFullUrl(); 690 } 691 692 private boolean isStripVersionsFromReferences(CompositeChildElement theCompositeChildElement) { 693 Boolean stripVersionsFromReferences = myStripVersionsFromReferences; 694 if (stripVersionsFromReferences != null) { 695 return stripVersionsFromReferences; 696 } 697 698 if (myContext.getParserOptions().isStripVersionsFromReferences() == false) { 699 return false; 700 } 701 702 Set<String> dontStripVersionsFromReferencesAtPaths = myDontStripVersionsFromReferencesAtPaths; 703 if (dontStripVersionsFromReferencesAtPaths != null) { 704 if (dontStripVersionsFromReferencesAtPaths.isEmpty() == false && theCompositeChildElement.anyPathMatches(dontStripVersionsFromReferencesAtPaths)) { 705 return false; 706 } 707 } 708 709 dontStripVersionsFromReferencesAtPaths = myContext.getParserOptions().getDontStripVersionsFromReferencesAtPaths(); 710 return dontStripVersionsFromReferencesAtPaths.isEmpty() != false || !theCompositeChildElement.anyPathMatches(dontStripVersionsFromReferencesAtPaths); 711 } 712 713 @Override 714 public boolean isSummaryMode() { 715 return mySummaryMode; 716 } 717 718 /** 719 * If set to <code>true</code> (default is <code>false</code>), narratives will not be included in the encoded 720 * values. 721 * 722 * @since 1.2 723 */ 724 public boolean isSuppressNarratives() { 725 return mySuppressNarratives; 726 } 727 728 @Override 729 public IBaseResource parseResource(InputStream theInputStream) throws DataFormatException { 730 return parseResource(new InputStreamReader(theInputStream, Charsets.UTF_8)); 731 } 732 733 @Override 734 public <T extends IBaseResource> T parseResource(Class<T> theResourceType, InputStream theInputStream) throws DataFormatException { 735 return parseResource(theResourceType, new InputStreamReader(theInputStream, Constants.CHARSET_UTF8)); 736 } 737 738 @Override 739 public <T extends IBaseResource> T parseResource(Class<T> theResourceType, Reader theReader) throws DataFormatException { 740 741 /* 742 * We do this so that the context can verify that the structure is for 743 * the correct FHIR version 744 */ 745 if (theResourceType != null) { 746 myContext.getResourceDefinition(theResourceType); 747 } 748 749 // Actually do the parse 750 T retVal = doParseResource(theResourceType, theReader); 751 752 RuntimeResourceDefinition def = myContext.getResourceDefinition(retVal); 753 if ("Bundle".equals(def.getName())) { 754 755 if (isOverrideResourceIdWithBundleEntryFullUrl()) { 756 BundleUtil.processEntries(myContext, (IBaseBundle) retVal, t -> { 757 String fullUrl = t.getFullUrl(); 758 if (fullUrl != null) { 759 IBaseResource resource = t.getResource(); 760 if (resource != null) { 761 IIdType resourceId = resource.getIdElement(); 762 if (isBlank(resourceId.getValue())) { 763 resourceId.setValue(fullUrl); 764 } else { 765 if (fullUrl.startsWith("urn:") && fullUrl.endsWith(":" + resourceId.getIdPart())) { 766 resourceId.setValue(fullUrl); 767 } else { 768 IIdType fullUrlId = myContext.getVersion().newIdType(); 769 fullUrlId.setValue(fullUrl); 770 if (myContext.getVersion().getVersion().isOlderThan(FhirVersionEnum.DSTU3)) { 771 IIdType newId = fullUrlId; 772 if (!newId.hasVersionIdPart() && resourceId.hasVersionIdPart()) { 773 newId = newId.withVersion(resourceId.getVersionIdPart()); 774 } 775 resourceId.setValue(newId.getValue()); 776 } else if (StringUtils.equals(fullUrlId.getIdPart(), resourceId.getIdPart())) { 777 if (fullUrlId.hasBaseUrl()) { 778 IIdType newResourceId = resourceId.withServerBase(fullUrlId.getBaseUrl(), resourceId.getResourceType()); 779 resourceId.setValue(newResourceId.getValue()); 780 } 781 } 782 } 783 } 784 } 785 } 786 }); 787 } 788 789 } 790 791 return retVal; 792 } 793 794 @SuppressWarnings("cast") 795 @Override 796 public <T extends IBaseResource> T parseResource(Class<T> theResourceType, String theMessageString) { 797 StringReader reader = new StringReader(theMessageString); 798 return parseResource(theResourceType, reader); 799 } 800 801 @Override 802 public IBaseResource parseResource(Reader theReader) throws ConfigurationException, DataFormatException { 803 return parseResource(null, theReader); 804 } 805 806 @Override 807 public IBaseResource parseResource(String theMessageString) throws ConfigurationException, DataFormatException { 808 return parseResource(null, theMessageString); 809 } 810 811 protected List<? extends IBase> preProcessValues(BaseRuntimeChildDefinition theMetaChildUncast, IBaseResource theResource, List<? extends IBase> theValues, 812 CompositeChildElement theCompositeChildElement, EncodeContext theEncodeContext) { 813 if (myContext.getVersion().getVersion().isRi()) { 814 815 /* 816 * If we're encoding the meta tag, we do some massaging of the meta values before 817 * encoding. But if there is no meta element at all, we create one since we're possibly going to be 818 * adding things to it 819 */ 820 if (theValues.isEmpty() && theMetaChildUncast.getElementName().equals("meta")) { 821 BaseRuntimeElementDefinition<?> metaChild = theMetaChildUncast.getChildByName("meta"); 822 if (IBaseMetaType.class.isAssignableFrom(metaChild.getImplementingClass())) { 823 IBaseMetaType newType = (IBaseMetaType) metaChild.newInstance(); 824 theValues = Collections.singletonList(newType); 825 } 826 } 827 828 if (theValues.size() == 1 && theValues.get(0) instanceof IBaseMetaType) { 829 830 IBaseMetaType metaValue = (IBaseMetaType) theValues.get(0); 831 try { 832 metaValue = (IBaseMetaType) metaValue.getClass().getMethod("copy").invoke(metaValue); 833 } catch (Exception e) { 834 throw new InternalErrorException("Failed to duplicate meta", e); 835 } 836 837 if (isBlank(metaValue.getVersionId())) { 838 if (theResource.getIdElement().hasVersionIdPart()) { 839 metaValue.setVersionId(theResource.getIdElement().getVersionIdPart()); 840 } 841 } 842 843 filterCodingsWithNoCodeOrSystem(metaValue.getTag()); 844 filterCodingsWithNoCodeOrSystem(metaValue.getSecurity()); 845 846 List<? extends IPrimitiveType<String>> newProfileList = getProfileTagsForEncoding(theResource, metaValue.getProfile()); 847 List<? extends IPrimitiveType<String>> oldProfileList = metaValue.getProfile(); 848 if (oldProfileList != newProfileList) { 849 oldProfileList.clear(); 850 for (IPrimitiveType<String> next : newProfileList) { 851 if (isNotBlank(next.getValue())) { 852 metaValue.addProfile(next.getValue()); 853 } 854 } 855 } 856 857 if (shouldAddSubsettedTag(theEncodeContext)) { 858 IBaseCoding coding = metaValue.addTag(); 859 coding.setCode(Constants.TAG_SUBSETTED_CODE); 860 coding.setSystem(getSubsettedCodeSystem()); 861 coding.setDisplay(subsetDescription()); 862 } 863 864 return Collections.singletonList(metaValue); 865 } 866 } 867 868 @SuppressWarnings("unchecked") 869 List<IBase> retVal = (List<IBase>) theValues; 870 871 for (int i = 0; i < retVal.size(); i++) { 872 IBase next = retVal.get(i); 873 874 /* 875 * If we have automatically contained any resources via 876 * their references, this ensures that we output the new 877 * local reference 878 */ 879 if (next instanceof IBaseReference) { 880 IBaseReference nextRef = (IBaseReference) next; 881 String refText = determineReferenceText(nextRef, theCompositeChildElement); 882 if (!StringUtils.equals(refText, nextRef.getReferenceElement().getValue())) { 883 884 if (retVal == theValues) { 885 retVal = new ArrayList<>(theValues); 886 } 887 IBaseReference newRef = (IBaseReference) myContext.getElementDefinition(nextRef.getClass()).newInstance(); 888 myContext.newTerser().cloneInto(nextRef, newRef, true); 889 newRef.setReference(refText); 890 retVal.set(i, newRef); 891 892 } 893 } 894 } 895 896 return retVal; 897 } 898 899 private String getSubsettedCodeSystem() { 900 if (myContext.getVersion().getVersion().isEqualOrNewerThan(FhirVersionEnum.R4)) { 901 return Constants.TAG_SUBSETTED_SYSTEM_R4; 902 } else { 903 return Constants.TAG_SUBSETTED_SYSTEM_DSTU3; 904 } 905 } 906 907 @Override 908 public IParser setDontStripVersionsFromReferencesAtPaths(String... thePaths) { 909 if (thePaths == null) { 910 setDontStripVersionsFromReferencesAtPaths((List<String>) null); 911 } else { 912 setDontStripVersionsFromReferencesAtPaths(Arrays.asList(thePaths)); 913 } 914 return this; 915 } 916 917 @SuppressWarnings("unchecked") 918 @Override 919 public IParser setDontStripVersionsFromReferencesAtPaths(Collection<String> thePaths) { 920 if (thePaths == null) { 921 myDontStripVersionsFromReferencesAtPaths = Collections.emptySet(); 922 } else if (thePaths instanceof HashSet) { 923 myDontStripVersionsFromReferencesAtPaths = (Set<String>) ((HashSet<String>) thePaths).clone(); 924 } else { 925 myDontStripVersionsFromReferencesAtPaths = new HashSet<>(thePaths); 926 } 927 return this; 928 } 929 930 @Override 931 public IParser setOmitResourceId(boolean theOmitResourceId) { 932 myOmitResourceId = theOmitResourceId; 933 return this; 934 } 935 936 @Override 937 public IParser setOverrideResourceIdWithBundleEntryFullUrl(Boolean theOverrideResourceIdWithBundleEntryFullUrl) { 938 myOverrideResourceIdWithBundleEntryFullUrl = theOverrideResourceIdWithBundleEntryFullUrl; 939 return this; 940 } 941 942 @Override 943 public IParser setParserErrorHandler(IParserErrorHandler theErrorHandler) { 944 Validate.notNull(theErrorHandler, "theErrorHandler must not be null"); 945 myErrorHandler = theErrorHandler; 946 return this; 947 } 948 949 @Override 950 public IParser setServerBaseUrl(String theUrl) { 951 myServerBaseUrl = isNotBlank(theUrl) ? theUrl : null; 952 return this; 953 } 954 955 @Override 956 public IParser setStripVersionsFromReferences(Boolean theStripVersionsFromReferences) { 957 myStripVersionsFromReferences = theStripVersionsFromReferences; 958 return this; 959 } 960 961 @Override 962 public IParser setSummaryMode(boolean theSummaryMode) { 963 mySummaryMode = theSummaryMode; 964 return this; 965 } 966 967 @Override 968 public IParser setSuppressNarratives(boolean theSuppressNarratives) { 969 mySuppressNarratives = theSuppressNarratives; 970 return this; 971 } 972 973 protected boolean shouldAddSubsettedTag(EncodeContext theEncodeContext) { 974 if (isSummaryMode()) { 975 return true; 976 } 977 if (isSuppressNarratives()) { 978 return true; 979 } 980 if (myEncodeElements != null) { 981 if (isEncodeElementsAppliesToChildResourcesOnly() && theEncodeContext.getResourcePath().size() < 2) { 982 return false; 983 } 984 985 String currentResourceName = theEncodeContext.getResourcePath().get(theEncodeContext.getResourcePath().size() - 1).getName(); 986 return myEncodeElementsAppliesToResourceTypes == null || myEncodeElementsAppliesToResourceTypes.contains(currentResourceName); 987 } 988 989 return false; 990 } 991 992 protected boolean shouldEncodeResourceId(IBaseResource theResource, EncodeContext theEncodeContext) { 993 boolean retVal = true; 994 if (isOmitResourceId()) { 995 retVal = false; 996 } else { 997 if (myDontEncodeElements != null) { 998 String resourceName = myContext.getResourceType(theResource); 999 if (myDontEncodeElements.stream().anyMatch(t -> t.equalsPath(resourceName + ".id"))) { 1000 retVal = false; 1001 } else if (myDontEncodeElements.stream().anyMatch(t -> t.equalsPath("*.id"))) { 1002 retVal = false; 1003 } else if (theEncodeContext.getResourcePath().size() == 1 && myDontEncodeElements.stream().anyMatch(t -> t.equalsPath("id"))) { 1004 retVal = false; 1005 } 1006 } 1007 } 1008 return retVal; 1009 } 1010 1011 /** 1012 * Used for DSTU2 only 1013 */ 1014 protected boolean shouldEncodeResourceMeta(IResource theResource) { 1015 return shouldEncodePath(theResource, "meta"); 1016 } 1017 1018 /** 1019 * Used for DSTU2 only 1020 */ 1021 protected boolean shouldEncodePath(IResource theResource, String thePath) { 1022 if (myDontEncodeElements != null) { 1023 String resourceName = myContext.getResourceType(theResource); 1024 if (myDontEncodeElements.stream().anyMatch(t -> t.equalsPath(resourceName + "." + thePath))) { 1025 return false; 1026 } else return myDontEncodeElements.stream().noneMatch(t -> t.equalsPath("*." + thePath)); 1027 } 1028 return true; 1029 } 1030 1031 private String subsetDescription() { 1032 return "Resource encoded in summary mode"; 1033 } 1034 1035 protected void throwExceptionForUnknownChildType(BaseRuntimeChildDefinition nextChild, Class<? extends IBase> theType) { 1036 if (nextChild instanceof BaseRuntimeDeclaredChildDefinition) { 1037 StringBuilder b = new StringBuilder(); 1038 b.append(nextChild.getElementName()); 1039 b.append(" has type "); 1040 b.append(theType.getName()); 1041 b.append(" but this is not a valid type for this element"); 1042 if (nextChild instanceof RuntimeChildChoiceDefinition) { 1043 RuntimeChildChoiceDefinition choice = (RuntimeChildChoiceDefinition) nextChild; 1044 b.append(" - Expected one of: " + choice.getValidChildTypes()); 1045 } 1046 throw new DataFormatException(b.toString()); 1047 } 1048 throw new DataFormatException(nextChild + " has no child of type " + theType); 1049 } 1050 1051 protected boolean shouldEncodeResource(String theName) { 1052 if (myDontEncodeElements != null) { 1053 for (EncodeContextPath next : myDontEncodeElements) { 1054 if (next.equalsPath(theName)) { 1055 return false; 1056 } 1057 } 1058 } 1059 return true; 1060 } 1061 1062 class ChildNameAndDef { 1063 1064 private final BaseRuntimeElementDefinition<?> myChildDef; 1065 private final String myChildName; 1066 1067 public ChildNameAndDef(String theChildName, BaseRuntimeElementDefinition<?> theChildDef) { 1068 myChildName = theChildName; 1069 myChildDef = theChildDef; 1070 } 1071 1072 public BaseRuntimeElementDefinition<?> getChildDef() { 1073 return myChildDef; 1074 } 1075 1076 public String getChildName() { 1077 return myChildName; 1078 } 1079 1080 } 1081 1082 /** 1083 * EncodeContext is a shared state object that is passed around the 1084 * encode process 1085 */ 1086 public class EncodeContext extends EncodeContextPath { 1087 private final Map<Key, List<BaseParser.CompositeChildElement>> myCompositeChildrenCache = new HashMap<>(); 1088 1089 public Map<Key, List<BaseParser.CompositeChildElement>> getCompositeChildrenCache() { 1090 return myCompositeChildrenCache; 1091 } 1092 1093 } 1094 1095 1096 protected class CompositeChildElement { 1097 private final BaseRuntimeChildDefinition myDef; 1098 private final CompositeChildElement myParent; 1099 private final RuntimeResourceDefinition myResDef; 1100 private final EncodeContext myEncodeContext; 1101 1102 public CompositeChildElement(CompositeChildElement theParent, @Nullable BaseRuntimeChildDefinition theDef, EncodeContext theEncodeContext) { 1103 myDef = theDef; 1104 myParent = theParent; 1105 myResDef = null; 1106 myEncodeContext = theEncodeContext; 1107 1108 if (ourLog.isTraceEnabled()) { 1109 if (theParent != null) { 1110 StringBuilder path = theParent.buildPath(); 1111 if (path != null) { 1112 path.append('.'); 1113 if (myDef != null) { 1114 path.append(myDef.getElementName()); 1115 } 1116 ourLog.trace(" * Next path: {}", path.toString()); 1117 } 1118 } 1119 } 1120 1121 } 1122 1123 public CompositeChildElement(RuntimeResourceDefinition theResDef, EncodeContext theEncodeContext) { 1124 myResDef = theResDef; 1125 myDef = null; 1126 myParent = null; 1127 myEncodeContext = theEncodeContext; 1128 } 1129 1130 private void addParent(CompositeChildElement theParent, StringBuilder theB) { 1131 if (theParent != null) { 1132 if (theParent.myResDef != null) { 1133 theB.append(theParent.myResDef.getName()); 1134 return; 1135 } 1136 1137 if (theParent.myParent != null) { 1138 addParent(theParent.myParent, theB); 1139 } 1140 1141 if (theParent.myDef != null) { 1142 if (theB.length() > 0) { 1143 theB.append('.'); 1144 } 1145 theB.append(theParent.myDef.getElementName()); 1146 } 1147 } 1148 } 1149 1150 public boolean anyPathMatches(Set<String> thePaths) { 1151 StringBuilder b = new StringBuilder(); 1152 addParent(this, b); 1153 1154 String path = b.toString(); 1155 return thePaths.contains(path); 1156 } 1157 1158 private StringBuilder buildPath() { 1159 if (myResDef != null) { 1160 StringBuilder b = new StringBuilder(); 1161 b.append(myResDef.getName()); 1162 return b; 1163 } else if (myParent != null) { 1164 StringBuilder b = myParent.buildPath(); 1165 if (b != null && myDef != null) { 1166 b.append('.'); 1167 b.append(myDef.getElementName()); 1168 } 1169 return b; 1170 } else { 1171 return null; 1172 } 1173 } 1174 1175 private boolean checkIfParentShouldBeEncodedAndBuildPath() { 1176 List<EncodeContextPath> encodeElements = myEncodeElements; 1177 1178 String currentResourceName = myEncodeContext.getResourcePath().get(myEncodeContext.getResourcePath().size() - 1).getName(); 1179 if (myEncodeElementsAppliesToResourceTypes != null && !myEncodeElementsAppliesToResourceTypes.contains(currentResourceName)) { 1180 encodeElements = null; 1181 } 1182 1183 boolean retVal = checkIfPathMatchesForEncoding(encodeElements, true); 1184 1185 /* 1186 * We force the meta tag to be encoded even if it's not specified as an element in the 1187 * elements filter, specifically because we'll need it in order to automatically add 1188 * the SUBSETTED tag 1189 */ 1190 if (!retVal) { 1191 if ("meta".equals(myEncodeContext.getLeafResourcePathFirstField()) && shouldAddSubsettedTag(myEncodeContext)) { 1192 // The next element is a child of the <meta> element 1193 retVal = true; 1194 } else if ("meta".equals(myDef.getElementName()) && shouldAddSubsettedTag(myEncodeContext)) { 1195 // The next element is the <meta> element 1196 retVal = true; 1197 } 1198 } 1199 1200 return retVal; 1201 } 1202 1203 private boolean checkIfParentShouldNotBeEncodedAndBuildPath() { 1204 return checkIfPathMatchesForEncoding(myDontEncodeElements, false); 1205 } 1206 1207 private boolean checkIfPathMatchesForEncoding(List<EncodeContextPath> theElements, boolean theCheckingForEncodeElements) { 1208 1209 boolean retVal = false; 1210 if (myDef != null) { 1211 myEncodeContext.pushPath(myDef.getElementName(), false); 1212 } 1213 1214 if (theCheckingForEncodeElements && isEncodeElementsAppliesToChildResourcesOnly() && myEncodeContext.getResourcePath().size() < 2) { 1215 retVal = true; 1216 } else if (theElements == null) { 1217 retVal = true; 1218 } else { 1219 EncodeContextPath currentResourcePath = myEncodeContext.getCurrentResourcePath(); 1220 ourLog.trace("Current resource path: {}", currentResourcePath); 1221 for (EncodeContextPath next : theElements) { 1222 1223 if (next.startsWith(currentResourcePath, true)) { 1224 if (theCheckingForEncodeElements || next.getPath().size() == currentResourcePath.getPath().size()) { 1225 retVal = true; 1226 break; 1227 } 1228 } 1229 1230 if (next.getPath().get(next.getPath().size() - 1).getName().equals("(mandatory)")) { 1231 if (myDef.getMin() > 0) { 1232 retVal = true; 1233 break; 1234 } 1235 if (currentResourcePath.getPath().size() > next.getPath().size()) { 1236 retVal = true; 1237 break; 1238 } 1239 } 1240 1241 } 1242 } 1243 1244 if (myDef != null) { 1245 myEncodeContext.popPath(); 1246 } 1247 1248 return retVal; 1249 } 1250 1251 public BaseRuntimeChildDefinition getDef() { 1252 return myDef; 1253 } 1254 1255 public CompositeChildElement getParent() { 1256 return myParent; 1257 } 1258 1259 public boolean shouldBeEncoded(boolean theContainedResource) { 1260 boolean retVal = true; 1261 if (myEncodeElements != null) { 1262 retVal = checkIfParentShouldBeEncodedAndBuildPath(); 1263 } 1264 if (retVal && myDontEncodeElements != null) { 1265 retVal = !checkIfParentShouldNotBeEncodedAndBuildPath(); 1266 } 1267 if (theContainedResource) { 1268 retVal = !notEncodeForContainedResource.contains(myDef.getElementName()); 1269 } 1270 if (retVal && isSummaryMode() && (getDef() == null || !getDef().isSummary())) { 1271 String resourceName = myEncodeContext.getLeafResourceName(); 1272 // Technically the spec says we shouldn't include extensions in CapabilityStatement 1273 // but we will do so because there are people who depend on this behaviour, at least 1274 // as of 2019-07. See 1275 // https://github.com/smart-on-fhir/Swift-FHIR/issues/26 1276 // for example. 1277 if (("Conformance".equals(resourceName) || "CapabilityStatement".equals(resourceName)) && 1278 ("extension".equals(myDef.getElementName()) || "extension".equals(myEncodeContext.getLeafElementName()) 1279 )) { 1280 // skip 1281 } else { 1282 retVal = false; 1283 } 1284 } 1285 1286 return retVal; 1287 } 1288 1289 @Override 1290 public int hashCode() { 1291 final int prime = 31; 1292 int result = 1; 1293 result = prime * result + ((myDef == null) ? 0 : myDef.hashCode()); 1294 result = prime * result + ((myParent == null) ? 0 : myParent.hashCode()); 1295 result = prime * result + ((myResDef == null) ? 0 : myResDef.hashCode()); 1296 result = prime * result + ((myEncodeContext == null) ? 0 : myEncodeContext.hashCode()); 1297 return result; 1298 } 1299 1300 @Override 1301 public boolean equals(Object obj) { 1302 if (this == obj) 1303 return true; 1304 1305 if (obj instanceof CompositeChildElement) { 1306 final CompositeChildElement that = (CompositeChildElement) obj; 1307 return Objects.equals(this.getEnclosingInstance(), that.getEnclosingInstance()) && 1308 Objects.equals(this.myDef, that.myDef) && 1309 Objects.equals(this.myParent, that.myParent) && 1310 Objects.equals(this.myResDef, that.myResDef) && 1311 Objects.equals(this.myEncodeContext, that.myEncodeContext); 1312 } 1313 return false; 1314 } 1315 1316 private BaseParser getEnclosingInstance() { 1317 return BaseParser.this; 1318 } 1319 } 1320 1321 private static class Key { 1322 private final BaseRuntimeElementCompositeDefinition<?> resDef; 1323 private final boolean theContainedResource; 1324 private final BaseParser.CompositeChildElement theParent; 1325 private final BaseParser.EncodeContext theEncodeContext; 1326 1327 public Key(BaseRuntimeElementCompositeDefinition<?> resDef, final boolean theContainedResource, final BaseParser.CompositeChildElement theParent, BaseParser.EncodeContext theEncodeContext) { 1328 this.resDef = resDef; 1329 this.theContainedResource = theContainedResource; 1330 this.theParent = theParent; 1331 this.theEncodeContext = theEncodeContext; 1332 } 1333 1334 @Override 1335 public int hashCode() { 1336 final int prime = 31; 1337 int result = 1; 1338 result = prime * result + ((resDef == null) ? 0 : resDef.hashCode()); 1339 result = prime * result + (theContainedResource ? 1231 : 1237); 1340 result = prime * result + ((theParent == null) ? 0 : theParent.hashCode()); 1341 result = prime * result + ((theEncodeContext == null) ? 0 : theEncodeContext.hashCode()); 1342 return result; 1343 } 1344 1345 @Override 1346 public boolean equals(final Object obj) { 1347 if (this == obj) { 1348 return true; 1349 } 1350 if (obj instanceof Key) { 1351 final Key that = (Key) obj; 1352 return Objects.equals(this.resDef, that.resDef) && 1353 this.theContainedResource == that.theContainedResource && 1354 Objects.equals(this.theParent, that.theParent) && 1355 Objects.equals(this.theEncodeContext, that.theEncodeContext); 1356 } 1357 return false; 1358 } 1359 } 1360 1361 1362 static class ContainedResources { 1363 private long myNextContainedId = 1; 1364 1365 private List<IBaseResource> myResourceList; 1366 private IdentityHashMap<IBaseResource, IIdType> myResourceToIdMap; 1367 private Map<String, IBaseResource> myExistingIdToContainedResourceMap; 1368 1369 public Map<String, IBaseResource> getExistingIdToContainedResource() { 1370 if (myExistingIdToContainedResourceMap == null) { 1371 myExistingIdToContainedResourceMap = new HashMap<>(); 1372 } 1373 return myExistingIdToContainedResourceMap; 1374 } 1375 1376 public void addContained(IBaseResource theResource) { 1377 if (getResourceToIdMap().containsKey(theResource)) { 1378 return; 1379 } 1380 1381 IIdType newId; 1382 if (theResource.getIdElement().isLocal()) { 1383 newId = theResource.getIdElement(); 1384 } else { 1385 newId = null; 1386 } 1387 1388 getResourceToIdMap().put(theResource, newId); 1389 getResourceList().add(theResource); 1390 } 1391 1392 public void addContained(IIdType theId, IBaseResource theResource) { 1393 if (!getResourceToIdMap().containsKey(theResource)) { 1394 getResourceToIdMap().put(theResource, theId); 1395 getResourceList().add(theResource); 1396 } 1397 } 1398 1399 public List<IBaseResource> getContainedResources() { 1400 if (getResourceToIdMap() == null) { 1401 return Collections.emptyList(); 1402 } 1403 return getResourceList(); 1404 } 1405 1406 public IIdType getResourceId(IBaseResource theNext) { 1407 if (getResourceToIdMap() == null) { 1408 return null; 1409 } 1410 return getResourceToIdMap().get(theNext); 1411 } 1412 1413 private List<IBaseResource> getResourceList() { 1414 if (myResourceList == null) { 1415 myResourceList = new ArrayList<>(); 1416 } 1417 return myResourceList; 1418 } 1419 1420 private IdentityHashMap<IBaseResource, IIdType> getResourceToIdMap() { 1421 if (myResourceToIdMap == null) { 1422 myResourceToIdMap = new IdentityHashMap<>(); 1423 } 1424 return myResourceToIdMap; 1425 } 1426 1427 public boolean isEmpty() { 1428 if (myResourceToIdMap == null) { 1429 return true; 1430 } 1431 return myResourceToIdMap.isEmpty(); 1432 } 1433 1434 public boolean hasExistingIdToContainedResource() { 1435 return myExistingIdToContainedResourceMap != null; 1436 } 1437 1438 public void assignIdsToContainedResources() { 1439 1440 if (getResourceList() != null) { 1441 1442 /* 1443 * The idea with the code block below: 1444 * 1445 * We want to preserve any IDs that were user-assigned, so that if it's really 1446 * important to someone that their contained resource have the ID of #FOO 1447 * or #1 we will keep that. 1448 * 1449 * For any contained resources where no ID was assigned by the user, we 1450 * want to manually create an ID but make sure we don't reuse an existing ID. 1451 */ 1452 1453 Set<String> ids = new HashSet<>(); 1454 1455 // Gather any user assigned IDs 1456 for (IBaseResource nextResource : getResourceList()) { 1457 if (getResourceToIdMap().get(nextResource) != null) { 1458 ids.add(getResourceToIdMap().get(nextResource).getValue()); 1459 } 1460 } 1461 1462 // Automatically assign IDs to the rest 1463 for (IBaseResource nextResource : getResourceList()) { 1464 1465 while (getResourceToIdMap().get(nextResource) == null) { 1466 String nextCandidate = "#" + myNextContainedId; 1467 myNextContainedId++; 1468 if (!ids.add(nextCandidate)) { 1469 continue; 1470 } 1471 1472 getResourceToIdMap().put(nextResource, new IdDt(nextCandidate)); 1473 } 1474 1475 } 1476 1477 } 1478 1479 } 1480 } 1481 1482 protected static <T> List<T> extractMetadataListNotNull(IResource resource, ResourceMetadataKeyEnum<List<T>> key) { 1483 List<? extends T> securityLabels = key.get(resource); 1484 if (securityLabels == null) { 1485 securityLabels = Collections.emptyList(); 1486 } 1487 return new ArrayList<>(securityLabels); 1488 } 1489 1490 static boolean hasNoExtensions(IBase theElement) { 1491 if (theElement instanceof ISupportsUndeclaredExtensions) { 1492 ISupportsUndeclaredExtensions res = (ISupportsUndeclaredExtensions) theElement; 1493 if (res.getUndeclaredExtensions().size() > 0 || res.getUndeclaredModifierExtensions().size() > 0) { 1494 return false; 1495 } 1496 } 1497 if (theElement instanceof IBaseHasExtensions) { 1498 IBaseHasExtensions res = (IBaseHasExtensions) theElement; 1499 if (res.hasExtension()) { 1500 return false; 1501 } 1502 } 1503 if (theElement instanceof IBaseHasModifierExtensions) { 1504 IBaseHasModifierExtensions res = (IBaseHasModifierExtensions) theElement; 1505 return !res.hasModifierExtension(); 1506 } 1507 return true; 1508 } 1509 1510}