001package ca.uhn.fhir.util; 002 003import ca.uhn.fhir.context.BaseRuntimeChildDefinition; 004import ca.uhn.fhir.context.BaseRuntimeElementCompositeDefinition; 005import ca.uhn.fhir.context.BaseRuntimeElementDefinition; 006import ca.uhn.fhir.context.BaseRuntimeElementDefinition.ChildTypeEnum; 007import ca.uhn.fhir.context.ConfigurationException; 008import ca.uhn.fhir.context.FhirContext; 009import ca.uhn.fhir.context.FhirVersionEnum; 010import ca.uhn.fhir.context.RuntimeChildChoiceDefinition; 011import ca.uhn.fhir.context.RuntimeChildDirectResource; 012import ca.uhn.fhir.context.RuntimeExtensionDtDefinition; 013import ca.uhn.fhir.context.RuntimeResourceDefinition; 014import ca.uhn.fhir.context.RuntimeSearchParam; 015import ca.uhn.fhir.model.api.ExtensionDt; 016import ca.uhn.fhir.model.api.IElement; 017import ca.uhn.fhir.model.api.IIdentifiableElement; 018import ca.uhn.fhir.model.api.IResource; 019import ca.uhn.fhir.model.api.ISupportsUndeclaredExtensions; 020import ca.uhn.fhir.model.base.composite.BaseContainedDt; 021import ca.uhn.fhir.model.base.composite.BaseResourceReferenceDt; 022import ca.uhn.fhir.model.primitive.StringDt; 023import ca.uhn.fhir.parser.DataFormatException; 024import org.apache.commons.lang3.Validate; 025import org.hl7.fhir.instance.model.api.IBase; 026import org.hl7.fhir.instance.model.api.IBaseElement; 027import org.hl7.fhir.instance.model.api.IBaseExtension; 028import org.hl7.fhir.instance.model.api.IBaseHasExtensions; 029import org.hl7.fhir.instance.model.api.IBaseHasModifierExtensions; 030import org.hl7.fhir.instance.model.api.IBaseReference; 031import org.hl7.fhir.instance.model.api.IBaseResource; 032import org.hl7.fhir.instance.model.api.IIdType; 033import org.hl7.fhir.instance.model.api.IPrimitiveType; 034 035import java.util.ArrayList; 036import java.util.Arrays; 037import java.util.Collection; 038import java.util.Collections; 039import java.util.IdentityHashMap; 040import java.util.List; 041import java.util.Map; 042import java.util.Optional; 043import java.util.regex.Matcher; 044import java.util.regex.Pattern; 045import java.util.stream.Collectors; 046 047import static org.apache.commons.lang3.StringUtils.defaultString; 048import static org.apache.commons.lang3.StringUtils.isBlank; 049import static org.apache.commons.lang3.StringUtils.isNotBlank; 050 051/* 052 * #%L 053 * HAPI FHIR - Core Library 054 * %% 055 * Copyright (C) 2014 - 2020 University Health Network 056 * %% 057 * Licensed under the Apache License, Version 2.0 (the "License"); 058 * you may not use this file except in compliance with the License. 059 * You may obtain a copy of the License at 060 * 061 * http://www.apache.org/licenses/LICENSE-2.0 062 * 063 * Unless required by applicable law or agreed to in writing, software 064 * distributed under the License is distributed on an "AS IS" BASIS, 065 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 066 * See the License for the specific language governing permissions and 067 * limitations under the License. 068 * #L% 069 */ 070 071public class FhirTerser { 072 073 private static final Pattern COMPARTMENT_MATCHER_PATH = Pattern.compile("([a-zA-Z.]+)\\.where\\(resolve\\(\\) is ([a-zA-Z]+)\\)"); 074 private FhirContext myContext; 075 076 public FhirTerser(FhirContext theContext) { 077 super(); 078 myContext = theContext; 079 } 080 081 private List<String> addNameToList(List<String> theCurrentList, BaseRuntimeChildDefinition theChildDefinition) { 082 if (theChildDefinition == null) 083 return null; 084 if (theCurrentList == null || theCurrentList.isEmpty()) 085 return new ArrayList<>(Collections.singletonList(theChildDefinition.getElementName())); 086 List<String> newList = new ArrayList<>(theCurrentList); 087 newList.add(theChildDefinition.getElementName()); 088 return newList; 089 } 090 091 private ExtensionDt createEmptyExtensionDt(IBaseExtension theBaseExtension, String theUrl) { 092 return createEmptyExtensionDt(theBaseExtension, false, theUrl); 093 } 094 095 @SuppressWarnings("unchecked") 096 private ExtensionDt createEmptyExtensionDt(IBaseExtension theBaseExtension, boolean theIsModifier, String theUrl) { 097 ExtensionDt retVal = new ExtensionDt(theIsModifier, theUrl); 098 theBaseExtension.getExtension().add(retVal); 099 return retVal; 100 } 101 102 private ExtensionDt createEmptyExtensionDt(ISupportsUndeclaredExtensions theSupportsUndeclaredExtensions, String theUrl) { 103 return createEmptyExtensionDt(theSupportsUndeclaredExtensions, false, theUrl); 104 } 105 106 private ExtensionDt createEmptyExtensionDt(ISupportsUndeclaredExtensions theSupportsUndeclaredExtensions, boolean theIsModifier, String theUrl) { 107 return theSupportsUndeclaredExtensions.addUndeclaredExtension(theIsModifier, theUrl); 108 } 109 110 private IBaseExtension createEmptyExtension(IBaseHasExtensions theBaseHasExtensions, String theUrl) { 111 return (IBaseExtension) theBaseHasExtensions.addExtension().setUrl(theUrl); 112 } 113 114 private IBaseExtension createEmptyModifierExtension(IBaseHasModifierExtensions theBaseHasModifierExtensions, String theUrl) { 115 return (IBaseExtension) theBaseHasModifierExtensions.addModifierExtension().setUrl(theUrl); 116 } 117 118 private ExtensionDt createEmptyModifierExtensionDt(ISupportsUndeclaredExtensions theSupportsUndeclaredExtensions, String theUrl) { 119 return createEmptyExtensionDt(theSupportsUndeclaredExtensions, true, theUrl); 120 } 121 122 /** 123 * Clones all values from a source object into the equivalent fields in a target object 124 * 125 * @param theSource The source object (must not be null) 126 * @param theTarget The target object to copy values into (must not be null) 127 * @param theIgnoreMissingFields The ignore fields in the target which do not exist (if false, an exception will be thrown if the target is unable to accept a value from the source) 128 * @return Returns the target (which will be the same object that was passed into theTarget) for easy chaining 129 */ 130 public IBase cloneInto(IBase theSource, IBase theTarget, boolean theIgnoreMissingFields) { 131 Validate.notNull(theSource, "theSource must not be null"); 132 Validate.notNull(theTarget, "theTarget must not be null"); 133 134 // DSTU3+ 135 if (theSource instanceof IBaseElement) { 136 IBaseElement source = (IBaseElement) theSource; 137 IBaseElement target = (IBaseElement) theTarget; 138 target.setId(source.getId()); 139 } 140 141 // DSTU2 only 142 if (theSource instanceof IIdentifiableElement) { 143 IIdentifiableElement source = (IIdentifiableElement) theSource; 144 IIdentifiableElement target = (IIdentifiableElement) theTarget; 145 target.setElementSpecificId(source.getElementSpecificId()); 146 } 147 148 // DSTU2 only 149 if (theSource instanceof IResource) { 150 IResource source = (IResource) theSource; 151 IResource target = (IResource) theTarget; 152 target.setId(source.getId()); 153 target.getResourceMetadata().putAll(source.getResourceMetadata()); 154 } 155 156 if (theSource instanceof IPrimitiveType<?>) { 157 if (theTarget instanceof IPrimitiveType<?>) { 158 String valueAsString = ((IPrimitiveType<?>) theSource).getValueAsString(); 159 if (isNotBlank(valueAsString)) { 160 ((IPrimitiveType<?>) theTarget).setValueAsString(valueAsString); 161 } 162 if (theSource instanceof IBaseHasExtensions && theTarget instanceof IBaseHasExtensions) { 163 List<? extends IBaseExtension<?, ?>> extensions = ((IBaseHasExtensions) theSource).getExtension(); 164 for (IBaseExtension<?, ?> nextSource : extensions) { 165 IBaseExtension<?, ?> nextTarget = ((IBaseHasExtensions) theTarget).addExtension(); 166 cloneInto(nextSource, nextTarget, theIgnoreMissingFields); 167 } 168 } 169 return theSource; 170 } 171 if (theIgnoreMissingFields) { 172 return theSource; 173 } 174 throw new DataFormatException("Can not copy value from primitive of type " + theSource.getClass().getName() + " into type " + theTarget.getClass().getName()); 175 } 176 177 BaseRuntimeElementCompositeDefinition<?> sourceDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theSource.getClass()); 178 BaseRuntimeElementCompositeDefinition<?> targetDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theTarget.getClass()); 179 180 List<BaseRuntimeChildDefinition> children = sourceDef.getChildren(); 181 if (sourceDef instanceof RuntimeExtensionDtDefinition) { 182 children = ((RuntimeExtensionDtDefinition) sourceDef).getChildrenIncludingUrl(); 183 } 184 185 for (BaseRuntimeChildDefinition nextChild : children) 186 for (IBase nextValue : nextChild.getAccessor().getValues(theSource)) { 187 String elementName = nextChild.getChildNameByDatatype(nextValue.getClass()); 188 BaseRuntimeChildDefinition targetChild = targetDef.getChildByName(elementName); 189 if (targetChild == null) { 190 if (theIgnoreMissingFields) { 191 continue; 192 } 193 throw new DataFormatException("Type " + theTarget.getClass().getName() + " does not have a child with name " + elementName); 194 } 195 196 BaseRuntimeElementDefinition<?> element = myContext.getElementDefinition(nextValue.getClass()); 197 Object instanceConstructorArg = targetChild.getInstanceConstructorArguments(); 198 IBase target; 199 if (instanceConstructorArg != null) { 200 target = element.newInstance(instanceConstructorArg); 201 } else { 202 target = element.newInstance(); 203 } 204 205 targetChild.getMutator().addValue(theTarget, target); 206 cloneInto(nextValue, target, theIgnoreMissingFields); 207 } 208 209 return theTarget; 210 } 211 212 /** 213 * Returns a list containing all child elements (including the resource itself) which are <b>non-empty</b> and are either of the exact type specified, or are a subclass of that type. 214 * <p> 215 * For example, specifying a type of {@link StringDt} would return all non-empty string instances within the message. Specifying a type of {@link IResource} would return the resource itself, as 216 * well as any contained resources. 217 * </p> 218 * <p> 219 * Note on scope: This method will descend into any contained resources ({@link IResource#getContained()}) as well, but will not descend into linked resources (e.g. 220 * {@link BaseResourceReferenceDt#getResource()}) or embedded resources (e.g. Bundle.entry.resource) 221 * </p> 222 * 223 * @param theResource The resource instance to search. Must not be null. 224 * @param theType The type to search for. Must not be null. 225 * @return Returns a list of all matching elements 226 */ 227 public <T extends IBase> List<T> getAllPopulatedChildElementsOfType(IBaseResource theResource, final Class<T> theType) { 228 final ArrayList<T> retVal = new ArrayList<>(); 229 BaseRuntimeElementCompositeDefinition<?> def = myContext.getResourceDefinition(theResource); 230 visit(newMap(), theResource, theResource, null, null, def, new IModelVisitor() { 231 @SuppressWarnings("unchecked") 232 @Override 233 public void acceptElement(IBaseResource theOuterResource, IBase theElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition) { 234 if (theElement == null || theElement.isEmpty()) { 235 return; 236 } 237 238 if (theType.isAssignableFrom(theElement.getClass())) { 239 retVal.add((T) theElement); 240 } 241 } 242 }); 243 return retVal; 244 } 245 246 public List<ResourceReferenceInfo> getAllResourceReferences(final IBaseResource theResource) { 247 final ArrayList<ResourceReferenceInfo> retVal = new ArrayList<>(); 248 BaseRuntimeElementCompositeDefinition<?> def = myContext.getResourceDefinition(theResource); 249 visit(newMap(), theResource, theResource, null, null, def, new IModelVisitor() { 250 @Override 251 public void acceptElement(IBaseResource theOuterResource, IBase theElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition) { 252 if (theElement == null || theElement.isEmpty()) { 253 return; 254 } 255 if (IBaseReference.class.isAssignableFrom(theElement.getClass())) { 256 retVal.add(new ResourceReferenceInfo(myContext, theOuterResource, thePathToElement, (IBaseReference) theElement)); 257 } 258 } 259 }); 260 return retVal; 261 } 262 263 private BaseRuntimeChildDefinition getDefinition(BaseRuntimeElementCompositeDefinition<?> theCurrentDef, List<String> theSubList) { 264 BaseRuntimeChildDefinition nextDef = theCurrentDef.getChildByNameOrThrowDataFormatException(theSubList.get(0)); 265 266 if (theSubList.size() == 1) { 267 return nextDef; 268 } 269 BaseRuntimeElementCompositeDefinition<?> cmp = (BaseRuntimeElementCompositeDefinition<?>) nextDef.getChildByName(theSubList.get(0)); 270 return getDefinition(cmp, theSubList.subList(1, theSubList.size())); 271 } 272 273 public BaseRuntimeChildDefinition getDefinition(Class<? extends IBaseResource> theResourceType, String thePath) { 274 RuntimeResourceDefinition def = myContext.getResourceDefinition(theResourceType); 275 276 List<String> parts = Arrays.asList(thePath.split("\\.")); 277 List<String> subList = parts.subList(1, parts.size()); 278 if (subList.size() < 1) { 279 throw new ConfigurationException("Invalid path: " + thePath); 280 } 281 return getDefinition(def, subList); 282 283 } 284 285 public Object getSingleValueOrNull(IBase theTarget, String thePath) { 286 Class<IBase> wantedType = IBase.class; 287 288 return getSingleValueOrNull(theTarget, thePath, wantedType); 289 } 290 291 public <T extends IBase> T getSingleValueOrNull(IBase theTarget, String thePath, Class<T> theWantedType) { 292 Validate.notNull(theTarget, "theTarget must not be null"); 293 Validate.notBlank(thePath, "thePath must not be empty"); 294 295 BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition(theTarget.getClass()); 296 if (!(def instanceof BaseRuntimeElementCompositeDefinition)) { 297 throw new IllegalArgumentException("Target is not a composite type: " + theTarget.getClass().getName()); 298 } 299 300 BaseRuntimeElementCompositeDefinition<?> currentDef = (BaseRuntimeElementCompositeDefinition<?>) def; 301 302 List<String> parts = parsePath(currentDef, thePath); 303 304 List<T> retVal = getValues(currentDef, theTarget, parts, theWantedType); 305 if (retVal.isEmpty()) { 306 return null; 307 } 308 return retVal.get(0); 309 } 310 311 public <T extends IBase> Optional<T> getSingleValue(IBase theTarget, String thePath, Class<T> theWantedType) { 312 return Optional.ofNullable(getSingleValueOrNull(theTarget, thePath, theWantedType)); 313 } 314 315 316 private <T extends IBase> List<T> getValues(BaseRuntimeElementCompositeDefinition<?> theCurrentDef, IBase theCurrentObj, List<String> theSubList, Class<T> theWantedClass) { 317 return getValues(theCurrentDef, theCurrentObj, theSubList, theWantedClass, false, false); 318 } 319 320 @SuppressWarnings("unchecked") 321 private <T extends IBase> List<T> getValues(BaseRuntimeElementCompositeDefinition<?> theCurrentDef, IBase theCurrentObj, List<String> theSubList, Class<T> theWantedClass, boolean theCreate, boolean theAddExtension) { 322 String name = theSubList.get(0); 323 List<T> retVal = new ArrayList<>(); 324 325 if (name.startsWith("extension('")) { 326 String extensionUrl = name.substring("extension('".length()); 327 int endIndex = extensionUrl.indexOf('\''); 328 if (endIndex != -1) { 329 extensionUrl = extensionUrl.substring(0, endIndex); 330 } 331 332 if (myContext.getVersion().getVersion().isOlderThan(FhirVersionEnum.DSTU3)) { 333 // DTSU2 334 final String extensionDtUrlForLambda = extensionUrl; 335 List<ExtensionDt> extensionDts = Collections.emptyList(); 336 if (theCurrentObj instanceof ISupportsUndeclaredExtensions) { 337 extensionDts = ((ISupportsUndeclaredExtensions) theCurrentObj).getUndeclaredExtensions() 338 .stream() 339 .filter(t -> t.getUrl().equals(extensionDtUrlForLambda)) 340 .collect(Collectors.toList()); 341 342 if (theAddExtension 343 && (!(theCurrentObj instanceof IBaseExtension) || (extensionDts.isEmpty() && theSubList.size() == 1))) { 344 extensionDts.add(createEmptyExtensionDt((ISupportsUndeclaredExtensions) theCurrentObj, extensionUrl)); 345 } 346 347 if (extensionDts.isEmpty() && theCreate) { 348 extensionDts.add(createEmptyExtensionDt((ISupportsUndeclaredExtensions) theCurrentObj, extensionUrl)); 349 } 350 351 } else if (theCurrentObj instanceof IBaseExtension) { 352 extensionDts = ((IBaseExtension) theCurrentObj).getExtension(); 353 354 if (theAddExtension 355 && (extensionDts.isEmpty() && theSubList.size() == 1)) { 356 extensionDts.add(createEmptyExtensionDt((IBaseExtension) theCurrentObj, extensionUrl)); 357 } 358 359 if (extensionDts.isEmpty() && theCreate) { 360 extensionDts.add(createEmptyExtensionDt((IBaseExtension) theCurrentObj, extensionUrl)); 361 } 362 } 363 364 for (ExtensionDt next : extensionDts) { 365 if (theWantedClass.isAssignableFrom(next.getClass())) { 366 retVal.add((T) next); 367 } 368 } 369 } else { 370 // DSTU3+ 371 final String extensionUrlForLambda = extensionUrl; 372 List<IBaseExtension> extensions = Collections.emptyList(); 373 if (theCurrentObj instanceof IBaseHasExtensions) { 374 extensions = ((IBaseHasExtensions) theCurrentObj).getExtension() 375 .stream() 376 .filter(t -> t.getUrl().equals(extensionUrlForLambda)) 377 .collect(Collectors.toList()); 378 379 if (theAddExtension 380 && (!(theCurrentObj instanceof IBaseExtension) || (extensions.isEmpty() && theSubList.size() == 1))) { 381 extensions.add(createEmptyExtension((IBaseHasExtensions) theCurrentObj, extensionUrl)); 382 } 383 384 if (extensions.isEmpty() && theCreate) { 385 extensions.add(createEmptyExtension((IBaseHasExtensions) theCurrentObj, extensionUrl)); 386 } 387 } 388 389 for (IBaseExtension next : extensions) { 390 if (theWantedClass.isAssignableFrom(next.getClass())) { 391 retVal.add((T) next); 392 } 393 } 394 } 395 396 if (theSubList.size() > 1) { 397 List<T> values = retVal; 398 retVal = new ArrayList<>(); 399 for (T nextElement : values) { 400 BaseRuntimeElementCompositeDefinition<?> nextChildDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(nextElement.getClass()); 401 List<T> foundValues = getValues(nextChildDef, nextElement, theSubList.subList(1, theSubList.size()), theWantedClass, theCreate, theAddExtension); 402 retVal.addAll(foundValues); 403 } 404 } 405 406 return retVal; 407 } 408 409 if (name.startsWith("modifierExtension('")) { 410 String extensionUrl = name.substring("modifierExtension('".length()); 411 int endIndex = extensionUrl.indexOf('\''); 412 if (endIndex != -1) { 413 extensionUrl = extensionUrl.substring(0, endIndex); 414 } 415 416 if (myContext.getVersion().getVersion().isOlderThan(FhirVersionEnum.DSTU3)) { 417 // DSTU2 418 final String extensionDtUrlForLambda = extensionUrl; 419 List<ExtensionDt> extensionDts = Collections.emptyList(); 420 if (theCurrentObj instanceof ISupportsUndeclaredExtensions) { 421 extensionDts = ((ISupportsUndeclaredExtensions) theCurrentObj).getUndeclaredModifierExtensions() 422 .stream() 423 .filter(t -> t.getUrl().equals(extensionDtUrlForLambda)) 424 .collect(Collectors.toList()); 425 426 if (theAddExtension 427 && (!(theCurrentObj instanceof IBaseExtension) || (extensionDts.isEmpty() && theSubList.size() == 1))) { 428 extensionDts.add(createEmptyModifierExtensionDt((ISupportsUndeclaredExtensions) theCurrentObj, extensionUrl)); 429 } 430 431 if (extensionDts.isEmpty() && theCreate) { 432 extensionDts.add(createEmptyModifierExtensionDt((ISupportsUndeclaredExtensions) theCurrentObj, extensionUrl)); 433 } 434 435 } else if (theCurrentObj instanceof IBaseExtension) { 436 extensionDts = ((IBaseExtension) theCurrentObj).getExtension(); 437 438 if (theAddExtension 439 && (extensionDts.isEmpty() && theSubList.size() == 1)) { 440 extensionDts.add(createEmptyExtensionDt((IBaseExtension) theCurrentObj, extensionUrl)); 441 } 442 443 if (extensionDts.isEmpty() && theCreate) { 444 extensionDts.add(createEmptyExtensionDt((IBaseExtension) theCurrentObj, extensionUrl)); 445 } 446 } 447 448 for (ExtensionDt next : extensionDts) { 449 if (theWantedClass.isAssignableFrom(next.getClass())) { 450 retVal.add((T) next); 451 } 452 } 453 } else { 454 // DSTU3+ 455 final String extensionUrlForLambda = extensionUrl; 456 List<IBaseExtension> extensions = Collections.emptyList(); 457 458 if (theCurrentObj instanceof IBaseHasModifierExtensions) { 459 extensions = ((IBaseHasModifierExtensions) theCurrentObj).getModifierExtension() 460 .stream() 461 .filter(t -> t.getUrl().equals(extensionUrlForLambda)) 462 .collect(Collectors.toList()); 463 464 if (theAddExtension 465 && (!(theCurrentObj instanceof IBaseExtension) || (extensions.isEmpty() && theSubList.size() == 1))) { 466 extensions.add(createEmptyModifierExtension((IBaseHasModifierExtensions) theCurrentObj, extensionUrl)); 467 } 468 469 if (extensions.isEmpty() && theCreate) { 470 extensions.add(createEmptyModifierExtension((IBaseHasModifierExtensions) theCurrentObj, extensionUrl)); 471 } 472 } 473 474 for (IBaseExtension next : extensions) { 475 if (theWantedClass.isAssignableFrom(next.getClass())) { 476 retVal.add((T) next); 477 } 478 } 479 } 480 481 if (theSubList.size() > 1) { 482 List<T> values = retVal; 483 retVal = new ArrayList<>(); 484 for (T nextElement : values) { 485 BaseRuntimeElementCompositeDefinition<?> nextChildDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(nextElement.getClass()); 486 List<T> foundValues = getValues(nextChildDef, nextElement, theSubList.subList(1, theSubList.size()), theWantedClass, theCreate, theAddExtension); 487 retVal.addAll(foundValues); 488 } 489 } 490 491 return retVal; 492 } 493 494 BaseRuntimeChildDefinition nextDef = theCurrentDef.getChildByNameOrThrowDataFormatException(name); 495 List<? extends IBase> values = nextDef.getAccessor().getValues(theCurrentObj); 496 497 if (values.isEmpty() && theCreate) { 498 BaseRuntimeElementDefinition<?> childByName = nextDef.getChildByName(name); 499 Object arg = nextDef.getInstanceConstructorArguments(); 500 IBase value; 501 if (arg != null) { 502 value = childByName.newInstance(arg); 503 } else { 504 value = childByName.newInstance(); 505 } 506 nextDef.getMutator().addValue(theCurrentObj, value); 507 List<IBase> list = new ArrayList<>(); 508 list.add(value); 509 values = list; 510 } 511 512 if (theSubList.size() == 1) { 513 if (nextDef instanceof RuntimeChildChoiceDefinition) { 514 for (IBase next : values) { 515 if (next != null) { 516 if (name.endsWith("[x]")) { 517 if (theWantedClass == null || theWantedClass.isAssignableFrom(next.getClass())) { 518 retVal.add((T) next); 519 } 520 } else { 521 String childName = nextDef.getChildNameByDatatype(next.getClass()); 522 if (theSubList.get(0).equals(childName)) { 523 if (theWantedClass == null || theWantedClass.isAssignableFrom(next.getClass())) { 524 retVal.add((T) next); 525 } 526 } 527 } 528 } 529 } 530 } else { 531 for (IBase next : values) { 532 if (next != null) { 533 if (theWantedClass == null || theWantedClass.isAssignableFrom(next.getClass())) { 534 retVal.add((T) next); 535 } 536 } 537 } 538 } 539 } else { 540 for (IBase nextElement : values) { 541 BaseRuntimeElementCompositeDefinition<?> nextChildDef = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(nextElement.getClass()); 542 List<T> foundValues = getValues(nextChildDef, nextElement, theSubList.subList(1, theSubList.size()), theWantedClass, theCreate, theAddExtension); 543 retVal.addAll(foundValues); 544 } 545 } 546 return retVal; 547 } 548 549 /** 550 * Returns values stored in an element identified by its path. The list of values is of 551 * type {@link Object}. 552 * 553 * @param theElement The element to be accessed. Must not be null. 554 * @param thePath The path for the element to be accessed.@param theElement The resource instance to be accessed. Must not be null. 555 * @return A list of values of type {@link Object}. 556 */ 557 public List<IBase> getValues(IBase theElement, String thePath) { 558 Class<IBase> wantedClass = IBase.class; 559 560 return getValues(theElement, thePath, wantedClass); 561 } 562 563 /** 564 * Returns values stored in an element identified by its path. The list of values is of 565 * type {@link Object}. 566 * 567 * @param theElement The element to be accessed. Must not be null. 568 * @param thePath The path for the element to be accessed. 569 * @param theCreate When set to <code>true</code>, the terser will create a null-valued element where none exists. 570 * @return A list of values of type {@link Object}. 571 */ 572 public List<IBase> getValues(IBase theElement, String thePath, boolean theCreate) { 573 Class<IBase> wantedClass = IBase.class; 574 575 return getValues(theElement, thePath, wantedClass, theCreate); 576 } 577 578 /** 579 * Returns values stored in an element identified by its path. The list of values is of 580 * type {@link Object}. 581 * 582 * @param theElement The element to be accessed. Must not be null. 583 * @param thePath The path for the element to be accessed. 584 * @param theCreate When set to <code>true</code>, the terser will create a null-valued element where none exists. 585 * @param theAddExtension When set to <code>true</code>, the terser will add a null-valued extension where one or more such extensions already exist. 586 * @return A list of values of type {@link Object}. 587 */ 588 public List<IBase> getValues(IBase theElement, String thePath, boolean theCreate, boolean theAddExtension) { 589 Class<IBase> wantedClass = IBase.class; 590 591 return getValues(theElement, thePath, wantedClass, theCreate, theAddExtension); 592 } 593 594 /** 595 * Returns values stored in an element identified by its path. The list of values is of 596 * type <code>theWantedClass</code>. 597 * 598 * @param theElement The element to be accessed. Must not be null. 599 * @param thePath The path for the element to be accessed. 600 * @param theWantedClass The desired class to be returned in a list. 601 * @param <T> Type declared by <code>theWantedClass</code> 602 * @return A list of values of type <code>theWantedClass</code>. 603 */ 604 public <T extends IBase> List<T> getValues(IBase theElement, String thePath, Class<T> theWantedClass) { 605 BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theElement.getClass()); 606 List<String> parts = parsePath(def, thePath); 607 return getValues(def, theElement, parts, theWantedClass); 608 } 609 610 /** 611 * Returns values stored in an element identified by its path. The list of values is of 612 * type <code>theWantedClass</code>. 613 * 614 * @param theElement The element to be accessed. Must not be null. 615 * @param thePath The path for the element to be accessed. 616 * @param theWantedClass The desired class to be returned in a list. 617 * @param theCreate When set to <code>true</code>, the terser will create a null-valued element where none exists. 618 * @param <T> Type declared by <code>theWantedClass</code> 619 * @return A list of values of type <code>theWantedClass</code>. 620 */ 621 public <T extends IBase> List<T> getValues(IBase theElement, String thePath, Class<T> theWantedClass, boolean theCreate) { 622 BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theElement.getClass()); 623 List<String> parts = parsePath(def, thePath); 624 return getValues(def, theElement, parts, theWantedClass, theCreate, false); 625 } 626 627 /** 628 * Returns values stored in an element identified by its path. The list of values is of 629 * type <code>theWantedClass</code>. 630 * 631 * @param theElement The element to be accessed. Must not be null. 632 * @param thePath The path for the element to be accessed. 633 * @param theWantedClass The desired class to be returned in a list. 634 * @param theCreate When set to <code>true</code>, the terser will create a null-valued element where none exists. 635 * @param theAddExtension When set to <code>true</code>, the terser will add a null-valued extension where one or more such extensions already exist. 636 * @param <T> Type declared by <code>theWantedClass</code> 637 * @return A list of values of type <code>theWantedClass</code>. 638 */ 639 public <T extends IBase> List<T> getValues(IBase theElement, String thePath, Class<T> theWantedClass, boolean theCreate, boolean theAddExtension) { 640 BaseRuntimeElementCompositeDefinition<?> def = (BaseRuntimeElementCompositeDefinition<?>) myContext.getElementDefinition(theElement.getClass()); 641 List<String> parts = parsePath(def, thePath); 642 return getValues(def, theElement, parts, theWantedClass, theCreate, theAddExtension); 643 } 644 645 private List<String> parsePath(BaseRuntimeElementCompositeDefinition<?> theElementDef, String thePath) { 646 List<String> parts = new ArrayList<>(); 647 648 int currentStart = 0; 649 boolean inSingleQuote = false; 650 for (int i = 0; i < thePath.length(); i++) { 651 switch (thePath.charAt(i)) { 652 case '\'': 653 inSingleQuote = !inSingleQuote; 654 break; 655 case '.': 656 if (!inSingleQuote) { 657 parts.add(thePath.substring(currentStart, i)); 658 currentStart = i + 1; 659 } 660 break; 661 } 662 } 663 664 parts.add(thePath.substring(currentStart)); 665 666 if (theElementDef instanceof RuntimeResourceDefinition) { 667 if (parts.size() > 0 && parts.get(0).equals(theElementDef.getName())) { 668 parts = parts.subList(1, parts.size()); 669 } 670 } 671 672 if (parts.size() < 1) { 673 throw new ConfigurationException("Invalid path: " + thePath); 674 } 675 return parts; 676 } 677 678 /** 679 * Returns <code>true</code> if <code>theSource</code> is in the compartment named <code>theCompartmentName</code> 680 * belonging to resource <code>theTarget</code> 681 * 682 * @param theCompartmentName The name of the compartment 683 * @param theSource The potential member of the compartment 684 * @param theTarget The owner of the compartment. Note that both the resource type and ID must be filled in on this IIdType or the method will throw an {@link IllegalArgumentException} 685 * @return <code>true</code> if <code>theSource</code> is in the compartment 686 * @throws IllegalArgumentException If theTarget does not contain both a resource type and ID 687 */ 688 public boolean isSourceInCompartmentForTarget(String theCompartmentName, IBaseResource theSource, IIdType theTarget) { 689 Validate.notBlank(theCompartmentName, "theCompartmentName must not be null or blank"); 690 Validate.notNull(theSource, "theSource must not be null"); 691 Validate.notNull(theTarget, "theTarget must not be null"); 692 Validate.notBlank(defaultString(theTarget.getResourceType()), "theTarget must have a populated resource type (theTarget.getResourceType() does not return a value)"); 693 Validate.notBlank(defaultString(theTarget.getIdPart()), "theTarget must have a populated ID (theTarget.getIdPart() does not return a value)"); 694 695 String wantRef = theTarget.toUnqualifiedVersionless().getValue(); 696 697 RuntimeResourceDefinition sourceDef = myContext.getResourceDefinition(theSource); 698 if (theSource.getIdElement().hasIdPart()) { 699 if (wantRef.equals(sourceDef.getName() + '/' + theSource.getIdElement().getIdPart())) { 700 return true; 701 } 702 } 703 704 List<RuntimeSearchParam> params = sourceDef.getSearchParamsForCompartmentName(theCompartmentName); 705 for (RuntimeSearchParam nextParam : params) { 706 for (String nextPath : nextParam.getPathsSplit()) { 707 708 /* 709 * DSTU3 and before just defined compartments as being (e.g.) named 710 * Patient with a path like CarePlan.subject 711 * 712 * R4 uses a fancier format like CarePlan.subject.where(resolve() is Patient) 713 * 714 * The following Regex is a hack to make that efficient at runtime. 715 */ 716 String wantType = null; 717 Pattern pattern = COMPARTMENT_MATCHER_PATH; 718 Matcher matcher = pattern.matcher(nextPath); 719 if (matcher.matches()) { 720 nextPath = matcher.group(1); 721 wantType = matcher.group(2); 722 } 723 724 List<IBaseReference> values = getValues(theSource, nextPath, IBaseReference.class); 725 for (IBaseReference nextValue : values) { 726 IIdType nextTargetId = nextValue.getReferenceElement(); 727 String nextRef = nextTargetId.toUnqualifiedVersionless().getValue(); 728 729 /* 730 * If the reference isn't an explicit resource ID, but instead is just 731 * a resource object, we'll calculate its ID and treat the target 732 * as that. 733 */ 734 if (isBlank(nextRef) && nextValue.getResource() != null) { 735 IBaseResource nextTarget = nextValue.getResource(); 736 nextTargetId = nextTarget.getIdElement().toUnqualifiedVersionless(); 737 if (!nextTargetId.hasResourceType()) { 738 String resourceType = myContext.getResourceType(nextTarget); 739 nextTargetId.setParts(null, resourceType, nextTargetId.getIdPart(), null); 740 } 741 nextRef = nextTargetId.getValue(); 742 } 743 744 if (isNotBlank(wantType)) { 745 String nextTargetIdResourceType = nextTargetId.getResourceType(); 746 if (nextTargetIdResourceType == null || !nextTargetIdResourceType.equals(wantType)) { 747 continue; 748 } 749 } 750 751 if (wantRef.equals(nextRef)) { 752 return true; 753 } 754 } 755 } 756 } 757 758 return false; 759 } 760 761 private void visit(IBase theElement, BaseRuntimeChildDefinition theChildDefinition, BaseRuntimeElementDefinition<?> theDefinition, IModelVisitor2 theCallback, List<IBase> theContainingElementPath, 762 List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) { 763 if (theChildDefinition != null) { 764 theChildDefinitionPath.add(theChildDefinition); 765 } 766 theContainingElementPath.add(theElement); 767 theElementDefinitionPath.add(theDefinition); 768 769 boolean recurse = theCallback.acceptElement(theElement, Collections.unmodifiableList(theContainingElementPath), Collections.unmodifiableList(theChildDefinitionPath), 770 Collections.unmodifiableList(theElementDefinitionPath)); 771 if (recurse) { 772 773 /* 774 * Visit undeclared extensions 775 */ 776 if (theElement instanceof ISupportsUndeclaredExtensions) { 777 ISupportsUndeclaredExtensions containingElement = (ISupportsUndeclaredExtensions) theElement; 778 for (ExtensionDt nextExt : containingElement.getUndeclaredExtensions()) { 779 theContainingElementPath.add(nextExt); 780 theCallback.acceptUndeclaredExtension(nextExt, theContainingElementPath, theChildDefinitionPath, theElementDefinitionPath); 781 theContainingElementPath.remove(theContainingElementPath.size() - 1); 782 } 783 } 784 785 /* 786 * Now visit the children of the given element 787 */ 788 switch (theDefinition.getChildType()) { 789 case ID_DATATYPE: 790 case PRIMITIVE_XHTML_HL7ORG: 791 case PRIMITIVE_XHTML: 792 case PRIMITIVE_DATATYPE: 793 // These are primitive types, so we don't need to visit their children 794 break; 795 case RESOURCE: 796 case RESOURCE_BLOCK: 797 case COMPOSITE_DATATYPE: { 798 BaseRuntimeElementCompositeDefinition<?> childDef = (BaseRuntimeElementCompositeDefinition<?>) theDefinition; 799 for (BaseRuntimeChildDefinition nextChild : childDef.getChildrenAndExtension()) { 800 List<? extends IBase> values = nextChild.getAccessor().getValues(theElement); 801 if (values != null) { 802 for (IBase nextValue : values) { 803 if (nextValue == null) { 804 continue; 805 } 806 if (nextValue.isEmpty()) { 807 continue; 808 } 809 BaseRuntimeElementDefinition<?> childElementDef; 810 Class<? extends IBase> valueType = nextValue.getClass(); 811 childElementDef = nextChild.getChildElementDefinitionByDatatype(valueType); 812 while (childElementDef == null && IBase.class.isAssignableFrom(valueType)) { 813 childElementDef = nextChild.getChildElementDefinitionByDatatype(valueType); 814 valueType = (Class<? extends IBase>) valueType.getSuperclass(); 815 } 816 817 Class<? extends IBase> typeClass = nextValue.getClass(); 818 while (childElementDef == null && IBase.class.isAssignableFrom(typeClass)) { 819 //noinspection unchecked 820 typeClass = (Class<? extends IBase>) typeClass.getSuperclass(); 821 childElementDef = nextChild.getChildElementDefinitionByDatatype(typeClass); 822 } 823 824 Validate.notNull(childElementDef, "Found value of type[%s] which is not valid for field[%s] in %s", nextValue.getClass(), nextChild.getElementName(), childDef.getName()); 825 826 visit(nextValue, nextChild, childElementDef, theCallback, theContainingElementPath, theChildDefinitionPath, theElementDefinitionPath); 827 } 828 } 829 } 830 break; 831 } 832 case CONTAINED_RESOURCES: { 833 BaseContainedDt value = (BaseContainedDt) theElement; 834 for (IResource next : value.getContainedResources()) { 835 BaseRuntimeElementCompositeDefinition<?> def = myContext.getResourceDefinition(next); 836 visit(next, null, def, theCallback, theContainingElementPath, theChildDefinitionPath, theElementDefinitionPath); 837 } 838 break; 839 } 840 case EXTENSION_DECLARED: 841 case UNDECL_EXT: { 842 throw new IllegalStateException("state should not happen: " + theDefinition.getChildType()); 843 } 844 case CONTAINED_RESOURCE_LIST: { 845 if (theElement != null) { 846 BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition(theElement.getClass()); 847 visit(theElement, null, def, theCallback, theContainingElementPath, theChildDefinitionPath, theElementDefinitionPath); 848 } 849 break; 850 } 851 } 852 853 } 854 855 if (theChildDefinition != null) { 856 theChildDefinitionPath.remove(theChildDefinitionPath.size() - 1); 857 } 858 theContainingElementPath.remove(theContainingElementPath.size() - 1); 859 theElementDefinitionPath.remove(theElementDefinitionPath.size() - 1); 860 } 861 862 /** 863 * Visit all elements in a given resource 864 * 865 * <p> 866 * Note on scope: This method will descend into any contained resources ({@link IResource#getContained()}) as well, but will not descend into linked resources (e.g. 867 * {@link BaseResourceReferenceDt#getResource()}) or embedded resources (e.g. Bundle.entry.resource) 868 * </p> 869 * 870 * @param theResource The resource to visit 871 * @param theVisitor The visitor 872 */ 873 public void visit(IBaseResource theResource, IModelVisitor theVisitor) { 874 BaseRuntimeElementCompositeDefinition<?> def = myContext.getResourceDefinition(theResource); 875 visit(newMap(), theResource, theResource, null, null, def, theVisitor); 876 } 877 878 public Map<Object, Object> newMap() { 879 return new IdentityHashMap<>(); 880 } 881 882 /** 883 * Visit all elements in a given resource or element 884 * <p> 885 * <b>THIS ALTERNATE METHOD IS STILL EXPERIMENTAL! USE WITH CAUTION</b> 886 * </p> 887 * <p> 888 * Note on scope: This method will descend into any contained resources ({@link IResource#getContained()}) as well, but will not descend into linked resources (e.g. 889 * {@link BaseResourceReferenceDt#getResource()}) or embedded resources (e.g. Bundle.entry.resource) 890 * </p> 891 * 892 * @param theElement The element to visit 893 * @param theVisitor The visitor 894 */ 895 public void visit(IBase theElement, IModelVisitor2 theVisitor) { 896 BaseRuntimeElementDefinition<?> def = myContext.getElementDefinition(theElement.getClass()); 897 if (def instanceof BaseRuntimeElementCompositeDefinition) { 898 BaseRuntimeElementCompositeDefinition<?> defComposite = (BaseRuntimeElementCompositeDefinition<?>) def; 899 visit(theElement, null, def, theVisitor, new ArrayList<>(), new ArrayList<>(), new ArrayList<>()); 900 } else if (theElement instanceof IBaseExtension) { 901 theVisitor.acceptUndeclaredExtension((IBaseExtension<?, ?>) theElement, Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); 902 } else { 903 theVisitor.acceptElement(theElement, Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); 904 } 905 } 906 907 private void visit(Map<Object, Object> theStack, IBaseResource theResource, IBase theElement, List<String> thePathToElement, BaseRuntimeChildDefinition theChildDefinition, 908 BaseRuntimeElementDefinition<?> theDefinition, IModelVisitor theCallback) { 909 List<String> pathToElement = addNameToList(thePathToElement, theChildDefinition); 910 911 if (theStack.put(theElement, theElement) != null) { 912 return; 913 } 914 915 theCallback.acceptElement(theResource, theElement, pathToElement, theChildDefinition, theDefinition); 916 917 BaseRuntimeElementDefinition<?> def = theDefinition; 918 if (def.getChildType() == ChildTypeEnum.CONTAINED_RESOURCE_LIST) { 919 def = myContext.getElementDefinition(theElement.getClass()); 920 } 921 922 if (theElement instanceof IBaseReference) { 923 IBaseResource target = ((IBaseReference) theElement).getResource(); 924 if (target != null) { 925 if (target.getIdElement().hasIdPart() == false || target.getIdElement().isLocal()) { 926 RuntimeResourceDefinition targetDef = myContext.getResourceDefinition(target); 927 visit(theStack, target, target, pathToElement, null, targetDef, theCallback); 928 } 929 } 930 } 931 932 switch (def.getChildType()) { 933 case ID_DATATYPE: 934 case PRIMITIVE_XHTML_HL7ORG: 935 case PRIMITIVE_XHTML: 936 case PRIMITIVE_DATATYPE: 937 // These are primitive types 938 break; 939 case RESOURCE: 940 case RESOURCE_BLOCK: 941 case COMPOSITE_DATATYPE: { 942 BaseRuntimeElementCompositeDefinition<?> childDef = (BaseRuntimeElementCompositeDefinition<?>) def; 943 for (BaseRuntimeChildDefinition nextChild : childDef.getChildrenAndExtension()) { 944 945 List<?> values = nextChild.getAccessor().getValues(theElement); 946 if (values != null) { 947 for (Object nextValueObject : values) { 948 IBase nextValue; 949 try { 950 nextValue = (IBase) nextValueObject; 951 } catch (ClassCastException e) { 952 String s = "Found instance of " + nextValueObject.getClass() + " - Did you set a field value to the incorrect type? Expected " + IBase.class.getName(); 953 throw new ClassCastException(s); 954 } 955 if (nextValue == null) { 956 continue; 957 } 958 if (nextValue.isEmpty()) { 959 continue; 960 } 961 BaseRuntimeElementDefinition<?> childElementDef; 962 childElementDef = nextChild.getChildElementDefinitionByDatatype(nextValue.getClass()); 963 964 if (childElementDef == null) { 965 childElementDef = myContext.getElementDefinition(nextValue.getClass()); 966 } 967 968 if (nextChild instanceof RuntimeChildDirectResource) { 969 // Don't descend into embedded resources 970 theCallback.acceptElement(theResource, nextValue, null, nextChild, childElementDef); 971 } else { 972 visit(theStack, theResource, nextValue, pathToElement, nextChild, childElementDef, theCallback); 973 } 974 } 975 } 976 } 977 break; 978 } 979 case CONTAINED_RESOURCES: { 980 BaseContainedDt value = (BaseContainedDt) theElement; 981 for (IResource next : value.getContainedResources()) { 982 def = myContext.getResourceDefinition(next); 983 visit(theStack, next, next, pathToElement, null, def, theCallback); 984 } 985 break; 986 } 987 case CONTAINED_RESOURCE_LIST: 988 case EXTENSION_DECLARED: 989 case UNDECL_EXT: { 990 throw new IllegalStateException("state should not happen: " + def.getChildType()); 991 } 992 } 993 994 theStack.remove(theElement); 995 996 } 997 998 /** 999 * Returns all embedded resources that are found embedded within <code>theResource</code>. 1000 * An embedded resource is a resource that can be found as a direct child within a resource, 1001 * as opposed to being referenced by the resource. 1002 * <p> 1003 * Examples include resources found within <code>Bundle.entry.resource</code> 1004 * and <code>Parameters.parameter.resource</code>, as well as contained resources 1005 * found within <code>Resource.contained</code> 1006 * </p> 1007 * 1008 * @param theRecurse Should embedded resources be recursively scanned for further embedded 1009 * resources 1010 * @return A collection containing the embedded resources. Order is arbitrary. 1011 */ 1012 public Collection<IBaseResource> getAllEmbeddedResources(IBaseResource theResource, boolean theRecurse) { 1013 Validate.notNull(theResource, "theResource must not be null"); 1014 ArrayList<IBaseResource> retVal = new ArrayList<>(); 1015 1016 visit(theResource, new IModelVisitor2() { 1017 @Override 1018 public boolean acceptElement(IBase theElement, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) { 1019 if (theElement == theResource) { 1020 return true; 1021 } 1022 if (theElement instanceof IBaseResource) { 1023 retVal.add((IBaseResource) theElement); 1024 return theRecurse; 1025 } 1026 return true; 1027 } 1028 1029 @Override 1030 public boolean acceptUndeclaredExtension(IBaseExtension<?, ?> theNextExt, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) { 1031 return true; 1032 } 1033 }); 1034 1035 return retVal; 1036 } 1037 1038 /** 1039 * Clear all content on a resource 1040 */ 1041 public void clear(IBaseResource theInput) { 1042 visit(theInput, new IModelVisitor2() { 1043 @Override 1044 public boolean acceptElement(IBase theElement, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) { 1045 if (theElement instanceof IPrimitiveType) { 1046 ((IPrimitiveType) theElement).setValueAsString(null); 1047 } 1048 return true; 1049 } 1050 1051 @Override 1052 public boolean acceptUndeclaredExtension(IBaseExtension<?, ?> theNextExt, List<IBase> theContainingElementPath, List<BaseRuntimeChildDefinition> theChildDefinitionPath, List<BaseRuntimeElementDefinition<?>> theElementDefinitionPath) { 1053 theNextExt.setUrl(null); 1054 theNextExt.setValue(null); 1055 return true; 1056 } 1057 1058 }); 1059 } 1060 1061}