001package org.hl7.fhir.r4.utils; 002 003import ca.uhn.fhir.model.api.TemporalPrecisionEnum; 004import ca.uhn.fhir.util.ElementUtil; 005import org.apache.commons.lang3.NotImplementedException; 006import org.fhir.ucum.Decimal; 007import org.fhir.ucum.Pair; 008import org.fhir.ucum.UcumException; 009import org.hl7.fhir.exceptions.DefinitionException; 010import org.hl7.fhir.exceptions.FHIRException; 011import org.hl7.fhir.exceptions.PathEngineException; 012import org.hl7.fhir.r4.conformance.ProfileUtilities; 013import org.hl7.fhir.r4.context.IWorkerContext; 014import org.hl7.fhir.r4.model.*; 015import org.hl7.fhir.r4.model.ElementDefinition.TypeRefComponent; 016import org.hl7.fhir.r4.model.ExpressionNode.*; 017import org.hl7.fhir.r4.model.StructureDefinition.StructureDefinitionKind; 018import org.hl7.fhir.r4.model.StructureDefinition.TypeDerivationRule; 019import org.hl7.fhir.r4.model.TypeDetails.ProfiledType; 020import org.hl7.fhir.r4.utils.FHIRLexer.FHIRLexerException; 021import org.hl7.fhir.r4.utils.FHIRPathEngine.IEvaluationContext.FunctionDetails; 022import org.hl7.fhir.utilities.TerminologyServiceOptions; 023import org.hl7.fhir.utilities.Utilities; 024 025import java.math.BigDecimal; 026import java.util.*; 027 028/*- 029 * #%L 030 * org.hl7.fhir.r4 031 * %% 032 * Copyright (C) 2014 - 2019 Health Level 7 033 * %% 034 * Licensed under the Apache License, Version 2.0 (the "License"); 035 * you may not use this file except in compliance with the License. 036 * You may obtain a copy of the License at 037 * 038 * http://www.apache.org/licenses/LICENSE-2.0 039 * 040 * Unless required by applicable law or agreed to in writing, software 041 * distributed under the License is distributed on an "AS IS" BASIS, 042 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 043 * See the License for the specific language governing permissions and 044 * limitations under the License. 045 * #L% 046 */ 047 048/** 049 * 050 * @author Grahame Grieve 051 * 052 */ 053public class FHIRPathEngine { 054 private enum Equality { Null, True, False } 055 056 private class FHIRConstant extends Base { 057 058 private static final long serialVersionUID = -8933773658248269439L; 059 private String value; 060 061 public FHIRConstant(String value) { 062 this.value = value; 063 } 064 065 @Override 066 public String fhirType() { 067 return "%constant"; 068 } 069 070 @Override 071 protected void listChildren(List<Property> result) { 072 } 073 074 @Override 075 public String getIdBase() { 076 return null; 077 } 078 079 @Override 080 public void setIdBase(String value) { 081 } 082 083 public String getValue() { 084 return value; 085 } 086 087 @Override 088 public String primitiveValue() { 089 return value; 090 } 091 } 092 093 private class ClassTypeInfo extends Base { 094 private static final long serialVersionUID = 4909223114071029317L; 095 private Base instance; 096 097 public ClassTypeInfo(Base instance) { 098 super(); 099 this.instance = instance; 100 } 101 102 @Override 103 public String fhirType() { 104 return "ClassInfo"; 105 } 106 107 @Override 108 protected void listChildren(List<Property> result) { 109 } 110 111 @Override 112 public String getIdBase() { 113 return null; 114 } 115 116 @Override 117 public void setIdBase(String value) { 118 } 119 public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException { 120 if (name.equals("name")) 121 return new Base[]{new StringType(getName())}; 122 else if (name.equals("namespace")) 123 return new Base[]{new StringType(getNamespace())}; 124 else 125 return super.getProperty(hash, name, checkValid); 126 } 127 128 private String getNamespace() { 129 if ((instance instanceof Resource)) 130 return "FHIR"; 131 else if (!(instance instanceof Element) || ((Element)instance).isDisallowExtensions()) 132 return "System"; 133 else 134 return "FHIR"; 135 } 136 137 private String getName() { 138 if ((instance instanceof Resource)) 139 return instance.fhirType(); 140 else if (!(instance instanceof Element) || ((Element)instance).isDisallowExtensions()) 141 return Utilities.capitalize(instance.fhirType()); 142 else 143 return instance.fhirType(); 144 } 145 } 146 147 private IWorkerContext worker; 148 private IEvaluationContext hostServices; 149 private StringBuilder log = new StringBuilder(); 150 private Set<String> primitiveTypes = new HashSet<String>(); 151 private Map<String, StructureDefinition> allTypes = new HashMap<String, StructureDefinition>(); 152 private boolean legacyMode; // some R2 and R3 constraints assume that != is valid for emptty sets, so when running for R2/R3, this is set ot true 153 private TerminologyServiceOptions terminologyServiceOptions = new TerminologyServiceOptions(); 154 155 // if the fhir path expressions are allowed to use constants beyond those defined in the specification 156 // the application can implement them by providing a constant resolver 157 public interface IEvaluationContext { 158 public class FunctionDetails { 159 private String description; 160 private int minParameters; 161 private int maxParameters; 162 public FunctionDetails(String description, int minParameters, int maxParameters) { 163 super(); 164 this.description = description; 165 this.minParameters = minParameters; 166 this.maxParameters = maxParameters; 167 } 168 public String getDescription() { 169 return description; 170 } 171 public int getMinParameters() { 172 return minParameters; 173 } 174 public int getMaxParameters() { 175 return maxParameters; 176 } 177 178 } 179 180 /** 181 * A constant reference - e.g. a reference to a name that must be resolved in context. 182 * The % will be removed from the constant name before this is invoked. 183 * 184 * This will also be called if the host invokes the FluentPath engine with a context of null 185 * 186 * @param appContext - content passed into the fluent path engine 187 * @param name - name reference to resolve 188 * @param beforeContext - whether this is being called before the name is resolved locally, or not 189 * @return the value of the reference (or null, if it's not valid, though can throw an exception if desired) 190 */ 191 public Base resolveConstant(Object appContext, String name, boolean beforeContext) throws PathEngineException; 192 public TypeDetails resolveConstantType(Object appContext, String name) throws PathEngineException; 193 194 /** 195 * when the .log() function is called 196 * 197 * @param argument 198 * @param focus 199 * @return 200 */ 201 public boolean log(String argument, List<Base> focus); 202 203 // extensibility for functions 204 /** 205 * 206 * @param functionName 207 * @return null if the function is not known 208 */ 209 public FunctionDetails resolveFunction(String functionName); 210 211 /** 212 * Check the function parameters, and throw an error if they are incorrect, or return the type for the function 213 * @param functionName 214 * @param parameters 215 * @return 216 */ 217 public TypeDetails checkFunction(Object appContext, String functionName, List<TypeDetails> parameters) throws PathEngineException; 218 219 /** 220 * @param appContext 221 * @param functionName 222 * @param parameters 223 * @return 224 */ 225 public List<Base> executeFunction(Object appContext, String functionName, List<List<Base>> parameters); 226 227 /** 228 * Implementation of resolve() function. Passed a string, return matching resource, if one is known - else null 229 * @appContext - passed in by the host to the FHIRPathEngine 230 * @param url the reference (Reference.reference or the value of the canonical 231 * @return 232 * @throws FHIRException 233 */ 234 public Base resolveReference(Object appContext, String url) throws FHIRException; 235 236 public boolean conformsToProfile(Object appContext, Base item, String url) throws FHIRException; 237 238 /* 239 * return the value set referenced by the url, which has been used in memberOf() 240 */ 241 public ValueSet resolveValueSet(Object appContext, String url); 242 } 243 244 245 /** 246 * @param worker - used when validating paths (@check), and used doing value set membership when executing tests (once that's defined) 247 */ 248 public FHIRPathEngine(IWorkerContext worker) { 249 super(); 250 this.worker = worker; 251 for (StructureDefinition sd : worker.allStructures()) { 252 if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() != StructureDefinitionKind.LOGICAL) 253 allTypes.put(sd.getName(), sd); 254 if (sd.getDerivation() == TypeDerivationRule.SPECIALIZATION && sd.getKind() == StructureDefinitionKind.PRIMITIVETYPE) { 255 primitiveTypes.add(sd.getName()); 256 } 257 } 258 } 259 260 261 // --- 3 methods to override in children ------------------------------------------------------- 262 // if you don't override, it falls through to the using the base reference implementation 263 // HAPI overrides to these to support extending the base model 264 265 public IEvaluationContext getHostServices() { 266 return hostServices; 267 } 268 269 270 public void setHostServices(IEvaluationContext constantResolver) { 271 this.hostServices = constantResolver; 272 } 273 274 275 /** 276 * Given an item, return all the children that conform to the pattern described in name 277 * 278 * Possible patterns: 279 * - a simple name (which may be the base of a name with [] e.g. value[x]) 280 * - a name with a type replacement e.g. valueCodeableConcept 281 * - * which means all children 282 * - ** which means all descendants 283 * 284 * @param item 285 * @param name 286 * @param result 287 * @throws FHIRException 288 */ 289 protected void getChildrenByName(Base item, String name, List<Base> result) throws FHIRException { 290 Base[] list = item.listChildrenByName(name, false); 291 if (list != null) 292 for (Base v : list) 293 if (v != null) 294 result.add(v); 295 } 296 297 298 public boolean isLegacyMode() { 299 return legacyMode; 300 } 301 302 303 public void setLegacyMode(boolean legacyMode) { 304 this.legacyMode = legacyMode; 305 } 306 307 308 // --- public API ------------------------------------------------------- 309 /** 310 * Parse a path for later use using execute 311 * 312 * @param path 313 * @return 314 * @throws PathEngineException 315 * @throws Exception 316 */ 317 public ExpressionNode parse(String path) throws FHIRLexerException { 318 return parse(path, null); 319 } 320 321 public ExpressionNode parse(String path, String name) throws FHIRLexerException { 322 FHIRLexer lexer = new FHIRLexer(path, name); 323 if (lexer.done()) 324 throw lexer.error("Path cannot be empty"); 325 ExpressionNode result = parseExpression(lexer, true); 326 if (!lexer.done()) 327 throw lexer.error("Premature ExpressionNode termination at unexpected token \""+lexer.getCurrent()+"\""); 328 result.check(); 329 return result; 330 } 331 332 public static class ExpressionNodeWithOffset { 333 private int offset; 334 private ExpressionNode node; 335 public ExpressionNodeWithOffset(int offset, ExpressionNode node) { 336 super(); 337 this.offset = offset; 338 this.node = node; 339 } 340 public int getOffset() { 341 return offset; 342 } 343 public ExpressionNode getNode() { 344 return node; 345 } 346 347 } 348 /** 349 * Parse a path for later use using execute 350 * 351 * @param path 352 * @return 353 * @throws PathEngineException 354 * @throws Exception 355 */ 356 public ExpressionNodeWithOffset parsePartial(String path, int i) throws FHIRLexerException { 357 FHIRLexer lexer = new FHIRLexer(path, i); 358 if (lexer.done()) 359 throw lexer.error("Path cannot be empty"); 360 ExpressionNode result = parseExpression(lexer, true); 361 result.check(); 362 return new ExpressionNodeWithOffset(lexer.getCurrentStart(), result); 363 } 364 365 /** 366 * Parse a path that is part of some other syntax 367 * 368 * @return 369 * @throws PathEngineException 370 * @throws Exception 371 */ 372 public ExpressionNode parse(FHIRLexer lexer) throws FHIRLexerException { 373 ExpressionNode result = parseExpression(lexer, true); 374 result.check(); 375 return result; 376 } 377 378 /** 379 * check that paths referred to in the ExpressionNode are valid 380 * 381 * xPathStartsWithValueRef is a hack work around for the fact that FHIR Path sometimes needs a different starting point than the xpath 382 * 383 * returns a list of the possible types that might be returned by executing the ExpressionNode against a particular context 384 * 385 * @param context - the logical type against which this path is applied 386 * @throws DefinitionException 387 * @throws PathEngineException 388 * @if the path is not valid 389 */ 390 public TypeDetails check(Object appContext, String resourceType, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException { 391 // if context is a path that refers to a type, do that conversion now 392 TypeDetails types; 393 if (context == null) { 394 types = null; // this is a special case; the first path reference will have to resolve to something in the context 395 } else if (!context.contains(".")) { 396 StructureDefinition sd = worker.fetchResource(StructureDefinition.class, context); 397 types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()); 398 } else { 399 String ctxt = context.substring(0, context.indexOf('.')); 400 if (Utilities.isAbsoluteUrl(resourceType)) { 401 ctxt = resourceType.substring(0, resourceType.lastIndexOf("/")+1)+ctxt; 402 } 403 StructureDefinition sd = worker.fetchResource(StructureDefinition.class, ctxt); 404 if (sd == null) 405 throw new PathEngineException("Unknown context "+context); 406 ElementDefinitionMatch ed = getElementDefinition(sd, context, true); 407 if (ed == null) 408 throw new PathEngineException("Unknown context element "+context); 409 if (ed.fixedType != null) 410 types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType); 411 else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType())) 412 types = new TypeDetails(CollectionStatus.SINGLETON, ctxt+"#"+context); 413 else { 414 types = new TypeDetails(CollectionStatus.SINGLETON); 415 for (TypeRefComponent t : ed.getDefinition().getType()) 416 types.addType(t.getCode()); 417 } 418 } 419 420 return executeType(new ExecutionTypeContext(appContext, resourceType, types, types), types, expr, true); 421 } 422 423 public TypeDetails check(Object appContext, StructureDefinition sd, String context, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException { 424 // if context is a path that refers to a type, do that conversion now 425 TypeDetails types; 426 if (!context.contains(".")) { 427 types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()); 428 } else { 429 ElementDefinitionMatch ed = getElementDefinition(sd, context, true); 430 if (ed == null) 431 throw new PathEngineException("Unknown context element "+context); 432 if (ed.fixedType != null) 433 types = new TypeDetails(CollectionStatus.SINGLETON, ed.fixedType); 434 else if (ed.getDefinition().getType().isEmpty() || isAbstractType(ed.getDefinition().getType())) 435 types = new TypeDetails(CollectionStatus.SINGLETON, sd.getUrl()+"#"+context); 436 else { 437 types = new TypeDetails(CollectionStatus.SINGLETON); 438 for (TypeRefComponent t : ed.getDefinition().getType()) 439 types.addType(t.getCode()); 440 } 441 } 442 443 return executeType(new ExecutionTypeContext(appContext, sd.getUrl(), types, types), types, expr, true); 444 } 445 446 public TypeDetails check(Object appContext, StructureDefinition sd, ExpressionNode expr) throws FHIRLexerException, PathEngineException, DefinitionException { 447 // if context is a path that refers to a type, do that conversion now 448 TypeDetails types = null; // this is a special case; the first path reference will have to resolve to something in the context 449 return executeType(new ExecutionTypeContext(appContext, sd == null ? null : sd.getUrl(), null, types), types, expr, true); 450 } 451 452 public TypeDetails check(Object appContext, String resourceType, String context, String expr) throws FHIRLexerException, PathEngineException, DefinitionException { 453 return check(appContext, resourceType, context, parse(expr)); 454 } 455 456 private int compareDateTimeElements(Base theL, Base theR, boolean theEquivalenceTest) { 457 String dateLeftString = theL.primitiveValue(); 458 DateTimeType dateLeft = new DateTimeType(dateLeftString); 459 460 String dateRightString = theR.primitiveValue(); 461 DateTimeType dateRight = new DateTimeType(dateRightString); 462 463 if (theEquivalenceTest) { 464 return dateLeft.equalsUsingFhirPathRules(dateRight) == Boolean.TRUE ? 0 : 1; 465 } 466 467 if (dateLeft.getPrecision().ordinal() > TemporalPrecisionEnum.DAY.ordinal()) { 468 dateLeft.setTimeZoneZulu(true); 469 } 470 if (dateRight.getPrecision().ordinal() > TemporalPrecisionEnum.DAY.ordinal()) { 471 dateRight.setTimeZoneZulu(true); 472 } 473 474 dateLeftString = dateLeft.getValueAsString(); 475 dateRightString = dateRight.getValueAsString(); 476 477 return dateLeftString.compareTo(dateRightString); 478 } 479 480 /** 481 * evaluate a path and return the matching elements 482 * 483 * @param base - the object against which the path is being evaluated 484 * @param ExpressionNode - the parsed ExpressionNode statement to use 485 * @return 486 * @throws FHIRException 487 * @ 488 */ 489 public List<Base> evaluate(Base base, ExpressionNode ExpressionNode) throws FHIRException { 490 List<Base> list = new ArrayList<Base>(); 491 if (base != null) 492 list.add(base); 493 log = new StringBuilder(); 494 return execute(new ExecutionContext(null, base != null && base.isResource() ? base : null, base != null && base.isResource() ? base : null, base, null, base), list, ExpressionNode, true); 495 } 496 497 /** 498 * evaluate a path and return the matching elements 499 * 500 * @param base - the object against which the path is being evaluated 501 * @param path - the FHIR Path statement to use 502 * @return 503 * @throws FHIRException 504 * @ 505 */ 506 public List<Base> evaluate(Base base, String path) throws FHIRException { 507 ExpressionNode exp = parse(path); 508 List<Base> list = new ArrayList<Base>(); 509 if (base != null) 510 list.add(base); 511 log = new StringBuilder(); 512 return execute(new ExecutionContext(null, base.isResource() ? base : null, base.isResource() ? base : null, base, null, base), list, exp, true); 513 } 514 515 /** 516 * evaluate a path and return the matching elements 517 * 518 * @param base - the object against which the path is being evaluated 519 * @param ExpressionNode - the parsed ExpressionNode statement to use 520 * @return 521 * @throws FHIRException 522 * @ 523 */ 524 public List<Base> evaluate(Object appContext, Resource focusResource, Resource rootResource, Base base, ExpressionNode ExpressionNode) throws FHIRException { 525 List<Base> list = new ArrayList<Base>(); 526 if (base != null) 527 list.add(base); 528 log = new StringBuilder(); 529 return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, ExpressionNode, true); 530 } 531 532 /** 533 * evaluate a path and return the matching elements 534 * 535 * @param base - the object against which the path is being evaluated 536 * @param ExpressionNode - the parsed ExpressionNode statement to use 537 * @return 538 * @throws FHIRException 539 * @ 540 */ 541 public List<Base> evaluate(Object appContext, Base focusResource, Base rootResource, Base base, ExpressionNode ExpressionNode) throws FHIRException { 542 List<Base> list = new ArrayList<Base>(); 543 if (base != null) 544 list.add(base); 545 log = new StringBuilder(); 546 return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, ExpressionNode, true); 547 } 548 549 /** 550 * evaluate a path and return the matching elements 551 * 552 * @param base - the object against which the path is being evaluated 553 * @param path - the FHIR Path statement to use 554 * @return 555 * @throws FHIRException 556 * @ 557 */ 558 public List<Base> evaluate(Object appContext, Resource focusResource, Resource rootResource, Base base, String path) throws FHIRException { 559 ExpressionNode exp = parse(path); 560 List<Base> list = new ArrayList<Base>(); 561 if (base != null) 562 list.add(base); 563 log = new StringBuilder(); 564 return execute(new ExecutionContext(appContext, focusResource, rootResource, base, null, base), list, exp, true); 565 } 566 567 /** 568 * evaluate a path and return true or false (e.g. for an invariant) 569 * 570 * @param base - the object against which the path is being evaluated 571 * @param path - the FHIR Path statement to use 572 * @return 573 * @throws FHIRException 574 * @ 575 */ 576 public boolean evaluateToBoolean(Resource focusResource, Resource rootResource, Base base, String path) throws FHIRException { 577 return convertToBoolean(evaluate(null, focusResource, rootResource, base, path)); 578 } 579 580 /** 581 * evaluate a path and return true or false (e.g. for an invariant) 582 * 583 * @param base - the object against which the path is being evaluated 584 * @return 585 * @throws FHIRException 586 * @ 587 */ 588 public boolean evaluateToBoolean(Resource focusResource, Resource rootResource, Base base, ExpressionNode node) throws FHIRException { 589 return convertToBoolean(evaluate(null, focusResource, rootResource, base, node)); 590 } 591 592 /** 593 * evaluate a path and return true or false (e.g. for an invariant) 594 * 595 * @param appInfo - application context 596 * @param base - the object against which the path is being evaluated 597 * @return 598 * @throws FHIRException 599 * @ 600 */ 601 public boolean evaluateToBoolean(Object appInfo, Resource focusResource, Resource rootResource, Base base, ExpressionNode node) throws FHIRException { 602 return convertToBoolean(evaluate(appInfo, focusResource, rootResource, base, node)); 603 } 604 605 /** 606 * evaluate a path and return true or false (e.g. for an invariant) 607 * 608 * @param base - the object against which the path is being evaluated 609 * @return 610 * @throws FHIRException 611 * @ 612 */ 613 public boolean evaluateToBoolean(Object appInfo, Base focusResource, Base rootResource, Base base, ExpressionNode node) throws FHIRException { 614 return convertToBoolean(evaluate(appInfo, focusResource, rootResource, base, node)); 615 } 616 617 /** 618 * evaluate a path and a string containing the outcome (for display) 619 * 620 * @param base - the object against which the path is being evaluated 621 * @param path - the FHIR Path statement to use 622 * @return 623 * @throws FHIRException 624 * @ 625 */ 626 public String evaluateToString(Base base, String path) throws FHIRException { 627 return convertToString(evaluate(base, path)); 628 } 629 630 public String evaluateToString(Object appInfo, Base focusResource, Base rootResource, Base base, ExpressionNode node) throws FHIRException { 631 return convertToString(evaluate(appInfo, focusResource, rootResource, base, node)); 632 } 633 634 /** 635 * worker routine for converting a set of objects to a string representation 636 * 637 * @param items - result from @evaluate 638 * @return 639 */ 640 public String convertToString(List<Base> items) { 641 StringBuilder b = new StringBuilder(); 642 boolean first = true; 643 for (Base item : items) { 644 if (first) 645 first = false; 646 else 647 b.append(','); 648 649 b.append(convertToString(item)); 650 } 651 return b.toString(); 652 } 653 654 public String convertToString(Base item) { 655 if (item.isPrimitive()) 656 return item.primitiveValue(); 657 else if (item instanceof Quantity) { 658 Quantity q = (Quantity) item; 659 if (q.getSystem().equals("http://unitsofmeasure.org")) { 660 String u = "'"+q.getCode()+"'"; 661 return q.getValue().toPlainString()+" "+u; 662 } 663 else 664 return item.toString(); 665 } else 666 return item.toString(); 667 } 668 669 /** 670 * worker routine for converting a set of objects to a boolean representation (for invariants) 671 * 672 * @param items - result from @evaluate 673 * @return 674 */ 675 public boolean convertToBoolean(List<Base> items) { 676 if (items == null) 677 return false; 678 else if (items.size() == 1 && items.get(0) instanceof BooleanType) 679 return ((BooleanType) items.get(0)).getValue(); 680 else if (items.size() == 1 && items.get(0).isBooleanPrimitive()) // element model 681 return Boolean.valueOf(items.get(0).primitiveValue()); 682 else 683 return items.size() > 0; 684 } 685 686 687 private void log(String name, List<Base> contents) { 688 if (hostServices == null || !hostServices.log(name, contents)) { 689 if (log.length() > 0) 690 log.append("; "); 691 log.append(name); 692 log.append(": "); 693 boolean first = true; 694 for (Base b : contents) { 695 if (first) 696 first = false; 697 else 698 log.append(","); 699 log.append(convertToString(b)); 700 } 701 } 702 } 703 704 public String forLog() { 705 if (log.length() > 0) 706 return " ("+log.toString()+")"; 707 else 708 return ""; 709 } 710 711 private class ExecutionContext { 712 private Object appInfo; 713 private Base focusResource; 714 private Base rootResource; 715 private Base context; 716 private Base thisItem; 717 private List<Base> total; 718 private Map<String, Base> aliases; 719 720 public ExecutionContext(Object appInfo, Base resource, Base rootResource, Base context, Map<String, Base> aliases, Base thisItem) { 721 this.appInfo = appInfo; 722 this.context = context; 723 this.focusResource = resource; 724 this.rootResource = rootResource; 725 this.aliases = aliases; 726 this.thisItem = thisItem; 727 } 728 public Base getFocusResource() { 729 return focusResource; 730 } 731 public Base getRootResource() { 732 return rootResource; 733 } 734 public Base getThisItem() { 735 return thisItem; 736 } 737 public List<Base> getTotal() { 738 return total; 739 } 740 public void addAlias(String name, List<Base> focus) throws FHIRException { 741 if (aliases == null) 742 aliases = new HashMap<String, Base>(); 743 else 744 aliases = new HashMap<String, Base>(aliases); // clone it, since it's going to change 745 if (focus.size() > 1) 746 throw new FHIRException("Attempt to alias a collection, not a singleton"); 747 aliases.put(name, focus.size() == 0 ? null : focus.get(0)); 748 } 749 public Base getAlias(String name) { 750 return aliases == null ? null : aliases.get(name); 751 } 752 } 753 754 private class ExecutionTypeContext { 755 private Object appInfo; 756 private String resource; 757 private TypeDetails context; 758 private TypeDetails thisItem; 759 private TypeDetails total; 760 761 762 public ExecutionTypeContext(Object appInfo, String resource, TypeDetails context, TypeDetails thisItem) { 763 super(); 764 this.appInfo = appInfo; 765 this.resource = resource; 766 this.context = context; 767 this.thisItem = thisItem; 768 769 } 770 public String getResource() { 771 return resource; 772 } 773 public TypeDetails getThisItem() { 774 return thisItem; 775 } 776 777 778 } 779 780 private ExpressionNode parseExpression(FHIRLexer lexer, boolean proximal) throws FHIRLexerException { 781 ExpressionNode result = new ExpressionNode(lexer.nextId()); 782 ExpressionNode wrapper = null; 783 SourceLocation c = lexer.getCurrentStartLocation(); 784 result.setStart(lexer.getCurrentLocation()); 785 // special: +/- represents a unary operation at this point, but cannot be a feature of the lexer, since that's not always true. 786 // so we back correct for both +/- and as part of a numeric constant below. 787 788 // special: +/- represents a unary operation at this point, but cannot be a feature of the lexer, since that's not always true. 789 // so we back correct for both +/- and as part of a numeric constant below. 790 if (Utilities.existsInList(lexer.getCurrent(), "-", "+")) { 791 wrapper = new ExpressionNode(lexer.nextId()); 792 wrapper.setKind(Kind.Unary); 793 wrapper.setOperation(ExpressionNode.Operation.fromCode(lexer.take())); 794 wrapper.setProximal(proximal); 795 } 796 797 if (lexer.isConstant()) { 798 boolean isString = lexer.isStringConstant(); 799 if (!isString && (lexer.getCurrent().startsWith("-") || lexer.getCurrent().startsWith("+"))) { 800 // the grammar says that this is a unary operation; it affects the correct processing order of the inner operations 801 wrapper = new ExpressionNode(lexer.nextId()); 802 wrapper.setKind(Kind.Unary); 803 wrapper.setOperation(ExpressionNode.Operation.fromCode(lexer.getCurrent().substring(0, 1))); 804 wrapper.setProximal(proximal); 805 lexer.setCurrent(lexer.getCurrent().substring(1)); 806 } 807 result.setConstant(processConstant(lexer)); 808 result.setKind(Kind.Constant); 809 if (!isString && !lexer.done() && (result.getConstant() instanceof IntegerType || result.getConstant() instanceof DecimalType) && (lexer.isStringConstant() || lexer.hasToken("year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds"))) { 810 // it's a quantity 811 String ucum = null; 812 if (lexer.hasToken("year", "years", "month", "months", "week", "weeks", "day", "days", "hour", "hours", "minute", "minutes", "second", "seconds", "millisecond", "milliseconds")) { 813 String s = lexer.take(); 814 if (s.equals("year") || s.equals("years")) 815 ucum = "a"; 816 else if (s.equals("month") || s.equals("months")) 817 ucum = "mo"; 818 else if (s.equals("week") || s.equals("weeks")) 819 ucum = "wk"; 820 else if (s.equals("day") || s.equals("days")) 821 ucum = "d"; 822 else if (s.equals("hour") || s.equals("hours")) 823 ucum = "h"; 824 else if (s.equals("minute") || s.equals("minutes")) 825 ucum = "min"; 826 else if (s.equals("second") || s.equals("seconds")) 827 ucum = "s"; 828 else // (s.equals("millisecond") || s.equals("milliseconds")) 829 ucum = "ms"; 830 } else 831 ucum = lexer.readConstant("units"); 832 result.setConstant(new Quantity().setValue(new BigDecimal(result.getConstant().primitiveValue())).setSystem("http://unitsofmeasure.org").setCode(ucum)); 833 } 834 result.setEnd(lexer.getCurrentLocation()); 835 } else if ("(".equals(lexer.getCurrent())) { 836 lexer.next(); 837 result.setKind(Kind.Group); 838 result.setGroup(parseExpression(lexer, true)); 839 if (!")".equals(lexer.getCurrent())) 840 throw lexer.error("Found "+lexer.getCurrent()+" expecting a \")\""); 841 result.setEnd(lexer.getCurrentLocation()); 842 lexer.next(); 843 } else { 844 if (!lexer.isToken() && !lexer.getCurrent().startsWith("`")) 845 throw lexer.error("Found "+lexer.getCurrent()+" expecting a token name"); 846 if (lexer.isFixedName()) 847 result.setName(lexer.readFixedName("Path Name")); 848 else 849 result.setName(lexer.take()); 850 result.setEnd(lexer.getCurrentLocation()); 851 if (!result.checkName()) 852 throw lexer.error("Found "+result.getName()+" expecting a valid token name"); 853 if ("(".equals(lexer.getCurrent())) { 854 Function f = Function.fromCode(result.getName()); 855 FunctionDetails details = null; 856 if (f == null) { 857 if (hostServices != null) 858 details = hostServices.resolveFunction(result.getName()); 859 if (details == null) 860 throw lexer.error("The name "+result.getName()+" is not a valid function name"); 861 f = Function.Custom; 862 } 863 result.setKind(Kind.Function); 864 result.setFunction(f); 865 lexer.next(); 866 while (!")".equals(lexer.getCurrent())) { 867 result.getParameters().add(parseExpression(lexer, true)); 868 if (",".equals(lexer.getCurrent())) 869 lexer.next(); 870 else if (!")".equals(lexer.getCurrent())) 871 throw lexer.error("The token "+lexer.getCurrent()+" is not expected here - either a \",\" or a \")\" expected"); 872 } 873 result.setEnd(lexer.getCurrentLocation()); 874 lexer.next(); 875 checkParameters(lexer, c, result, details); 876 } else 877 result.setKind(Kind.Name); 878 } 879 ExpressionNode focus = result; 880 if ("[".equals(lexer.getCurrent())) { 881 lexer.next(); 882 ExpressionNode item = new ExpressionNode(lexer.nextId()); 883 item.setKind(Kind.Function); 884 item.setFunction(ExpressionNode.Function.Item); 885 item.getParameters().add(parseExpression(lexer, true)); 886 if (!lexer.getCurrent().equals("]")) 887 throw lexer.error("The token "+lexer.getCurrent()+" is not expected here - a \"]\" expected"); 888 lexer.next(); 889 result.setInner(item); 890 focus = item; 891 } 892 if (".".equals(lexer.getCurrent())) { 893 lexer.next(); 894 focus.setInner(parseExpression(lexer, false)); 895 } 896 result.setProximal(proximal); 897 if (proximal) { 898 while (lexer.isOp()) { 899 focus.setOperation(ExpressionNode.Operation.fromCode(lexer.getCurrent())); 900 focus.setOpStart(lexer.getCurrentStartLocation()); 901 focus.setOpEnd(lexer.getCurrentLocation()); 902 lexer.next(); 903 focus.setOpNext(parseExpression(lexer, false)); 904 focus = focus.getOpNext(); 905 } 906 result = organisePrecedence(lexer, result); 907 } 908 if (wrapper != null) { 909 wrapper.setOpNext(result); 910 result.setProximal(false); 911 result = wrapper; 912 } 913 return result; 914 } 915 916 private ExpressionNode organisePrecedence(FHIRLexer lexer, ExpressionNode node) { 917 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Times, Operation.DivideBy, Operation.Div, Operation.Mod)); 918 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Plus, Operation.Minus, Operation.Concatenate)); 919 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Union)); 920 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.LessThan, Operation.Greater, Operation.LessOrEqual, Operation.GreaterOrEqual)); 921 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Is)); 922 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Equals, Operation.Equivalent, Operation.NotEquals, Operation.NotEquivalent)); 923 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.And)); 924 node = gatherPrecedence(lexer, node, EnumSet.of(Operation.Xor, Operation.Or)); 925 // last: implies 926 return node; 927 } 928 929 private ExpressionNode gatherPrecedence(FHIRLexer lexer, ExpressionNode start, EnumSet<Operation> ops) { 930 // work : boolean; 931 // focus, node, group : ExpressionNode; 932 933 assert(start.isProximal()); 934 935 // is there anything to do? 936 boolean work = false; 937 ExpressionNode focus = start.getOpNext(); 938 if (ops.contains(start.getOperation())) { 939 while (focus != null && focus.getOperation() != null) { 940 work = work || !ops.contains(focus.getOperation()); 941 focus = focus.getOpNext(); 942 } 943 } else { 944 while (focus != null && focus.getOperation() != null) { 945 work = work || ops.contains(focus.getOperation()); 946 focus = focus.getOpNext(); 947 } 948 } 949 if (!work) 950 return start; 951 952 // entry point: tricky 953 ExpressionNode group; 954 if (ops.contains(start.getOperation())) { 955 group = newGroup(lexer, start); 956 group.setProximal(true); 957 focus = start; 958 start = group; 959 } else { 960 ExpressionNode node = start; 961 962 focus = node.getOpNext(); 963 while (!ops.contains(focus.getOperation())) { 964 node = focus; 965 focus = focus.getOpNext(); 966 } 967 group = newGroup(lexer, focus); 968 node.setOpNext(group); 969 } 970 971 // now, at this point: 972 // group is the group we are adding to, it already has a .group property filled out. 973 // focus points at the group.group 974 do { 975 // run until we find the end of the sequence 976 while (ops.contains(focus.getOperation())) 977 focus = focus.getOpNext(); 978 if (focus.getOperation() != null) { 979 group.setOperation(focus.getOperation()); 980 group.setOpNext(focus.getOpNext()); 981 focus.setOperation(null); 982 focus.setOpNext(null); 983 // now look for another sequence, and start it 984 ExpressionNode node = group; 985 focus = group.getOpNext(); 986 if (focus != null) { 987 while (focus != null && !ops.contains(focus.getOperation())) { 988 node = focus; 989 focus = focus.getOpNext(); 990 } 991 if (focus != null) { // && (focus.Operation in Ops) - must be true 992 group = newGroup(lexer, focus); 993 node.setOpNext(group); 994 } 995 } 996 } 997 } 998 while (focus != null && focus.getOperation() != null); 999 return start; 1000 } 1001 1002 1003 private ExpressionNode newGroup(FHIRLexer lexer, ExpressionNode next) { 1004 ExpressionNode result = new ExpressionNode(lexer.nextId()); 1005 result.setKind(Kind.Group); 1006 result.setGroup(next); 1007 result.getGroup().setProximal(true); 1008 return result; 1009 } 1010 1011 private Base processConstant(FHIRLexer lexer) throws FHIRLexerException { 1012 if (lexer.isStringConstant()) { 1013 return new StringType(processConstantString(lexer.take(), lexer)).noExtensions(); 1014 } else if (Utilities.isInteger(lexer.getCurrent())) { 1015 return new IntegerType(lexer.take()).noExtensions(); 1016 } else if (Utilities.isDecimal(lexer.getCurrent(), false)) { 1017 return new DecimalType(lexer.take()).noExtensions(); 1018 } else if (Utilities.existsInList(lexer.getCurrent(), "true", "false")) { 1019 return new BooleanType(lexer.take()).noExtensions(); 1020 } else if (lexer.getCurrent().equals("{}")) { 1021 lexer.take(); 1022 return null; 1023 } else if (lexer.getCurrent().startsWith("%") || lexer.getCurrent().startsWith("@")) { 1024 return new FHIRConstant(lexer.take()); 1025 } else 1026 throw lexer.error("Invalid Constant "+lexer.getCurrent()); 1027 } 1028 1029 // procedure CheckParamCount(c : integer); 1030 // begin 1031 // if exp.Parameters.Count <> c then 1032 // raise lexer.error('The function "'+exp.name+'" requires '+inttostr(c)+' parameters', offset); 1033 // end; 1034 1035 private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int count) throws FHIRLexerException { 1036 if (exp.getParameters().size() != count) 1037 throw lexer.error("The function \""+exp.getName()+"\" requires "+Integer.toString(count)+" parameters", location.toString()); 1038 return true; 1039 } 1040 1041 private boolean checkParamCount(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, int countMin, int countMax) throws FHIRLexerException { 1042 if (exp.getParameters().size() < countMin || exp.getParameters().size() > countMax) 1043 throw lexer.error("The function \""+exp.getName()+"\" requires between "+Integer.toString(countMin)+" and "+Integer.toString(countMax)+" parameters", location.toString()); 1044 return true; 1045 } 1046 1047 private boolean checkParameters(FHIRLexer lexer, SourceLocation location, ExpressionNode exp, FunctionDetails details) throws FHIRLexerException { 1048 switch (exp.getFunction()) { 1049 case Empty: return checkParamCount(lexer, location, exp, 0); 1050 case Not: return checkParamCount(lexer, location, exp, 0); 1051 case Exists: return checkParamCount(lexer, location, exp, 0); 1052 case SubsetOf: return checkParamCount(lexer, location, exp, 1); 1053 case SupersetOf: return checkParamCount(lexer, location, exp, 1); 1054 case IsDistinct: return checkParamCount(lexer, location, exp, 0); 1055 case Distinct: return checkParamCount(lexer, location, exp, 0); 1056 case Count: return checkParamCount(lexer, location, exp, 0); 1057 case Where: return checkParamCount(lexer, location, exp, 1); 1058 case Select: return checkParamCount(lexer, location, exp, 1); 1059 case All: return checkParamCount(lexer, location, exp, 0, 1); 1060 case Repeat: return checkParamCount(lexer, location, exp, 1); 1061 case Aggregate: return checkParamCount(lexer, location, exp, 1, 2); 1062 case Item: return checkParamCount(lexer, location, exp, 1); 1063 case As: return checkParamCount(lexer, location, exp, 1); 1064 case OfType: return checkParamCount(lexer, location, exp, 1); 1065 case Type: return checkParamCount(lexer, location, exp, 0); 1066 case Is: return checkParamCount(lexer, location, exp, 1); 1067 case Single: return checkParamCount(lexer, location, exp, 0); 1068 case First: return checkParamCount(lexer, location, exp, 0); 1069 case Last: return checkParamCount(lexer, location, exp, 0); 1070 case Tail: return checkParamCount(lexer, location, exp, 0); 1071 case Skip: return checkParamCount(lexer, location, exp, 1); 1072 case Take: return checkParamCount(lexer, location, exp, 1); 1073 case Union: return checkParamCount(lexer, location, exp, 1); 1074 case Combine: return checkParamCount(lexer, location, exp, 1); 1075 case Intersect: return checkParamCount(lexer, location, exp, 1); 1076 case Exclude: return checkParamCount(lexer, location, exp, 1); 1077 case Iif: return checkParamCount(lexer, location, exp, 2,3); 1078 case Lower: return checkParamCount(lexer, location, exp, 0); 1079 case Upper: return checkParamCount(lexer, location, exp, 0); 1080 case ToChars: return checkParamCount(lexer, location, exp, 0); 1081 case Substring: return checkParamCount(lexer, location, exp, 1, 2); 1082 case StartsWith: return checkParamCount(lexer, location, exp, 1); 1083 case EndsWith: return checkParamCount(lexer, location, exp, 1); 1084 case Matches: return checkParamCount(lexer, location, exp, 1); 1085 case ReplaceMatches: return checkParamCount(lexer, location, exp, 2); 1086 case Contains: return checkParamCount(lexer, location, exp, 1); 1087 case Replace: return checkParamCount(lexer, location, exp, 2); 1088 case Length: return checkParamCount(lexer, location, exp, 0); 1089 case Children: return checkParamCount(lexer, location, exp, 0); 1090 case Descendants: return checkParamCount(lexer, location, exp, 0); 1091 case MemberOf: return checkParamCount(lexer, location, exp, 1); 1092 case Trace: return checkParamCount(lexer, location, exp, 1, 2); 1093 case Check: return checkParamCount(lexer, location, exp, 2); 1094 case Today: return checkParamCount(lexer, location, exp, 0); 1095 case Now: return checkParamCount(lexer, location, exp, 0); 1096 case Resolve: return checkParamCount(lexer, location, exp, 0); 1097 case Extension: return checkParamCount(lexer, location, exp, 1); 1098 case AllFalse: return checkParamCount(lexer, location, exp, 0); 1099 case AnyFalse: return checkParamCount(lexer, location, exp, 0); 1100 case AllTrue: return checkParamCount(lexer, location, exp, 0); 1101 case AnyTrue: return checkParamCount(lexer, location, exp, 0); 1102 case HasValue: return checkParamCount(lexer, location, exp, 0); 1103 case Alias: return checkParamCount(lexer, location, exp, 1); 1104 case AliasAs: return checkParamCount(lexer, location, exp, 1); 1105 case HtmlChecks: return checkParamCount(lexer, location, exp, 0); 1106 case ToInteger: return checkParamCount(lexer, location, exp, 0); 1107 case ToDecimal: return checkParamCount(lexer, location, exp, 0); 1108 case ToString: return checkParamCount(lexer, location, exp, 0); 1109 case ToQuantity: return checkParamCount(lexer, location, exp, 0); 1110 case ToBoolean: return checkParamCount(lexer, location, exp, 0); 1111 case ToDateTime: return checkParamCount(lexer, location, exp, 0); 1112 case ToTime: return checkParamCount(lexer, location, exp, 0); 1113 case ConvertsToInteger: return checkParamCount(lexer, location, exp, 0); 1114 case ConvertsToDecimal: return checkParamCount(lexer, location, exp, 0); 1115 case ConvertsToString: return checkParamCount(lexer, location, exp, 0); 1116 case ConvertsToQuantity: return checkParamCount(lexer, location, exp, 0); 1117 case ConvertsToBoolean: return checkParamCount(lexer, location, exp, 0); 1118 case ConvertsToDateTime: return checkParamCount(lexer, location, exp, 0); 1119 case ConvertsToTime: return checkParamCount(lexer, location, exp, 0); 1120 case ConformsTo: return checkParamCount(lexer, location, exp, 1); 1121 case Custom: return checkParamCount(lexer, location, exp, details.getMinParameters(), details.getMaxParameters()); 1122 } 1123 return false; 1124 } 1125 1126 private List<Base> execute(ExecutionContext context, List<Base> focus, ExpressionNode exp, boolean atEntry) throws FHIRException { 1127// System.out.println("Evaluate {'"+exp.toString()+"'} on "+focus.toString()); 1128 List<Base> work = new ArrayList<Base>(); 1129 switch (exp.getKind()) { 1130 case Unary: 1131 work.add(new IntegerType(0)); 1132 break; 1133 case Name: 1134 if (atEntry && exp.getName().equals("$this")) 1135 work.add(context.getThisItem()); 1136 else if (atEntry && exp.getName().equals("$total")) 1137 work.addAll(context.getTotal()); 1138 else 1139 for (Base item : focus) { 1140 List<Base> outcome = execute(context, item, exp, atEntry); 1141 for (Base base : outcome) 1142 if (base != null) 1143 work.add(base); 1144 } 1145 break; 1146 case Function: 1147 List<Base> work2 = evaluateFunction(context, focus, exp); 1148 work.addAll(work2); 1149 break; 1150 case Constant: 1151 Base b = resolveConstant(context, exp.getConstant(), false); 1152 if (b != null) 1153 work.add(b); 1154 break; 1155 case Group: 1156 work2 = execute(context, focus, exp.getGroup(), atEntry); 1157 work.addAll(work2); 1158 } 1159 1160 if (exp.getInner() != null) 1161 work = execute(context, work, exp.getInner(), false); 1162 1163 if (exp.isProximal() && exp.getOperation() != null) { 1164 ExpressionNode next = exp.getOpNext(); 1165 ExpressionNode last = exp; 1166 while (next != null) { 1167 List<Base> work2 = preOperate(work, last.getOperation()); 1168 if (work2 != null) 1169 work = work2; 1170 else if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As) { 1171 work2 = executeTypeName(context, focus, next, false); 1172 work = operate(context, work, last.getOperation(), work2); 1173 } else { 1174 work2 = execute(context, focus, next, true); 1175 work = operate(context, work, last.getOperation(), work2); 1176// System.out.println("Result of {'"+last.toString()+" "+last.getOperation().toCode()+" "+next.toString()+"'}: "+focus.toString()); 1177 } 1178 last = next; 1179 next = next.getOpNext(); 1180 } 1181 } 1182// System.out.println("Result of {'"+exp.toString()+"'}: "+work.toString()); 1183 return work; 1184 } 1185 1186 private List<Base> executeTypeName(ExecutionContext context, List<Base> focus, ExpressionNode next, boolean atEntry) { 1187 List<Base> result = new ArrayList<Base>(); 1188 if (next.getInner() != null) 1189 result.add(new StringType(next.getName()+"."+next.getInner().getName())); 1190 else 1191 result.add(new StringType(next.getName())); 1192 return result; 1193 } 1194 1195 1196 private List<Base> preOperate(List<Base> left, Operation operation) throws PathEngineException { 1197 if (left.size() == 0) 1198 return null; 1199 switch (operation) { 1200 case And: 1201 return isBoolean(left, false) ? makeBoolean(false) : null; 1202 case Or: 1203 return isBoolean(left, true) ? makeBoolean(true) : null; 1204 case Implies: 1205 Equality v = asBool(left); 1206 return v == Equality.False ? makeBoolean(true) : null; 1207 default: 1208 return null; 1209 } 1210 } 1211 1212 private List<Base> makeBoolean(boolean b) { 1213 List<Base> res = new ArrayList<Base>(); 1214 res.add(new BooleanType(b).noExtensions()); 1215 return res; 1216 } 1217 1218 private List<Base> makeNull() { 1219 List<Base> res = new ArrayList<Base>(); 1220 return res; 1221 } 1222 1223 private TypeDetails executeTypeName(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException { 1224 return new TypeDetails(CollectionStatus.SINGLETON, exp.getName()); 1225 } 1226 1227 private TypeDetails executeType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException { 1228 TypeDetails result = new TypeDetails(null); 1229 switch (exp.getKind()) { 1230 case Name: 1231 if (atEntry && exp.getName().equals("$this")) 1232 result.update(context.getThisItem()); 1233 else if (atEntry && exp.getName().equals("$total")) 1234 result.update(anything(CollectionStatus.UNORDERED)); 1235 else if (atEntry && focus == null) 1236 result.update(executeContextType(context, exp.getName())); 1237 else { 1238 for (String s : focus.getTypes()) { 1239 result.update(executeType(s, exp, atEntry)); 1240 } 1241 if (result.hasNoTypes()) 1242 throw new PathEngineException("The name "+exp.getName()+" is not valid for any of the possible types: "+focus.describe()); 1243 } 1244 break; 1245 case Function: 1246 result.update(evaluateFunctionType(context, focus, exp)); 1247 break; 1248 case Unary: 1249 result.addType("integer"); 1250 break; 1251 case Constant: 1252 result.update(resolveConstantType(context, exp.getConstant())); 1253 break; 1254 case Group: 1255 result.update(executeType(context, focus, exp.getGroup(), atEntry)); 1256 } 1257 exp.setTypes(result); 1258 1259 if (exp.getInner() != null) { 1260 result = executeType(context, result, exp.getInner(), false); 1261 } 1262 1263 if (exp.isProximal() && exp.getOperation() != null) { 1264 ExpressionNode next = exp.getOpNext(); 1265 ExpressionNode last = exp; 1266 while (next != null) { 1267 TypeDetails work; 1268 if (last.getOperation() == Operation.Is || last.getOperation() == Operation.As) 1269 work = executeTypeName(context, focus, next, atEntry); 1270 else 1271 work = executeType(context, focus, next, atEntry); 1272 result = operateTypes(result, last.getOperation(), work); 1273 last = next; 1274 next = next.getOpNext(); 1275 } 1276 exp.setOpTypes(result); 1277 } 1278 return result; 1279 } 1280 1281 private Base resolveConstant(ExecutionContext context, Base constant, boolean beforeContext) throws PathEngineException { 1282 if (!(constant instanceof FHIRConstant)) 1283 return constant; 1284 FHIRConstant c = (FHIRConstant) constant; 1285 if (c.getValue().startsWith("%")) { 1286 return resolveConstant(context, c.getValue(), beforeContext); 1287 } else if (c.getValue().startsWith("@")) { 1288 return processDateConstant(context.appInfo, c.getValue().substring(1)); 1289 } else 1290 throw new PathEngineException("Invaild FHIR Constant "+c.getValue()); 1291 } 1292 1293 private Base processDateConstant(Object appInfo, String value) throws PathEngineException { 1294 if (value.startsWith("T")) 1295 return new TimeType(value.substring(1)).noExtensions(); 1296 String v = value; 1297 if (v.length() > 10) { 1298 int i = v.substring(10).indexOf("-"); 1299 if (i == -1) 1300 i = v.substring(10).indexOf("+"); 1301 if (i == -1) 1302 i = v.substring(10).indexOf("Z"); 1303 v = i == -1 ? value : v.substring(0, 10+i); 1304 } 1305 if (v.length() > 10) 1306 return new DateTimeType(value).noExtensions(); 1307 else 1308 return new DateType(value).noExtensions(); 1309 } 1310 1311 1312 private Base resolveConstant(ExecutionContext context, String s, boolean beforeContext) throws PathEngineException { 1313 if (s.equals("%sct")) 1314 return new StringType("http://snomed.info/sct").noExtensions(); 1315 else if (s.equals("%loinc")) 1316 return new StringType("http://loinc.org").noExtensions(); 1317 else if (s.equals("%ucum")) 1318 return new StringType("http://unitsofmeasure.org").noExtensions(); 1319 else if (s.equals("%resource")) { 1320 if (context.focusResource == null) 1321 throw new PathEngineException("Cannot use %resource in this context"); 1322 return context.focusResource; 1323 } else if (s.equals("%rootResource")) { 1324 if (context.rootResource == null) 1325 throw new PathEngineException("Cannot use %rootResource in this context"); 1326 return context.rootResource; 1327 } else if (s.equals("%context")) { 1328 return context.context; 1329 } else if (s.equals("%us-zip")) 1330 return new StringType("[0-9]{5}(-[0-9]{4}){0,1}").noExtensions(); 1331 else if (s.startsWith("%`vs-")) 1332 return new StringType("http://hl7.org/fhir/ValueSet/"+s.substring(5, s.length()-1)+"").noExtensions(); 1333 else if (s.startsWith("%`cs-")) 1334 return new StringType("http://hl7.org/fhir/"+s.substring(5, s.length()-1)+"").noExtensions(); 1335 else if (s.startsWith("%`ext-")) 1336 return new StringType("http://hl7.org/fhir/StructureDefinition/"+s.substring(6, s.length()-1)).noExtensions(); 1337 else if (hostServices == null) 1338 throw new PathEngineException("Unknown fixed constant '"+s+"'"); 1339 else 1340 return hostServices.resolveConstant(context.appInfo, s.substring(1), beforeContext); 1341 } 1342 1343 1344 private String processConstantString(String s, FHIRLexer lexer) throws FHIRLexerException { 1345 StringBuilder b = new StringBuilder(); 1346 int i = 1; 1347 while (i < s.length()-1) { 1348 char ch = s.charAt(i); 1349 if (ch == '\\') { 1350 i++; 1351 switch (s.charAt(i)) { 1352 case 't': 1353 b.append('\t'); 1354 break; 1355 case 'r': 1356 b.append('\r'); 1357 break; 1358 case 'n': 1359 b.append('\n'); 1360 break; 1361 case 'f': 1362 b.append('\f'); 1363 break; 1364 case '\'': 1365 b.append('\''); 1366 break; 1367 case '"': 1368 b.append('"'); 1369 break; 1370 case '`': 1371 b.append('`'); 1372 break; 1373 case '\\': 1374 b.append('\\'); 1375 break; 1376 case '/': 1377 b.append('/'); 1378 break; 1379 case 'u': 1380 i++; 1381 int uc = Integer.parseInt(s.substring(i, i+4), 16); 1382 b.append((char) uc); 1383 i = i + 3; 1384 break; 1385 default: 1386 throw lexer.error("Unknown character escape \\"+s.charAt(i)); 1387 } 1388 i++; 1389 } else { 1390 b.append(ch); 1391 i++; 1392 } 1393 } 1394 return b.toString(); 1395 } 1396 1397 1398 private List<Base> operate(ExecutionContext context, List<Base> left, Operation operation, List<Base> right) throws FHIRException { 1399 switch (operation) { 1400 case Equals: return opEquals(left, right); 1401 case Equivalent: return opEquivalent(left, right); 1402 case NotEquals: return opNotEquals(left, right); 1403 case NotEquivalent: return opNotEquivalent(left, right); 1404 case LessThan: return opLessThan(left, right); 1405 case Greater: return opGreater(left, right); 1406 case LessOrEqual: return opLessOrEqual(left, right); 1407 case GreaterOrEqual: return opGreaterOrEqual(left, right); 1408 case Union: return opUnion(left, right); 1409 case In: return opIn(left, right); 1410 case MemberOf: return opMemberOf(context, left, right); 1411 case Contains: return opContains(left, right); 1412 case Or: return opOr(left, right); 1413 case And: return opAnd(left, right); 1414 case Xor: return opXor(left, right); 1415 case Implies: return opImplies(left, right); 1416 case Plus: return opPlus(left, right); 1417 case Times: return opTimes(left, right); 1418 case Minus: return opMinus(left, right); 1419 case Concatenate: return opConcatenate(left, right); 1420 case DivideBy: return opDivideBy(left, right); 1421 case Div: return opDiv(left, right); 1422 case Mod: return opMod(left, right); 1423 case Is: return opIs(left, right); 1424 case As: return opAs(left, right); 1425 default: 1426 throw new Error("Not Done Yet: "+operation.toCode()); 1427 } 1428 } 1429 1430 private List<Base> opAs(List<Base> left, List<Base> right) { 1431 List<Base> result = new ArrayList<>(); 1432 if (right.size() != 1) 1433 return result; 1434 else { 1435 String tn = convertToString(right); 1436 for (Base nextLeft : left) { 1437 if (tn.equals(nextLeft.fhirType())) 1438 result.add(nextLeft); 1439 } 1440 } 1441 return result; 1442 } 1443 1444 1445 private List<Base> opIs(List<Base> left, List<Base> right) { 1446 List<Base> result = new ArrayList<Base>(); 1447 if (left.size() != 1 || right.size() != 1) 1448 result.add(new BooleanType(false).noExtensions()); 1449 else { 1450 String tn = convertToString(right); 1451 if (left.get(0) instanceof org.hl7.fhir.r4.elementmodel.Element) 1452 result.add(new BooleanType(left.get(0).hasType(tn)).noExtensions()); 1453 else if ((left.get(0) instanceof Element) && ((Element) left.get(0)).isDisallowExtensions()) 1454 result.add(new BooleanType(Utilities.capitalize(left.get(0).fhirType()).equals(tn) || ("System."+Utilities.capitalize(left.get(0).fhirType())).equals(tn)).noExtensions()); 1455 else 1456 result.add(new BooleanType(left.get(0).hasType(tn)).noExtensions()); 1457 } 1458 return result; 1459 } 1460 1461 1462 private TypeDetails operateTypes(TypeDetails left, Operation operation, TypeDetails right) { 1463 switch (operation) { 1464 case Equals: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1465 case Equivalent: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1466 case NotEquals: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1467 case NotEquivalent: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1468 case LessThan: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1469 case Greater: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1470 case LessOrEqual: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1471 case GreaterOrEqual: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1472 case Is: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1473 case As: return new TypeDetails(CollectionStatus.SINGLETON, right.getTypes()); 1474 case Union: return left.union(right); 1475 case Or: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1476 case And: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1477 case Xor: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1478 case Implies : return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1479 case Times: 1480 TypeDetails result = new TypeDetails(CollectionStatus.SINGLETON); 1481 if (left.hasType(worker, "integer") && right.hasType(worker, "integer")) 1482 result.addType(TypeDetails.FP_Integer); 1483 else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal")) 1484 result.addType(TypeDetails.FP_Decimal); 1485 return result; 1486 case DivideBy: 1487 result = new TypeDetails(CollectionStatus.SINGLETON); 1488 if (left.hasType(worker, "integer") && right.hasType(worker, "integer")) 1489 result.addType(TypeDetails.FP_Decimal); 1490 else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal")) 1491 result.addType(TypeDetails.FP_Decimal); 1492 return result; 1493 case Concatenate: 1494 result = new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 1495 return result; 1496 case Plus: 1497 result = new TypeDetails(CollectionStatus.SINGLETON); 1498 if (left.hasType(worker, "integer") && right.hasType(worker, "integer")) 1499 result.addType(TypeDetails.FP_Integer); 1500 else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal")) 1501 result.addType(TypeDetails.FP_Decimal); 1502 else if (left.hasType(worker, "string", "id", "code", "uri") && right.hasType(worker, "string", "id", "code", "uri")) 1503 result.addType(TypeDetails.FP_String); 1504 return result; 1505 case Minus: 1506 result = new TypeDetails(CollectionStatus.SINGLETON); 1507 if (left.hasType(worker, "integer") && right.hasType(worker, "integer")) 1508 result.addType(TypeDetails.FP_Integer); 1509 else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal")) 1510 result.addType(TypeDetails.FP_Decimal); 1511 return result; 1512 case Div: 1513 case Mod: 1514 result = new TypeDetails(CollectionStatus.SINGLETON); 1515 if (left.hasType(worker, "integer") && right.hasType(worker, "integer")) 1516 result.addType(TypeDetails.FP_Integer); 1517 else if (left.hasType(worker, "integer", "decimal") && right.hasType(worker, "integer", "decimal")) 1518 result.addType(TypeDetails.FP_Decimal); 1519 return result; 1520 case In: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1521 case MemberOf: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1522 case Contains: return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 1523 default: 1524 return null; 1525 } 1526 } 1527 1528 1529 private List<Base> opEquals(List<Base> left, List<Base> right) { 1530 if (left.size() == 0 || right.size() == 0) 1531 return new ArrayList<Base>(); 1532 1533 if (left.size() != right.size()) 1534 return makeBoolean(false); 1535 1536 boolean res = true; 1537 boolean nil = false; 1538 for (int i = 0; i < left.size(); i++) { 1539 Boolean eq = doEquals(left.get(i), right.get(i)); 1540 if (eq == null) 1541 nil = true; 1542 else if (eq == false) { 1543 res = false; 1544 break; 1545 } 1546 } 1547 if (!res) 1548 return makeBoolean(res); 1549 else if (nil) 1550 return new ArrayList<Base>(); 1551 else 1552 return makeBoolean(res); 1553 } 1554 1555 private List<Base> opNotEquals(List<Base> left, List<Base> right) { 1556 if (!legacyMode && (left.size() == 0 || right.size() == 0)) 1557 return new ArrayList<Base>(); 1558 1559 if (left.size() != right.size()) 1560 return makeBoolean(true); 1561 1562 boolean res = true; 1563 boolean nil = false; 1564 for (int i = 0; i < left.size(); i++) { 1565 Boolean eq = doEquals(left.get(i), right.get(i)); 1566 if (eq == null) 1567 nil = true; 1568 else if (eq == true) { 1569 res = false; 1570 break; 1571 } 1572 } 1573 if (!res) 1574 return makeBoolean(res); 1575 else if (nil) 1576 return new ArrayList<Base>(); 1577 else 1578 return makeBoolean(res); 1579 } 1580 1581 private String removeTrailingZeros(String s) { 1582 if (Utilities.noString(s)) 1583 return ""; 1584 int i = s.length()-1; 1585 boolean done = false; 1586 boolean dot = false; 1587 while (i > 0 && !done) { 1588 if (s.charAt(i) == '.') { 1589 i--; 1590 dot = true; 1591 } 1592 else if (!dot && s.charAt(i) == '0') 1593 i--; 1594 else 1595 done = true; 1596 } 1597 return s.substring(0, i+1); 1598 } 1599 1600 private boolean decEqual(String left, String right) { 1601 left = removeTrailingZeros(left); 1602 right = removeTrailingZeros(right); 1603 return left.equals(right); 1604 } 1605 1606 private Boolean compareDates(BaseDateTimeType left, BaseDateTimeType right) { 1607 return left.equalsUsingFhirPathRules(right); 1608 } 1609 1610 private Boolean doEquals(Base left, Base right) { 1611 if (left instanceof Quantity && right instanceof Quantity) 1612 return qtyEqual((Quantity) left, (Quantity) right); 1613 else if (left.isDateTime() && right.isDateTime()) { 1614 return compareDates(left.dateTimeValue(), right.dateTimeValue()); 1615 } else if (left instanceof DecimalType || right instanceof DecimalType) 1616 return decEqual(left.primitiveValue(), right.primitiveValue()); 1617 else if (left.isPrimitive() && right.isPrimitive()) 1618 return Base.equals(left.primitiveValue(), right.primitiveValue()); 1619 else 1620 return Base.compareDeep(left, right, false); 1621 } 1622 1623 1624 private boolean doEquivalent(Base left, Base right) throws PathEngineException { 1625 if (left instanceof Quantity && right instanceof Quantity) 1626 return qtyEquivalent((Quantity) left, (Quantity) right); 1627 if (left.hasType("integer") && right.hasType("integer")) 1628 return doEquals(left, right); 1629 if (left.hasType("boolean") && right.hasType("boolean")) 1630 return doEquals(left, right); 1631 if (left.hasType("integer", "decimal", "unsignedInt", "positiveInt") && right.hasType("integer", "decimal", "unsignedInt", "positiveInt")) 1632 return Utilities.equivalentNumber(left.primitiveValue(), right.primitiveValue()); 1633 if (left.hasType("date", "dateTime", "time", "instant") && right.hasType("date", "dateTime", "time", "instant")) 1634 return compareDateTimeElements(left, right, true) == 0; 1635 if (left.hasType(FHIR_TYPES_STRING) && right.hasType(FHIR_TYPES_STRING)) 1636 return Utilities.equivalent(convertToString(left), convertToString(right)); 1637 1638 throw new PathEngineException(String.format("Unable to determine equivalence between %s and %s", left.fhirType(), right.fhirType())); 1639 } 1640 1641 private boolean qtyEqual(Quantity left, Quantity right) { 1642 if (worker.getUcumService() != null) { 1643 DecimalType dl = qtyToCanonical(left); 1644 DecimalType dr = qtyToCanonical(right); 1645 if (dl != null && dr != null) 1646 return doEquals(dl, dr); 1647 } 1648 return left.equals(right); 1649 } 1650 1651 private DecimalType qtyToCanonical(Quantity q) { 1652 if (!"http://unitsofmeasure.org".equals(q.getSystem())) 1653 return null; 1654 try { 1655 Pair p = new Pair(new Decimal(q.getValue().toPlainString()), q.getCode()); 1656 Pair c = worker.getUcumService().getCanonicalForm(p); 1657 return new DecimalType(c.getValue().asDecimal()); 1658 } catch (UcumException e) { 1659 return null; 1660 } 1661 } 1662 1663 private Base pairToQty(Pair p) { 1664 return new Quantity().setValue(new BigDecimal(p.getValue().toString())).setSystem("http://unitsofmeasure.org").setCode(p.getCode()).noExtensions(); 1665 } 1666 1667 1668 private Pair qtyToPair(Quantity q) { 1669 if (!"http://unitsofmeasure.org".equals(q.getSystem())) 1670 return null; 1671 try { 1672 return new Pair(new Decimal(q.getValue().toPlainString()), q.getCode()); 1673 } catch (UcumException e) { 1674 return null; 1675 } 1676 } 1677 1678 1679 private boolean qtyEquivalent(Quantity left, Quantity right) throws PathEngineException { 1680 if (worker.getUcumService() != null) { 1681 DecimalType dl = qtyToCanonical(left); 1682 DecimalType dr = qtyToCanonical(right); 1683 if (dl != null && dr != null) 1684 return doEquivalent(dl, dr); 1685 } 1686 return left.equals(right); 1687 } 1688 1689 1690 1691 private List<Base> opEquivalent(List<Base> left, List<Base> right) throws PathEngineException { 1692 if (left.size() != right.size()) 1693 return makeBoolean(false); 1694 1695 boolean res = true; 1696 for (int i = 0; i < left.size(); i++) { 1697 boolean found = false; 1698 for (int j = 0; j < right.size(); j++) { 1699 if (doEquivalent(left.get(i), right.get(j))) { 1700 found = true; 1701 break; 1702 } 1703 } 1704 if (!found) { 1705 res = false; 1706 break; 1707 } 1708 } 1709 return makeBoolean(res); 1710 } 1711 1712 private List<Base> opNotEquivalent(List<Base> left, List<Base> right) throws PathEngineException { 1713 if (left.size() != right.size()) 1714 return makeBoolean(true); 1715 1716 boolean res = true; 1717 for (int i = 0; i < left.size(); i++) { 1718 boolean found = false; 1719 for (int j = 0; j < right.size(); j++) { 1720 if (doEquivalent(left.get(i), right.get(j))) { 1721 found = true; 1722 break; 1723 } 1724 } 1725 if (!found) { 1726 res = false; 1727 break; 1728 } 1729 } 1730 return makeBoolean(!res); 1731 } 1732 1733 private final static String[] FHIR_TYPES_STRING = new String[] {"string", "uri", "code", "oid", "id", "uuid", "sid", "markdown", "base64Binary", "canonical", "url"}; 1734 1735 private List<Base> opLessThan(List<Base> left, List<Base> right) throws FHIRException { 1736 if (left.size() == 0 || right.size() == 0) 1737 return new ArrayList<Base>(); 1738 1739 if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) { 1740 Base l = left.get(0); 1741 Base r = right.get(0); 1742 if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 1743 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0); 1744 else if ((l.hasType("integer") || l.hasType("decimal")) && (r.hasType("integer") || r.hasType("decimal"))) 1745 return makeBoolean(new Double(l.primitiveValue()) < new Double(r.primitiveValue())); 1746 else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant"))) 1747 return makeBoolean(compareDateTimeElements(l, r, false) < 0); 1748 else if ((l.hasType("time")) && (r.hasType("time"))) 1749 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) < 0); 1750 else 1751 throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType()); 1752 } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) { 1753 List<Base> lUnit = left.get(0).listChildrenByName("code"); 1754 List<Base> rUnit = right.get(0).listChildrenByName("code"); 1755 if (Base.compareDeep(lUnit, rUnit, true)) { 1756 return opLessThan(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value")); 1757 } else { 1758 if (worker.getUcumService() == null) 1759 return makeBoolean(false); 1760 else { 1761 List<Base> dl = new ArrayList<Base>(); 1762 dl.add(qtyToCanonical((Quantity) left.get(0))); 1763 List<Base> dr = new ArrayList<Base>(); 1764 dr.add(qtyToCanonical((Quantity) right.get(0))); 1765 return opLessThan(dl, dr); 1766 } 1767 } 1768 } 1769 return new ArrayList<Base>(); 1770 } 1771 1772 private List<Base> opGreater(List<Base> left, List<Base> right) throws FHIRException { 1773 if (left.size() == 0 || right.size() == 0) 1774 return new ArrayList<Base>(); 1775 if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) { 1776 Base l = left.get(0); 1777 Base r = right.get(0); 1778 if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 1779 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0); 1780 else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 1781 return makeBoolean(new Double(l.primitiveValue()) > new Double(r.primitiveValue())); 1782 else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant"))) 1783 return makeBoolean(compareDateTimeElements(l, r, false) > 0); 1784 else if ((l.hasType("time")) && (r.hasType("time"))) 1785 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) > 0); 1786 else 1787 throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType()); 1788 } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) { 1789 List<Base> lUnit = left.get(0).listChildrenByName("unit"); 1790 List<Base> rUnit = right.get(0).listChildrenByName("unit"); 1791 if (Base.compareDeep(lUnit, rUnit, true)) { 1792 return opGreater(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value")); 1793 } else { 1794 if (worker.getUcumService() == null) 1795 return makeBoolean(false); 1796 else { 1797 List<Base> dl = new ArrayList<Base>(); 1798 dl.add(qtyToCanonical((Quantity) left.get(0))); 1799 List<Base> dr = new ArrayList<Base>(); 1800 dr.add(qtyToCanonical((Quantity) right.get(0))); 1801 return opGreater(dl, dr); 1802 } 1803 } 1804 } 1805 return new ArrayList<Base>(); 1806 } 1807 1808 private List<Base> opLessOrEqual(List<Base> left, List<Base> right) throws FHIRException { 1809 if (left.size() == 0 || right.size() == 0) 1810 return new ArrayList<Base>(); 1811 if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) { 1812 Base l = left.get(0); 1813 Base r = right.get(0); 1814 if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 1815 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0); 1816 else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 1817 return makeBoolean(new Double(l.primitiveValue()) <= new Double(r.primitiveValue())); 1818 else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant"))) 1819 return makeBoolean(compareDateTimeElements(l, r, false) <= 0); 1820 else if ((l.hasType("time")) && (r.hasType("time"))) 1821 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) <= 0); 1822 else 1823 throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType()); 1824 } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) { 1825 List<Base> lUnits = left.get(0).listChildrenByName("unit"); 1826 String lunit = lUnits.size() == 1 ? lUnits.get(0).primitiveValue() : null; 1827 List<Base> rUnits = right.get(0).listChildrenByName("unit"); 1828 String runit = rUnits.size() == 1 ? rUnits.get(0).primitiveValue() : null; 1829 if ((lunit == null && runit == null) || lunit.equals(runit)) { 1830 return opLessOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value")); 1831 } else { 1832 if (worker.getUcumService() == null) 1833 return makeBoolean(false); 1834 else { 1835 List<Base> dl = new ArrayList<Base>(); 1836 dl.add(qtyToCanonical((Quantity) left.get(0))); 1837 List<Base> dr = new ArrayList<Base>(); 1838 dr.add(qtyToCanonical((Quantity) right.get(0))); 1839 return opLessOrEqual(dl, dr); 1840 } 1841 } 1842 } 1843 return new ArrayList<Base>(); 1844 } 1845 1846 private List<Base> opGreaterOrEqual(List<Base> left, List<Base> right) throws FHIRException { 1847 if (left.size() == 0 || right.size() == 0) 1848 return new ArrayList<Base>(); 1849 if (left.size() == 1 && right.size() == 1 && left.get(0).isPrimitive() && right.get(0).isPrimitive()) { 1850 Base l = left.get(0); 1851 Base r = right.get(0); 1852 if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 1853 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0); 1854 else if ((l.hasType("integer", "decimal", "unsignedInt", "positiveInt")) && (r.hasType("integer", "decimal", "unsignedInt", "positiveInt"))) 1855 return makeBoolean(new Double(l.primitiveValue()) >= new Double(r.primitiveValue())); 1856 else if ((l.hasType("date", "dateTime", "instant")) && (r.hasType("date", "dateTime", "instant"))) 1857 return makeBoolean(compareDateTimeElements(l, r, false) >= 0); 1858 else if ((l.hasType("time")) && (r.hasType("time"))) 1859 return makeBoolean(l.primitiveValue().compareTo(r.primitiveValue()) >= 0); 1860 else 1861 throw new PathEngineException("Unable to compare values of type "+l.fhirType()+" and "+r.fhirType()); 1862 } else if (left.size() == 1 && right.size() == 1 && left.get(0).fhirType().equals("Quantity") && right.get(0).fhirType().equals("Quantity") ) { 1863 List<Base> lUnit = left.get(0).listChildrenByName("unit"); 1864 List<Base> rUnit = right.get(0).listChildrenByName("unit"); 1865 if (Base.compareDeep(lUnit, rUnit, true)) { 1866 return opGreaterOrEqual(left.get(0).listChildrenByName("value"), right.get(0).listChildrenByName("value")); 1867 } else { 1868 if (worker.getUcumService() == null) 1869 return makeBoolean(false); 1870 else { 1871 List<Base> dl = new ArrayList<Base>(); 1872 dl.add(qtyToCanonical((Quantity) left.get(0))); 1873 List<Base> dr = new ArrayList<Base>(); 1874 dr.add(qtyToCanonical((Quantity) right.get(0))); 1875 return opGreaterOrEqual(dl, dr); 1876 } 1877 } 1878 } 1879 return new ArrayList<Base>(); 1880 } 1881 1882 private List<Base> opMemberOf(ExecutionContext context, List<Base> left, List<Base> right) throws FHIRException { 1883 boolean ans = false; 1884 ValueSet vs = hostServices != null ? hostServices.resolveValueSet(context.appInfo, right.get(0).primitiveValue()) : worker.fetchResource(ValueSet.class, right.get(0).primitiveValue()); 1885 if (vs != null) { 1886 for (Base l : left) { 1887 if (l.fhirType().equals("code")) { 1888 if (worker.validateCode(terminologyServiceOptions , l.castToCoding(l), vs).isOk()) 1889 ans = true; 1890 } else if (l.fhirType().equals("Coding")) { 1891 if (worker.validateCode(terminologyServiceOptions, l.castToCoding(l), vs).isOk()) 1892 ans = true; 1893 } else if (l.fhirType().equals("CodeableConcept")) { 1894 if (worker.validateCode(terminologyServiceOptions, l.castToCodeableConcept(l), vs).isOk()) 1895 ans = true; 1896 } 1897 } 1898 } 1899 return makeBoolean(ans); 1900 } 1901 1902 private List<Base> opIn(List<Base> left, List<Base> right) throws FHIRException { 1903 if (left.size() == 0) 1904 return new ArrayList<Base>(); 1905 if (right.size() == 0) 1906 return makeBoolean(false); 1907 boolean ans = true; 1908 for (Base l : left) { 1909 boolean f = false; 1910 for (Base r : right) { 1911 Boolean eq = doEquals(l, r); 1912 if (eq != null && eq == true) { 1913 f = true; 1914 break; 1915 } 1916 } 1917 if (!f) { 1918 ans = false; 1919 break; 1920 } 1921 } 1922 return makeBoolean(ans); 1923 } 1924 1925 private List<Base> opContains(List<Base> left, List<Base> right) { 1926 if (left.size() == 0 || right.size() == 0) 1927 return new ArrayList<Base>(); 1928 boolean ans = true; 1929 for (Base r : right) { 1930 boolean f = false; 1931 for (Base l : left) { 1932 Boolean eq = doEquals(l, r); 1933 if (eq != null && eq == true) { 1934 f = true; 1935 break; 1936 } 1937 } 1938 if (!f) { 1939 ans = false; 1940 break; 1941 } 1942 } 1943 return makeBoolean(ans); 1944 } 1945 1946 private List<Base> opPlus(List<Base> left, List<Base> right) throws PathEngineException { 1947 if (left.size() == 0 || right.size() == 0) 1948 return new ArrayList<Base>(); 1949 if (left.size() > 1) 1950 throw new PathEngineException("Error performing +: left operand has more than one value"); 1951 if (!left.get(0).isPrimitive()) 1952 throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType())); 1953 if (right.size() > 1) 1954 throw new PathEngineException("Error performing +: right operand has more than one value"); 1955 if (!right.get(0).isPrimitive()) 1956 throw new PathEngineException(String.format("Error performing +: right operand has the wrong type (%s)", right.get(0).fhirType())); 1957 1958 List<Base> result = new ArrayList<Base>(); 1959 Base l = left.get(0); 1960 Base r = right.get(0); 1961 if (l.hasType(FHIR_TYPES_STRING) && r.hasType(FHIR_TYPES_STRING)) 1962 result.add(new StringType(l.primitiveValue() + r.primitiveValue())); 1963 else if (l.hasType("integer") && r.hasType("integer")) 1964 result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) + Integer.parseInt(r.primitiveValue()))); 1965 else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 1966 result.add(new DecimalType(new BigDecimal(l.primitiveValue()).add(new BigDecimal(r.primitiveValue())))); 1967 else 1968 throw new PathEngineException(String.format("Error performing +: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 1969 return result; 1970 } 1971 1972 private List<Base> opTimes(List<Base> left, List<Base> right) throws PathEngineException { 1973 if (left.size() == 0 || right.size() == 0) 1974 return new ArrayList<Base>(); 1975 if (left.size() > 1) 1976 throw new PathEngineException("Error performing *: left operand has more than one value"); 1977 if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity)) 1978 throw new PathEngineException(String.format("Error performing +: left operand has the wrong type (%s)", left.get(0).fhirType())); 1979 if (right.size() > 1) 1980 throw new PathEngineException("Error performing *: right operand has more than one value"); 1981 if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity)) 1982 throw new PathEngineException(String.format("Error performing *: right operand has the wrong type (%s)", right.get(0).fhirType())); 1983 1984 List<Base> result = new ArrayList<Base>(); 1985 Base l = left.get(0); 1986 Base r = right.get(0); 1987 1988 if (l.hasType("integer") && r.hasType("integer")) 1989 result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) * Integer.parseInt(r.primitiveValue()))); 1990 else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 1991 result.add(new DecimalType(new BigDecimal(l.primitiveValue()).multiply(new BigDecimal(r.primitiveValue())))); 1992 else if (l instanceof Quantity && r instanceof Quantity && worker.getUcumService() != null) { 1993 Pair pl = qtyToPair((Quantity) l); 1994 Pair pr = qtyToPair((Quantity) r); 1995 Pair p; 1996 try { 1997 p = worker.getUcumService().multiply(pl, pr); 1998 result.add(pairToQty(p)); 1999 } catch (UcumException e) { 2000 throw new PathEngineException(e.getMessage(), e); 2001 } 2002 } else 2003 throw new PathEngineException(String.format("Error performing *: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 2004 return result; 2005 } 2006 2007 2008 private List<Base> opConcatenate(List<Base> left, List<Base> right) throws PathEngineException { 2009 if (left.size() > 1) 2010 throw new PathEngineException("Error performing &: left operand has more than one value"); 2011 if (left.size() > 0 && !left.get(0).hasType(FHIR_TYPES_STRING)) 2012 throw new PathEngineException(String.format("Error performing &: left operand has the wrong type (%s)", left.get(0).fhirType())); 2013 if (right.size() > 1) 2014 throw new PathEngineException("Error performing &: right operand has more than one value"); 2015 if (right.size() > 0 && !right.get(0).hasType(FHIR_TYPES_STRING)) 2016 throw new PathEngineException(String.format("Error performing &: right operand has the wrong type (%s)", right.get(0).fhirType())); 2017 2018 List<Base> result = new ArrayList<Base>(); 2019 String l = left.size() == 0 ? "" : left.get(0).primitiveValue(); 2020 String r = right.size() == 0 ? "" : right.get(0).primitiveValue(); 2021 result.add(new StringType(l + r)); 2022 return result; 2023 } 2024 2025 private List<Base> opUnion(List<Base> left, List<Base> right) { 2026 List<Base> result = new ArrayList<Base>(); 2027 for (Base item : left) { 2028 if (!doContains(result, item)) 2029 result.add(item); 2030 } 2031 for (Base item : right) { 2032 if (!doContains(result, item)) 2033 result.add(item); 2034 } 2035 return result; 2036 } 2037 2038 private boolean doContains(List<Base> list, Base item) { 2039 for (Base test : list) { 2040 Boolean eq = doEquals(test, item); 2041 if (eq != null && eq == true) 2042 return true; 2043 } 2044 return false; 2045 } 2046 2047 2048 private List<Base> opAnd(List<Base> left, List<Base> right) throws PathEngineException { 2049 Equality l = asBool(left); 2050 Equality r = asBool(right); 2051 switch (l) { 2052 case False: return makeBoolean(false); 2053 case Null: 2054 if (r == Equality.False) 2055 return makeBoolean(false); 2056 else 2057 return makeNull(); 2058 case True: 2059 switch (r) { 2060 case False: return makeBoolean(false); 2061 case Null: return makeNull(); 2062 case True: return makeBoolean(true); 2063 } 2064 } 2065 return makeNull(); 2066 } 2067 2068 private boolean isBoolean(List<Base> list, boolean b) { 2069 return list.size() == 1 && list.get(0) instanceof BooleanType && ((BooleanType) list.get(0)).booleanValue() == b; 2070 } 2071 2072 private List<Base> opOr(List<Base> left, List<Base> right) throws PathEngineException { 2073 Equality l = asBool(left); 2074 Equality r = asBool(right); 2075 switch (l) { 2076 case True: return makeBoolean(true); 2077 case Null: 2078 if (r == Equality.True) 2079 return makeBoolean(true); 2080 else 2081 return makeNull(); 2082 case False: 2083 switch (r) { 2084 case False: return makeBoolean(false); 2085 case Null: return makeNull(); 2086 case True: return makeBoolean(true); 2087 } 2088 } 2089 return makeNull(); 2090 } 2091 2092 private List<Base> opXor(List<Base> left, List<Base> right) throws PathEngineException { 2093 Equality l = asBool(left); 2094 Equality r = asBool(right); 2095 switch (l) { 2096 case True: 2097 switch (r) { 2098 case False: return makeBoolean(true); 2099 case True: return makeBoolean(false); 2100 case Null: return makeNull(); 2101 } 2102 case Null: 2103 return makeNull(); 2104 case False: 2105 switch (r) { 2106 case False: return makeBoolean(false); 2107 case True: return makeBoolean(true); 2108 case Null: return makeNull(); 2109 } 2110 } 2111 return makeNull(); 2112 } 2113 2114 private List<Base> opImplies(List<Base> left, List<Base> right) throws PathEngineException { 2115 Equality eq = asBool(left); 2116 if (eq == Equality.False) 2117 return makeBoolean(true); 2118 else if (right.size() == 0) 2119 return makeNull(); 2120 else switch (asBool(right)) { 2121 case False: return eq == Equality.Null ? makeNull() : makeBoolean(false); 2122 case Null: return makeNull(); 2123 case True: return makeBoolean(true); 2124 } 2125 return makeNull(); 2126 } 2127 2128 2129 private List<Base> opMinus(List<Base> left, List<Base> right) throws PathEngineException { 2130 if (left.size() == 0 || right.size() == 0) 2131 return new ArrayList<Base>(); 2132 if (left.size() > 1) 2133 throw new PathEngineException("Error performing -: left operand has more than one value"); 2134 if (!left.get(0).isPrimitive()) 2135 throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType())); 2136 if (right.size() > 1) 2137 throw new PathEngineException("Error performing -: right operand has more than one value"); 2138 if (!right.get(0).isPrimitive()) 2139 throw new PathEngineException(String.format("Error performing -: right operand has the wrong type (%s)", right.get(0).fhirType())); 2140 2141 List<Base> result = new ArrayList<Base>(); 2142 Base l = left.get(0); 2143 Base r = right.get(0); 2144 2145 if (l.hasType("integer") && r.hasType("integer")) 2146 result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) - Integer.parseInt(r.primitiveValue()))); 2147 else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) 2148 result.add(new DecimalType(new BigDecimal(l.primitiveValue()).subtract(new BigDecimal(r.primitiveValue())))); 2149 else 2150 throw new PathEngineException(String.format("Error performing -: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 2151 return result; 2152 } 2153 2154 private List<Base> opDivideBy(List<Base> left, List<Base> right) throws PathEngineException { 2155 if (left.size() == 0 || right.size() == 0) 2156 return new ArrayList<Base>(); 2157 if (left.size() > 1) 2158 throw new PathEngineException("Error performing /: left operand has more than one value"); 2159 if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity)) 2160 throw new PathEngineException(String.format("Error performing -: left operand has the wrong type (%s)", left.get(0).fhirType())); 2161 if (right.size() > 1) 2162 throw new PathEngineException("Error performing /: right operand has more than one value"); 2163 if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity)) 2164 throw new PathEngineException(String.format("Error performing /: right operand has the wrong type (%s)", right.get(0).fhirType())); 2165 2166 List<Base> result = new ArrayList<Base>(); 2167 Base l = left.get(0); 2168 Base r = right.get(0); 2169 2170 if (l.hasType("integer", "decimal", "unsignedInt", "positiveInt") && r.hasType("integer", "decimal", "unsignedInt", "positiveInt")) { 2171 Decimal d1; 2172 try { 2173 d1 = new Decimal(l.primitiveValue()); 2174 Decimal d2 = new Decimal(r.primitiveValue()); 2175 result.add(new DecimalType(d1.divide(d2).asDecimal())); 2176 } catch (UcumException e) { 2177 throw new PathEngineException(e); 2178 } 2179 } else if (l instanceof Quantity && r instanceof Quantity && worker.getUcumService() != null) { 2180 Pair pl = qtyToPair((Quantity) l); 2181 Pair pr = qtyToPair((Quantity) r); 2182 Pair p; 2183 try { 2184 p = worker.getUcumService().multiply(pl, pr); 2185 result.add(pairToQty(p)); 2186 } catch (UcumException e) { 2187 throw new PathEngineException(e.getMessage(), e); 2188 } 2189 } else 2190 throw new PathEngineException(String.format("Error performing /: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 2191 return result; 2192 } 2193 2194 private List<Base> opDiv(List<Base> left, List<Base> right) throws PathEngineException { 2195 if (left.size() == 0 || right.size() == 0) 2196 return new ArrayList<Base>(); 2197 if (left.size() > 1) 2198 throw new PathEngineException("Error performing div: left operand has more than one value"); 2199 if (!left.get(0).isPrimitive() && !(left.get(0) instanceof Quantity)) 2200 throw new PathEngineException(String.format("Error performing div: left operand has the wrong type (%s)", left.get(0).fhirType())); 2201 if (right.size() > 1) 2202 throw new PathEngineException("Error performing div: right operand has more than one value"); 2203 if (!right.get(0).isPrimitive() && !(right.get(0) instanceof Quantity)) 2204 throw new PathEngineException(String.format("Error performing div: right operand has the wrong type (%s)", right.get(0).fhirType())); 2205 2206 List<Base> result = new ArrayList<Base>(); 2207 Base l = left.get(0); 2208 Base r = right.get(0); 2209 2210 if (l.hasType("integer") && r.hasType("integer")) 2211 result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) / Integer.parseInt(r.primitiveValue()))); 2212 else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) { 2213 Decimal d1; 2214 try { 2215 d1 = new Decimal(l.primitiveValue()); 2216 Decimal d2 = new Decimal(r.primitiveValue()); 2217 result.add(new IntegerType(d1.divInt(d2).asDecimal())); 2218 } catch (UcumException e) { 2219 throw new PathEngineException(e); 2220 } 2221 } 2222 else 2223 throw new PathEngineException(String.format("Error performing div: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 2224 return result; 2225 } 2226 2227 private List<Base> opMod(List<Base> left, List<Base> right) throws PathEngineException { 2228 if (left.size() == 0 || right.size() == 0) 2229 return new ArrayList<Base>(); 2230 if (left.size() > 1) 2231 throw new PathEngineException("Error performing mod: left operand has more than one value"); 2232 if (!left.get(0).isPrimitive()) 2233 throw new PathEngineException(String.format("Error performing mod: left operand has the wrong type (%s)", left.get(0).fhirType())); 2234 if (right.size() > 1) 2235 throw new PathEngineException("Error performing mod: right operand has more than one value"); 2236 if (!right.get(0).isPrimitive()) 2237 throw new PathEngineException(String.format("Error performing mod: right operand has the wrong type (%s)", right.get(0).fhirType())); 2238 2239 List<Base> result = new ArrayList<Base>(); 2240 Base l = left.get(0); 2241 Base r = right.get(0); 2242 2243 if (l.hasType("integer") && r.hasType("integer")) 2244 result.add(new IntegerType(Integer.parseInt(l.primitiveValue()) % Integer.parseInt(r.primitiveValue()))); 2245 else if (l.hasType("decimal", "integer") && r.hasType("decimal", "integer")) { 2246 Decimal d1; 2247 try { 2248 d1 = new Decimal(l.primitiveValue()); 2249 Decimal d2 = new Decimal(r.primitiveValue()); 2250 result.add(new DecimalType(d1.modulo(d2).asDecimal())); 2251 } catch (UcumException e) { 2252 throw new PathEngineException(e); 2253 } 2254 } 2255 else 2256 throw new PathEngineException(String.format("Error performing mod: left and right operand have incompatible or illegal types (%s, %s)", left.get(0).fhirType(), right.get(0).fhirType())); 2257 return result; 2258 } 2259 2260 2261 private TypeDetails resolveConstantType(ExecutionTypeContext context, Base constant) throws PathEngineException { 2262 if (constant instanceof BooleanType) 2263 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2264 else if (constant instanceof IntegerType) 2265 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer); 2266 else if (constant instanceof DecimalType) 2267 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Decimal); 2268 else if (constant instanceof Quantity) 2269 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Quantity); 2270 else if (constant instanceof FHIRConstant) 2271 return resolveConstantType(context, ((FHIRConstant) constant).getValue()); 2272 else 2273 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2274 } 2275 2276 private TypeDetails resolveConstantType(ExecutionTypeContext context, String s) throws PathEngineException { 2277 if (s.startsWith("@")) { 2278 if (s.startsWith("@T")) 2279 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Time); 2280 else 2281 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime); 2282 } else if (s.equals("%sct")) 2283 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2284 else if (s.equals("%loinc")) 2285 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2286 else if (s.equals("%ucum")) 2287 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2288 else if (s.equals("%resource")) { 2289 if (context.resource == null) 2290 throw new PathEngineException("%resource cannot be used in this context"); 2291 return new TypeDetails(CollectionStatus.SINGLETON, context.resource); 2292 } else if (s.equals("%rootResource")) { 2293 if (context.resource == null) 2294 throw new PathEngineException("%rootResource cannot be used in this context"); 2295 return new TypeDetails(CollectionStatus.SINGLETON, context.resource); 2296 } else if (s.equals("%context")) { 2297 return context.context; 2298 } else if (s.equals("%map-codes")) 2299 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2300 else if (s.equals("%us-zip")) 2301 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2302 else if (s.startsWith("%`vs-")) 2303 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2304 else if (s.startsWith("%`cs-")) 2305 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2306 else if (s.startsWith("%`ext-")) 2307 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2308 else if (hostServices == null) 2309 throw new PathEngineException("Unknown fixed constant type for '"+s+"'"); 2310 else 2311 return hostServices.resolveConstantType(context.appInfo, s); 2312 } 2313 2314 private List<Base> execute(ExecutionContext context, Base item, ExpressionNode exp, boolean atEntry) throws FHIRException { 2315 List<Base> result = new ArrayList<Base>(); 2316 if (atEntry && context.appInfo != null && hostServices != null) { 2317 // we'll see if the name matches a constant known by the context. 2318 Base temp = hostServices.resolveConstant(context.appInfo, exp.getName(), true); 2319 if (temp != null) { 2320 result.add(temp); 2321 return result; 2322 } 2323 } 2324 if (atEntry && Character.isUpperCase(exp.getName().charAt(0))) {// special case for start up 2325 if (item.isResource() && item.fhirType().equals(exp.getName())) 2326 result.add(item); 2327 } else 2328 getChildrenByName(item, exp.getName(), result); 2329 if (atEntry && context.appInfo != null && hostServices != null && result.isEmpty()) { 2330 // well, we didn't get a match on the name - we'll see if the name matches a constant known by the context. 2331 // (if the name does match, and the user wants to get the constant value, they'll have to try harder... 2332 Base temp = hostServices.resolveConstant(context.appInfo, exp.getName(), false); 2333 if (temp != null) { 2334 result.add(temp); 2335 } 2336 } 2337 return result; 2338 } 2339 2340 private TypeDetails executeContextType(ExecutionTypeContext context, String name) throws PathEngineException, DefinitionException { 2341 if (hostServices == null) 2342 throw new PathEngineException("Unable to resolve context reference since no host services are provided"); 2343 return hostServices.resolveConstantType(context.appInfo, name); 2344 } 2345 2346 private TypeDetails executeType(String type, ExpressionNode exp, boolean atEntry) throws PathEngineException, DefinitionException { 2347 if (atEntry && Character.isUpperCase(exp.getName().charAt(0)) && hashTail(type).equals(exp.getName())) // special case for start up 2348 return new TypeDetails(CollectionStatus.SINGLETON, type); 2349 TypeDetails result = new TypeDetails(null); 2350 getChildTypesByName(type, exp.getName(), result); 2351 return result; 2352 } 2353 2354 2355 private String hashTail(String type) { 2356 return type.contains("#") ? "" : type.substring(type.lastIndexOf("/")+1); 2357 } 2358 2359 2360 @SuppressWarnings("unchecked") 2361 private TypeDetails evaluateFunctionType(ExecutionTypeContext context, TypeDetails focus, ExpressionNode exp) throws PathEngineException, DefinitionException { 2362 List<TypeDetails> paramTypes = new ArrayList<TypeDetails>(); 2363 if (exp.getFunction() == Function.Is || exp.getFunction() == Function.As || exp.getFunction() == Function.OfType) 2364 paramTypes.add(new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2365 else 2366 for (ExpressionNode expr : exp.getParameters()) { 2367 if (exp.getFunction() == Function.Where || exp.getFunction() == Function.All || exp.getFunction() == Function.Select || exp.getFunction() == Function.Repeat || exp.getFunction() == Function.Aggregate) 2368 paramTypes.add(executeType(changeThis(context, focus), focus, expr, true)); 2369 else 2370 paramTypes.add(executeType(context, focus, expr, true)); 2371 } 2372 switch (exp.getFunction()) { 2373 case Empty : 2374 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2375 case Not : 2376 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2377 case Exists : 2378 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2379 case SubsetOf : { 2380 checkParamTypes(exp.getFunction().toCode(), paramTypes, focus); 2381 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2382 } 2383 case SupersetOf : { 2384 checkParamTypes(exp.getFunction().toCode(), paramTypes, focus); 2385 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2386 } 2387 case IsDistinct : 2388 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2389 case Distinct : 2390 return focus; 2391 case Count : 2392 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer); 2393 case Where : 2394 return focus; 2395 case Select : 2396 return anything(focus.getCollectionStatus()); 2397 case All : 2398 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2399 case Repeat : 2400 return anything(focus.getCollectionStatus()); 2401 case Aggregate : 2402 return anything(focus.getCollectionStatus()); 2403 case Item : { 2404 checkOrdered(focus, "item"); 2405 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 2406 return focus; 2407 } 2408 case As : { 2409 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2410 return new TypeDetails(CollectionStatus.SINGLETON, exp.getParameters().get(0).getName()); 2411 } 2412 case OfType : { 2413 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2414 return new TypeDetails(CollectionStatus.SINGLETON, exp.getParameters().get(0).getName()); 2415 } 2416 case Type : { 2417 boolean s = false; 2418 boolean c = false; 2419 for (ProfiledType pt : focus.getProfiledTypes()) { 2420 s = s || pt.isSystemType(); 2421 c = c || !pt.isSystemType(); 2422 } 2423 if (s && c) 2424 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_SimpleTypeInfo, TypeDetails.FP_ClassInfo); 2425 else if (s) 2426 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_SimpleTypeInfo); 2427 else 2428 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_ClassInfo); 2429 } 2430 case Is : { 2431 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2432 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2433 } 2434 case Single : 2435 return focus.toSingleton(); 2436 case First : { 2437 checkOrdered(focus, "first"); 2438 return focus.toSingleton(); 2439 } 2440 case Last : { 2441 checkOrdered(focus, "last"); 2442 return focus.toSingleton(); 2443 } 2444 case Tail : { 2445 checkOrdered(focus, "tail"); 2446 return focus; 2447 } 2448 case Skip : { 2449 checkOrdered(focus, "skip"); 2450 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 2451 return focus; 2452 } 2453 case Take : { 2454 checkOrdered(focus, "take"); 2455 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 2456 return focus; 2457 } 2458 case Union : { 2459 return focus.union(paramTypes.get(0)); 2460 } 2461 case Combine : { 2462 return focus.union(paramTypes.get(0)); 2463 } 2464 case Intersect : { 2465 return focus.intersect(paramTypes.get(0)); 2466 } 2467 case Exclude : { 2468 return focus; 2469 } 2470 case Iif : { 2471 TypeDetails types = new TypeDetails(null); 2472 types.update(paramTypes.get(0)); 2473 if (paramTypes.size() > 1) 2474 types.update(paramTypes.get(1)); 2475 return types; 2476 } 2477 case Lower : { 2478 checkContextString(focus, "lower"); 2479 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2480 } 2481 case Upper : { 2482 checkContextString(focus, "upper"); 2483 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2484 } 2485 case ToChars : { 2486 checkContextString(focus, "toChars"); 2487 return new TypeDetails(CollectionStatus.ORDERED, TypeDetails.FP_String); 2488 } 2489 case Substring : { 2490 checkContextString(focus, "subString"); 2491 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer)); 2492 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2493 } 2494 case StartsWith : { 2495 checkContextString(focus, "startsWith"); 2496 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2497 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2498 } 2499 case EndsWith : { 2500 checkContextString(focus, "endsWith"); 2501 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2502 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2503 } 2504 case Matches : { 2505 checkContextString(focus, "matches"); 2506 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2507 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2508 } 2509 case ReplaceMatches : { 2510 checkContextString(focus, "replaceMatches"); 2511 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2512 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2513 } 2514 case Contains : { 2515 checkContextString(focus, "contains"); 2516 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2517 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2518 } 2519 case Replace : { 2520 checkContextString(focus, "replace"); 2521 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, "string"), new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2522 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2523 } 2524 case Length : { 2525 checkContextPrimitive(focus, "length", false); 2526 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer); 2527 } 2528 case Children : 2529 return childTypes(focus, "*"); 2530 case Descendants : 2531 return childTypes(focus, "**"); 2532 case MemberOf : { 2533 checkContextCoded(focus, "memberOf"); 2534 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2535 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2536 } 2537 case Trace : { 2538 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2539 return focus; 2540 } 2541 case Check : { 2542 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2543 return focus; 2544 } 2545 case Today : 2546 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime); 2547 case Now : 2548 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime); 2549 case Resolve : { 2550 checkContextReference(focus, "resolve"); 2551 return new TypeDetails(CollectionStatus.SINGLETON, "DomainResource"); 2552 } 2553 case Extension : { 2554 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2555 return new TypeDetails(CollectionStatus.SINGLETON, "Extension"); 2556 } 2557 case AnyTrue: 2558 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2559 case AllTrue: 2560 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2561 case AnyFalse: 2562 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2563 case AllFalse: 2564 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2565 case HasValue : 2566 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2567 case HtmlChecks : 2568 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2569 case Alias : 2570 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2571 return anything(CollectionStatus.SINGLETON); 2572 case AliasAs : 2573 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2574 return focus; 2575 case ToInteger : { 2576 checkContextPrimitive(focus, "toInteger", true); 2577 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Integer); 2578 } 2579 case ToDecimal : { 2580 checkContextPrimitive(focus, "toDecimal", true); 2581 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Decimal); 2582 } 2583 case ToString : { 2584 checkContextPrimitive(focus, "toString", true); 2585 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String); 2586 } 2587 case ToQuantity : { 2588 checkContextPrimitive(focus, "toQuantity", true); 2589 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Quantity); 2590 } 2591 case ToBoolean : { 2592 checkContextPrimitive(focus, "toBoolean", false); 2593 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2594 } 2595 case ToDateTime : { 2596 checkContextPrimitive(focus, "toBoolean", false); 2597 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_DateTime); 2598 } 2599 case ToTime : { 2600 checkContextPrimitive(focus, "toBoolean", false); 2601 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Time); 2602 } 2603 case ConvertsToString : 2604 case ConvertsToQuantity :{ 2605 checkContextPrimitive(focus, exp.getFunction().toCode(), true); 2606 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2607 } 2608 case ConvertsToInteger : 2609 case ConvertsToDecimal : 2610 case ConvertsToDateTime : 2611 case ConvertsToTime : 2612 case ConvertsToBoolean : { 2613 checkContextPrimitive(focus, exp.getFunction().toCode(), false); 2614 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2615 } 2616 case ConformsTo: { 2617 checkParamTypes(exp.getFunction().toCode(), paramTypes, new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_String)); 2618 return new TypeDetails(CollectionStatus.SINGLETON, TypeDetails.FP_Boolean); 2619 } 2620 case Custom : { 2621 return hostServices.checkFunction(context.appInfo, exp.getName(), paramTypes); 2622 } 2623 default: 2624 break; 2625 } 2626 throw new Error("not Implemented yet"); 2627 } 2628 2629 2630 private void checkParamTypes(String funcName, List<TypeDetails> paramTypes, TypeDetails... typeSet) throws PathEngineException { 2631 int i = 0; 2632 for (TypeDetails pt : typeSet) { 2633 if (i == paramTypes.size()) 2634 return; 2635 TypeDetails actual = paramTypes.get(i); 2636 i++; 2637 for (String a : actual.getTypes()) { 2638 if (!pt.hasType(worker, a)) 2639 throw new PathEngineException("The parameter type '"+a+"' is not legal for "+funcName+" parameter "+Integer.toString(i)+". expecting "+pt.toString()); 2640 } 2641 } 2642 } 2643 2644 private void checkOrdered(TypeDetails focus, String name) throws PathEngineException { 2645 if (focus.getCollectionStatus() == CollectionStatus.UNORDERED) 2646 throw new PathEngineException("The function '"+name+"'() can only be used on ordered collections"); 2647 } 2648 2649 private void checkContextReference(TypeDetails focus, String name) throws PathEngineException { 2650 if (!focus.hasType(worker, "string") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Reference") && !focus.hasType(worker, "canonical")) 2651 throw new PathEngineException("The function '"+name+"'() can only be used on string, uri, canonical, Reference"); 2652 } 2653 2654 2655 private void checkContextCoded(TypeDetails focus, String name) throws PathEngineException { 2656 if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "Coding") && !focus.hasType(worker, "CodeableConcept")) 2657 throw new PathEngineException("The function '"+name+"'() can only be used on string, code, uri, Coding, CodeableConcept"); 2658 } 2659 2660 2661 private void checkContextString(TypeDetails focus, String name) throws PathEngineException { 2662 if (!focus.hasType(worker, "string") && !focus.hasType(worker, "code") && !focus.hasType(worker, "uri") && !focus.hasType(worker, "canonical") && !focus.hasType(worker, "id")) 2663 throw new PathEngineException("The function '"+name+"'() can only be used on string, uri, code, id, but found "+focus.describe()); 2664 } 2665 2666 2667 private void checkContextPrimitive(TypeDetails focus, String name, boolean canQty) throws PathEngineException { 2668 if (canQty) { 2669 if (!focus.hasType(primitiveTypes) && !focus.hasType("Quantity")) 2670 throw new PathEngineException("The function '"+name+"'() can only be used on a Quantity or on "+primitiveTypes.toString()); 2671 } else if (!focus.hasType(primitiveTypes)) 2672 throw new PathEngineException("The function '"+name+"'() can only be used on "+primitiveTypes.toString()); 2673 } 2674 2675 2676 private TypeDetails childTypes(TypeDetails focus, String mask) throws PathEngineException, DefinitionException { 2677 TypeDetails result = new TypeDetails(CollectionStatus.UNORDERED); 2678 for (String f : focus.getTypes()) 2679 getChildTypesByName(f, mask, result); 2680 return result; 2681 } 2682 2683 private TypeDetails anything(CollectionStatus status) { 2684 return new TypeDetails(status, allTypes.keySet()); 2685 } 2686 2687 // private boolean isPrimitiveType(String s) { 2688 // return s.equals("boolean") || s.equals("integer") || s.equals("decimal") || s.equals("base64Binary") || s.equals("instant") || s.equals("string") || s.equals("uri") || s.equals("date") || s.equals("dateTime") || s.equals("time") || s.equals("code") || s.equals("oid") || s.equals("id") || s.equals("unsignedInt") || s.equals("positiveInt") || s.equals("markdown"); 2689 // } 2690 2691 private List<Base> evaluateFunction(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2692 switch (exp.getFunction()) { 2693 case Empty : return funcEmpty(context, focus, exp); 2694 case Not : return funcNot(context, focus, exp); 2695 case Exists : return funcExists(context, focus, exp); 2696 case SubsetOf : return funcSubsetOf(context, focus, exp); 2697 case SupersetOf : return funcSupersetOf(context, focus, exp); 2698 case IsDistinct : return funcIsDistinct(context, focus, exp); 2699 case Distinct : return funcDistinct(context, focus, exp); 2700 case Count : return funcCount(context, focus, exp); 2701 case Where : return funcWhere(context, focus, exp); 2702 case Select : return funcSelect(context, focus, exp); 2703 case All : return funcAll(context, focus, exp); 2704 case Repeat : return funcRepeat(context, focus, exp); 2705 case Aggregate : return funcAggregate(context, focus, exp); 2706 case Item : return funcItem(context, focus, exp); 2707 case As : return funcAs(context, focus, exp); 2708 case OfType : return funcAs(context, focus, exp); 2709 case Type : return funcType(context, focus, exp); 2710 case Is : return funcIs(context, focus, exp); 2711 case Single : return funcSingle(context, focus, exp); 2712 case First : return funcFirst(context, focus, exp); 2713 case Last : return funcLast(context, focus, exp); 2714 case Tail : return funcTail(context, focus, exp); 2715 case Skip : return funcSkip(context, focus, exp); 2716 case Take : return funcTake(context, focus, exp); 2717 case Union : return funcUnion(context, focus, exp); 2718 case Combine : return funcCombine(context, focus, exp); 2719 case Intersect : return funcIntersect(context, focus, exp); 2720 case Exclude : return funcExclude(context, focus, exp); 2721 case Iif : return funcIif(context, focus, exp); 2722 case Lower : return funcLower(context, focus, exp); 2723 case Upper : return funcUpper(context, focus, exp); 2724 case ToChars : return funcToChars(context, focus, exp); 2725 case Substring : return funcSubstring(context, focus, exp); 2726 case StartsWith : return funcStartsWith(context, focus, exp); 2727 case EndsWith : return funcEndsWith(context, focus, exp); 2728 case Matches : return funcMatches(context, focus, exp); 2729 case ReplaceMatches : return funcReplaceMatches(context, focus, exp); 2730 case Contains : return funcContains(context, focus, exp); 2731 case Replace : return funcReplace(context, focus, exp); 2732 case Length : return funcLength(context, focus, exp); 2733 case Children : return funcChildren(context, focus, exp); 2734 case Descendants : return funcDescendants(context, focus, exp); 2735 case MemberOf : return funcMemberOf(context, focus, exp); 2736 case Trace : return funcTrace(context, focus, exp); 2737 case Check : return funcCheck(context, focus, exp); 2738 case Today : return funcToday(context, focus, exp); 2739 case Now : return funcNow(context, focus, exp); 2740 case Resolve : return funcResolve(context, focus, exp); 2741 case Extension : return funcExtension(context, focus, exp); 2742 case AnyFalse: return funcAnyFalse(context, focus, exp); 2743 case AllFalse: return funcAllFalse(context, focus, exp); 2744 case AnyTrue: return funcAnyTrue(context, focus, exp); 2745 case AllTrue: return funcAllTrue(context, focus, exp); 2746 case HasValue : return funcHasValue(context, focus, exp); 2747 case AliasAs : return funcAliasAs(context, focus, exp); 2748 case Alias : return funcAlias(context, focus, exp); 2749 case HtmlChecks : return funcHtmlChecks(context, focus, exp); 2750 case ToInteger : return funcToInteger(context, focus, exp); 2751 case ToDecimal : return funcToDecimal(context, focus, exp); 2752 case ToString : return funcToString(context, focus, exp); 2753 case ToBoolean : return funcToBoolean(context, focus, exp); 2754 case ToQuantity : return funcToQuantity(context, focus, exp); 2755 case ToDateTime : return funcToDateTime(context, focus, exp); 2756 case ToTime : return funcToTime(context, focus, exp); 2757 case ConvertsToInteger : return funcIsInteger(context, focus, exp); 2758 case ConvertsToDecimal : return funcIsDecimal(context, focus, exp); 2759 case ConvertsToString : return funcIsString(context, focus, exp); 2760 case ConvertsToBoolean : return funcIsBoolean(context, focus, exp); 2761 case ConvertsToQuantity : return funcIsQuantity(context, focus, exp); 2762 case ConvertsToDateTime : return funcIsDateTime(context, focus, exp); 2763 case ConvertsToTime : return funcIsTime(context, focus, exp); 2764 case ConformsTo : return funcConformsTo(context, focus, exp); 2765 case Custom: { 2766 List<List<Base>> params = new ArrayList<List<Base>>(); 2767 for (ExpressionNode p : exp.getParameters()) 2768 params.add(execute(context, focus, p, true)); 2769 return hostServices.executeFunction(context.appInfo, exp.getName(), params); 2770 } 2771 default: 2772 throw new Error("not Implemented yet"); 2773 } 2774 } 2775 2776 private List<Base> funcAliasAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2777 List<Base> nl = execute(context, focus, exp.getParameters().get(0), true); 2778 String name = nl.get(0).primitiveValue(); 2779 context.addAlias(name, focus); 2780 return focus; 2781 } 2782 2783 private List<Base> funcAlias(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2784 List<Base> nl = execute(context, focus, exp.getParameters().get(0), true); 2785 String name = nl.get(0).primitiveValue(); 2786 List<Base> res = new ArrayList<Base>(); 2787 Base b = context.getAlias(name); 2788 if (b != null) 2789 res.add(b); 2790 return res; 2791 } 2792 2793 private List<Base> funcHtmlChecks(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2794 // todo: actually check the HTML 2795 return makeBoolean(true); 2796 } 2797 2798 2799 private List<Base> funcAll(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2800 List<Base> result = new ArrayList<Base>(); 2801 if (exp.getParameters().size() == 1) { 2802 List<Base> pc = new ArrayList<Base>(); 2803 boolean all = true; 2804 for (Base item : focus) { 2805 pc.clear(); 2806 pc.add(item); 2807 Equality eq = asBool(execute(changeThis(context, item), pc, exp.getParameters().get(0), true)); 2808 if (eq != Equality.True) { 2809 all = false; 2810 break; 2811 } 2812 } 2813 result.add(new BooleanType(all).noExtensions()); 2814 } else {// (exp.getParameters().size() == 0) { 2815 boolean all = true; 2816 for (Base item : focus) { 2817 Equality eq = asBool(item); 2818 if (eq != Equality.True) { 2819 all = false; 2820 break; 2821 } 2822 } 2823 result.add(new BooleanType(all).noExtensions()); 2824 } 2825 return result; 2826 } 2827 2828 2829 private ExecutionContext changeThis(ExecutionContext context, Base newThis) { 2830 return new ExecutionContext(context.appInfo, context.focusResource, context.rootResource, context.context, context.aliases, newThis); 2831 } 2832 2833 private ExecutionTypeContext changeThis(ExecutionTypeContext context, TypeDetails newThis) { 2834 return new ExecutionTypeContext(context.appInfo, context.resource, context.context, newThis); 2835 } 2836 2837 2838 private List<Base> funcNow(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2839 List<Base> result = new ArrayList<Base>(); 2840 result.add(DateTimeType.now()); 2841 return result; 2842 } 2843 2844 2845 private List<Base> funcToday(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2846 List<Base> result = new ArrayList<Base>(); 2847 result.add(new DateType(new Date(), TemporalPrecisionEnum.DAY)); 2848 return result; 2849 } 2850 2851 2852 private List<Base> funcMemberOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2853 throw new Error("not Implemented yet"); 2854 } 2855 2856 2857 private List<Base> funcDescendants(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2858 List<Base> result = new ArrayList<Base>(); 2859 List<Base> current = new ArrayList<Base>(); 2860 current.addAll(focus); 2861 List<Base> added = new ArrayList<Base>(); 2862 boolean more = true; 2863 while (more) { 2864 added.clear(); 2865 for (Base item : current) { 2866 getChildrenByName(item, "*", added); 2867 } 2868 more = !added.isEmpty(); 2869 result.addAll(added); 2870 current.clear(); 2871 current.addAll(added); 2872 } 2873 return result; 2874 } 2875 2876 2877 private List<Base> funcChildren(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2878 List<Base> result = new ArrayList<Base>(); 2879 for (Base b : focus) 2880 getChildrenByName(b, "*", result); 2881 return result; 2882 } 2883 2884 2885 private List<Base> funcReplace(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException, PathEngineException { 2886 List<Base> result = new ArrayList<Base>(); 2887 2888 if (focus.size() == 1) { 2889 String f = convertToString(focus.get(0)); 2890 2891 if (!Utilities.noString(f)) { 2892 2893 if (exp.getParameters().size() == 2) { 2894 2895 String t = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 2896 String r = convertToString(execute(context, focus, exp.getParameters().get(1), true)); 2897 2898 String n = f.replace(t, r); 2899 result.add(new StringType(n)); 2900 } 2901 else { 2902 throw new PathEngineException(String.format("funcReplace() : checking for 2 arguments (pattern, substitution) but found %d items", exp.getParameters().size())); 2903 } 2904 } 2905 else { 2906 throw new PathEngineException(String.format("funcReplace() : checking for 1 string item but found empty item")); 2907 } 2908 } 2909 else { 2910 throw new PathEngineException(String.format("funcReplace() : checking for 1 string item but found %d items", focus.size())); 2911 } 2912 return result; 2913 } 2914 2915 2916 private List<Base> funcReplaceMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2917 List<Base> result = new ArrayList<Base>(); 2918 String regex = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 2919 String repl = convertToString(execute(context, focus, exp.getParameters().get(1), true)); 2920 2921 if (focus.size() == 1 && !Utilities.noString(regex)) 2922 result.add(new StringType(convertToString(focus.get(0)).replaceAll(regex, repl)).noExtensions()); 2923 else 2924 result.add(new StringType(convertToString(focus.get(0))).noExtensions()); 2925 return result; 2926 } 2927 2928 2929 private List<Base> funcEndsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 2930 List<Base> result = new ArrayList<Base>(); 2931 String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 2932 2933 if (focus.size() == 0) 2934 result.add(new BooleanType(false).noExtensions()); 2935 else if (Utilities.noString(sw)) 2936 result.add(new BooleanType(true).noExtensions()); 2937 else { 2938 if (focus.size() == 1 && !Utilities.noString(sw)) 2939 result.add(new BooleanType(convertToString(focus.get(0)).endsWith(sw)).noExtensions()); 2940 else 2941 result.add(new BooleanType(false).noExtensions()); 2942 } 2943 return result; 2944 } 2945 2946 2947 private List<Base> funcToString(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2948 List<Base> result = new ArrayList<Base>(); 2949 result.add(new StringType(convertToString(focus)).noExtensions()); 2950 return result; 2951 } 2952 2953 private List<Base> funcToBoolean(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2954 List<Base> result = new ArrayList<Base>(); 2955 if (focus.size() == 1) { 2956 if (focus.get(0) instanceof BooleanType) 2957 result.add(focus.get(0)); 2958 else if (focus.get(0) instanceof IntegerType) { 2959 int i = Integer.parseInt(focus.get(0).primitiveValue()); 2960 if (i == 0) 2961 result.add(new BooleanType(false).noExtensions()); 2962 else if (i == 1) 2963 result.add(new BooleanType(true).noExtensions()); 2964 } else if (focus.get(0) instanceof DecimalType) { 2965 if (((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ZERO) == 0) 2966 result.add(new BooleanType(false).noExtensions()); 2967 else if (((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ONE) == 0) 2968 result.add(new BooleanType(true).noExtensions()); 2969 } else if (focus.get(0) instanceof StringType) { 2970 if ("true".equalsIgnoreCase(focus.get(0).primitiveValue())) 2971 result.add(new BooleanType(true).noExtensions()); 2972 else if ("false".equalsIgnoreCase(focus.get(0).primitiveValue())) 2973 result.add(new BooleanType(false).noExtensions()); 2974 } 2975 } 2976 return result; 2977 } 2978 2979 private List<Base> funcToQuantity(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2980 List<Base> result = new ArrayList<Base>(); 2981 if (focus.size() == 1) { 2982 if (focus.get(0) instanceof Quantity) 2983 result.add(focus.get(0)); 2984 else if (focus.get(0) instanceof StringType) { 2985 Quantity q = parseQuantityString(focus.get(0).primitiveValue()); 2986 if (q != null) 2987 result.add(q.noExtensions()); 2988 } else if (focus.get(0) instanceof IntegerType) { 2989 result.add(new Quantity().setValue(new BigDecimal(focus.get(0).primitiveValue())).setSystem("http://unitsofmeasure.org").setCode("1").noExtensions()); 2990 } else if (focus.get(0) instanceof DecimalType) { 2991 result.add(new Quantity().setValue(new BigDecimal(focus.get(0).primitiveValue())).setSystem("http://unitsofmeasure.org").setCode("1").noExtensions()); 2992 } 2993 } 2994 return result; 2995 } 2996 2997 private List<Base> funcToDateTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 2998// List<Base> result = new ArrayList<Base>(); 2999// result.add(new BooleanType(convertToBoolean(focus))); 3000// return result; 3001 throw new NotImplementedException("funcToDateTime is not implemented"); 3002} 3003 3004 private List<Base> funcToTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3005// List<Base> result = new ArrayList<Base>(); 3006// result.add(new BooleanType(convertToBoolean(focus))); 3007// return result; 3008 throw new NotImplementedException("funcToTime is not implemented"); 3009} 3010 3011 3012 private List<Base> funcToDecimal(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3013 String s = convertToString(focus); 3014 List<Base> result = new ArrayList<Base>(); 3015 if (Utilities.isDecimal(s, true)) 3016 result.add(new DecimalType(s).noExtensions()); 3017 if ("true".equals(s)) 3018 result.add(new DecimalType(1).noExtensions()); 3019 if ("false".equals(s)) 3020 result.add(new DecimalType(0).noExtensions()); 3021 return result; 3022 } 3023 3024 3025 private List<Base> funcIif(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3026 List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true); 3027 Equality v = asBool(n1); 3028 3029 if (v == Equality.True) 3030 return execute(context, focus, exp.getParameters().get(1), true); 3031 else if (exp.getParameters().size() < 3) 3032 return new ArrayList<Base>(); 3033 else 3034 return execute(context, focus, exp.getParameters().get(2), true); 3035 } 3036 3037 3038 private List<Base> funcTake(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3039 List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true); 3040 int i1 = Integer.parseInt(n1.get(0).primitiveValue()); 3041 3042 List<Base> result = new ArrayList<Base>(); 3043 for (int i = 0; i < Math.min(focus.size(), i1); i++) 3044 result.add(focus.get(i)); 3045 return result; 3046 } 3047 3048 3049 private List<Base> funcUnion(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3050 List<Base> result = new ArrayList<Base>(); 3051 for (Base item : focus) { 3052 if (!doContains(result, item)) 3053 result.add(item); 3054 } 3055 for (Base item : execute(context, focus, exp.getParameters().get(0), true)) { 3056 if (!doContains(result, item)) 3057 result.add(item); 3058 } 3059 return result; 3060 } 3061 3062 private List<Base> funcCombine(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3063 List<Base> result = new ArrayList<Base>(); 3064 for (Base item : focus) { 3065 result.add(item); 3066 } 3067 for (Base item : execute(context, focus, exp.getParameters().get(0), true)) { 3068 result.add(item); 3069 } 3070 return result; 3071 } 3072 3073 private List<Base> funcIntersect(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3074 List<Base> result = new ArrayList<Base>(); 3075 List<Base> other = execute(context, focus, exp.getParameters().get(0), true); 3076 3077 for (Base item : focus) { 3078 if (!doContains(result, item) && doContains(other, item)) 3079 result.add(item); 3080 } 3081 return result; 3082 } 3083 3084 private List<Base> funcExclude(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3085 List<Base> result = new ArrayList<Base>(); 3086 List<Base> other = execute(context, focus, exp.getParameters().get(0), true); 3087 3088 for (Base item : focus) { 3089 if (!doContains(other, item)) 3090 result.add(item); 3091 } 3092 return result; 3093 } 3094 3095 3096 private List<Base> funcSingle(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException { 3097 if (focus.size() == 1) 3098 return focus; 3099 throw new PathEngineException(String.format("Single() : checking for 1 item but found %d items", focus.size())); 3100 } 3101 3102 3103 private List<Base> funcIs(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException { 3104 if (focus.size() == 0 || focus.size() > 1) 3105 return makeBoolean(false); 3106 String ns = null; 3107 String n = null; 3108 3109 ExpressionNode texp = exp.getParameters().get(0); 3110 if (texp.getKind() != Kind.Name) 3111 throw new PathEngineException("Unsupported Expression type for Parameter on Is"); 3112 if (texp.getInner() != null) { 3113 if (texp.getInner().getKind() != Kind.Name) 3114 throw new PathEngineException("Unsupported Expression type for Parameter on Is"); 3115 ns = texp.getName(); 3116 n = texp.getInner().getName(); 3117 } else if (Utilities.existsInList(texp.getName(), "Boolean", "Integer", "Decimal", "String", "DateTime", "Time", "SimpleTypeInfo", "ClassInfo")) { 3118 ns = "System"; 3119 n = texp.getName(); 3120 } else { 3121 ns = "FHIR"; 3122 n = texp.getName(); 3123 } 3124 if (ns.equals("System")) { 3125 if (focus.get(0) instanceof Resource) 3126 return makeBoolean(false); 3127 if (!(focus.get(0) instanceof Element) || ((Element) focus.get(0)).isDisallowExtensions()) 3128 return makeBoolean(n.equals(Utilities.capitalize(focus.get(0).fhirType()))); 3129 else 3130 return makeBoolean(false); 3131 } else if (ns.equals("FHIR")) { 3132 return makeBoolean(n.equals(focus.get(0).fhirType())); 3133 } else { 3134 return makeBoolean(false); 3135 } 3136 } 3137 3138 3139 private List<Base> funcAs(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3140 List<Base> result = new ArrayList<Base>(); 3141 String tn; 3142 if (exp.getParameters().get(0).getInner() != null) 3143 tn = exp.getParameters().get(0).getName()+"."+exp.getParameters().get(0).getInner().getName(); 3144 else 3145 tn = "FHIR."+exp.getParameters().get(0).getName(); 3146 for (Base b : focus) { 3147 if (tn.startsWith("System.")) { 3148 if (b instanceof Element &&((Element) b).isDisallowExtensions()) 3149 if (b.hasType(tn.substring(7))) 3150 result.add(b); 3151 } else if (tn.startsWith("FHIR.")) { 3152 if (b.hasType(tn.substring(5))) 3153 result.add(b); 3154 } 3155 } 3156 return result; 3157 } 3158 3159 private List<Base> funcType(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3160 List<Base> result = new ArrayList<Base>(); 3161 for (Base item : focus) 3162 result.add(new ClassTypeInfo(item)); 3163 return result; 3164 } 3165 3166 3167 private List<Base> funcRepeat(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3168 List<Base> result = new ArrayList<Base>(); 3169 List<Base> current = new ArrayList<Base>(); 3170 current.addAll(focus); 3171 List<Base> added = new ArrayList<Base>(); 3172 boolean more = true; 3173 while (more) { 3174 added.clear(); 3175 List<Base> pc = new ArrayList<Base>(); 3176 for (Base item : current) { 3177 pc.clear(); 3178 pc.add(item); 3179 added.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), false)); 3180 } 3181 more = !added.isEmpty(); 3182 result.addAll(added); 3183 current.clear(); 3184 current.addAll(added); 3185 } 3186 return result; 3187 } 3188 3189 3190 private List<Base> funcAggregate(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3191 List<Base> total = new ArrayList<Base>(); 3192 if (exp.parameterCount() > 1) 3193 total = execute(context, focus, exp.getParameters().get(1), false); 3194 3195 List<Base> pc = new ArrayList<Base>(); 3196 for (Base item : focus) { 3197 ExecutionContext c = changeThis(context, item); 3198 c.total = total; 3199 total = execute(c, pc, exp.getParameters().get(0), true); 3200 } 3201 return total; 3202 } 3203 3204 3205 3206 private List<Base> funcIsDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3207 if (focus.size() < 1) 3208 return makeBoolean(true); 3209 if (focus.size() == 1) 3210 return makeBoolean(true); 3211 3212 boolean distinct = true; 3213 for (int i = 0; i < focus.size(); i++) { 3214 for (int j = i+1; j < focus.size(); j++) { 3215 Boolean eq = doEquals(focus.get(j), focus.get(i)); 3216 if (eq == null) { 3217 return new ArrayList<Base>(); 3218 } else if (eq == true) { 3219 distinct = false; 3220 break; 3221 } 3222 } 3223 } 3224 return makeBoolean(distinct); 3225 } 3226 3227 3228 private List<Base> funcSupersetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3229 List<Base> target = execute(context, focus, exp.getParameters().get(0), true); 3230 3231 boolean valid = true; 3232 for (Base item : target) { 3233 boolean found = false; 3234 for (Base t : focus) { 3235 if (Base.compareDeep(item, t, false)) { 3236 found = true; 3237 break; 3238 } 3239 } 3240 if (!found) { 3241 valid = false; 3242 break; 3243 } 3244 } 3245 List<Base> result = new ArrayList<Base>(); 3246 result.add(new BooleanType(valid).noExtensions()); 3247 return result; 3248 } 3249 3250 3251 private List<Base> funcSubsetOf(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3252 List<Base> target = execute(context, focus, exp.getParameters().get(0), true); 3253 3254 boolean valid = true; 3255 for (Base item : focus) { 3256 boolean found = false; 3257 for (Base t : target) { 3258 if (Base.compareDeep(item, t, false)) { 3259 found = true; 3260 break; 3261 } 3262 } 3263 if (!found) { 3264 valid = false; 3265 break; 3266 } 3267 } 3268 List<Base> result = new ArrayList<Base>(); 3269 result.add(new BooleanType(valid).noExtensions()); 3270 return result; 3271 } 3272 3273 3274 private List<Base> funcExists(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3275 List<Base> result = new ArrayList<Base>(); 3276 boolean empty = true; 3277 for (Base f : focus) 3278 if (!f.isEmpty()) 3279 empty = false; 3280 result.add(new BooleanType(!empty).noExtensions()); 3281 return result; 3282 } 3283 3284 3285 private List<Base> funcResolve(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3286 List<Base> result = new ArrayList<Base>(); 3287 for (Base item : focus) { 3288 String s = convertToString(item); 3289 if (item.fhirType().equals("Reference")) { 3290 Property p = item.getChildByName("reference"); 3291 if (p != null && p.hasValues()) 3292 s = convertToString(p.getValues().get(0)); 3293 else 3294 s = null; // a reference without any valid actual reference (just identifier or display, but we can't resolve it) 3295 } 3296 if (item.fhirType().equals("canonical")) { 3297 s = item.primitiveValue(); 3298 } 3299 if (s != null) { 3300 Base res = null; 3301 if (s.startsWith("#")) { 3302 Property p = context.rootResource.getChildByName("contained"); 3303 for (Base c : p.getValues()) { 3304 if (chompHash(s).equals(chompHash(c.getIdBase()))) { 3305 res = c; 3306 break; 3307 } 3308 } 3309 } else if (hostServices != null) { 3310 res = hostServices.resolveReference(context.appInfo, s); 3311 } 3312 if (res != null) 3313 result.add(res); 3314 } 3315 } 3316 3317 return result; 3318 } 3319 3320 /** 3321 * Strips a leading hashmark (#) if present at the start of a string 3322 */ 3323 private String chompHash(String theId) { 3324 String retVal = theId; 3325 while (retVal.startsWith("#")) { 3326 retVal = retVal.substring(1); 3327 } 3328 return retVal; 3329 } 3330 3331 private List<Base> funcExtension(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3332 List<Base> result = new ArrayList<Base>(); 3333 List<Base> nl = execute(context, focus, exp.getParameters().get(0), true); 3334 String url = nl.get(0).primitiveValue(); 3335 3336 for (Base item : focus) { 3337 List<Base> ext = new ArrayList<Base>(); 3338 getChildrenByName(item, "extension", ext); 3339 getChildrenByName(item, "modifierExtension", ext); 3340 for (Base ex : ext) { 3341 List<Base> vl = new ArrayList<Base>(); 3342 getChildrenByName(ex, "url", vl); 3343 if (convertToString(vl).equals(url)) 3344 result.add(ex); 3345 } 3346 } 3347 return result; 3348 } 3349 3350 private List<Base> funcAllFalse(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3351 List<Base> result = new ArrayList<Base>(); 3352 if (exp.getParameters().size() == 1) { 3353 boolean all = true; 3354 List<Base> pc = new ArrayList<Base>(); 3355 for (Base item : focus) { 3356 pc.clear(); 3357 pc.add(item); 3358 List<Base> res = execute(context, pc, exp.getParameters().get(0), true); 3359 Equality v = asBool(res); 3360 if (v != Equality.False) { 3361 all = false; 3362 break; 3363 } 3364 } 3365 result.add(new BooleanType(all).noExtensions()); 3366 } else { 3367 boolean all = true; 3368 for (Base item : focus) { 3369 Equality v = asBool(item); 3370 if (v != Equality.False) { 3371 all = false; 3372 break; 3373 } 3374 } 3375 result.add(new BooleanType(all).noExtensions()); 3376 } 3377 return result; 3378 } 3379 3380 private List<Base> funcAnyFalse(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3381 List<Base> result = new ArrayList<Base>(); 3382 if (exp.getParameters().size() == 1) { 3383 boolean any = false; 3384 List<Base> pc = new ArrayList<Base>(); 3385 for (Base item : focus) { 3386 pc.clear(); 3387 pc.add(item); 3388 List<Base> res = execute(context, pc, exp.getParameters().get(0), true); 3389 Equality v = asBool(res); 3390 if (v == Equality.False) { 3391 any = true; 3392 break; 3393 } 3394 } 3395 result.add(new BooleanType(any).noExtensions()); 3396 } else { 3397 boolean any = false; 3398 for (Base item : focus) { 3399 Equality v = asBool(item); 3400 if (v == Equality.False) { 3401 any = true; 3402 break; 3403 } 3404 } 3405 result.add(new BooleanType(any).noExtensions()); 3406 } 3407 return result; 3408 } 3409 3410 private List<Base> funcAllTrue(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3411 List<Base> result = new ArrayList<Base>(); 3412 if (exp.getParameters().size() == 1) { 3413 boolean all = true; 3414 List<Base> pc = new ArrayList<Base>(); 3415 for (Base item : focus) { 3416 pc.clear(); 3417 pc.add(item); 3418 List<Base> res = execute(context, pc, exp.getParameters().get(0), true); 3419 Equality v = asBool(res); 3420 if (v != Equality.True) { 3421 all = false; 3422 break; 3423 } 3424 } 3425 result.add(new BooleanType(all).noExtensions()); 3426 } else { 3427 boolean all = true; 3428 for (Base item : focus) { 3429 Equality v = asBool(item); 3430 if (v != Equality.True) { 3431 all = false; 3432 break; 3433 } 3434 } 3435 result.add(new BooleanType(all).noExtensions()); 3436 } 3437 return result; 3438 } 3439 3440 private List<Base> funcAnyTrue(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3441 List<Base> result = new ArrayList<Base>(); 3442 if (exp.getParameters().size() == 1) { 3443 boolean any = false; 3444 List<Base> pc = new ArrayList<Base>(); 3445 for (Base item : focus) { 3446 pc.clear(); 3447 pc.add(item); 3448 List<Base> res = execute(context, pc, exp.getParameters().get(0), true); 3449 Equality v = asBool(res); 3450 if (v == Equality.True) { 3451 any = true; 3452 break; 3453 } 3454 } 3455 result.add(new BooleanType(any).noExtensions()); 3456 } else { 3457 boolean any = false; 3458 for (Base item : focus) { 3459 Equality v = asBool(item); 3460 if (v == Equality.True) { 3461 any = true; 3462 break; 3463 } 3464 } 3465 result.add(new BooleanType(any).noExtensions()); 3466 } 3467 return result; 3468 } 3469 3470 private List<Base> funcTrace(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3471 List<Base> nl = execute(context, focus, exp.getParameters().get(0), true); 3472 String name = nl.get(0).primitiveValue(); 3473 if (exp.getParameters().size() == 2) { 3474 List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true); 3475 log(name, n2); 3476 } else 3477 log(name, focus); 3478 return focus; 3479 } 3480 3481 private List<Base> funcCheck(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3482 List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true); 3483 if (!convertToBoolean(n1)) { 3484 List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true); 3485 String name = n2.get(0).primitiveValue(); 3486 throw new FHIRException("check failed: "+name); 3487 } 3488 return focus; 3489 } 3490 3491 private List<Base> funcDistinct(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3492 if (focus.size() <= 1) 3493 return focus; 3494 3495 List<Base> result = new ArrayList<Base>(); 3496 for (int i = 0; i < focus.size(); i++) { 3497 boolean found = false; 3498 for (int j = i+1; j < focus.size(); j++) { 3499 Boolean eq = doEquals(focus.get(j), focus.get(i)); 3500 if (eq == null) 3501 return new ArrayList<Base>(); 3502 else if (eq == true) { 3503 found = true; 3504 break; 3505 } 3506 } 3507 if (!found) 3508 result.add(focus.get(i)); 3509 } 3510 return result; 3511 } 3512 3513 private List<Base> funcMatches(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3514 List<Base> result = new ArrayList<Base>(); 3515 String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 3516 3517 if (focus.size() == 1 && !Utilities.noString(sw)) { 3518 String st = convertToString(focus.get(0)); 3519 if (Utilities.noString(st)) 3520 result.add(new BooleanType(false).noExtensions()); 3521 else { 3522 boolean ok = st.matches(sw); 3523 result.add(new BooleanType(ok).noExtensions()); 3524 } 3525 } else 3526 result.add(new BooleanType(false).noExtensions()); 3527 return result; 3528 } 3529 3530 private List<Base> funcContains(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3531 List<Base> result = new ArrayList<Base>(); 3532 String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 3533 3534 if (focus.size() != 1) { 3535 result.add(new BooleanType(false).noExtensions()); 3536 } else if (Utilities.noString(sw)) { 3537 result.add(new BooleanType(true).noExtensions()); 3538 } else { 3539 String st = convertToString(focus.get(0)); 3540 if (Utilities.noString(st)) 3541 result.add(new BooleanType(false).noExtensions()); 3542 else 3543 result.add(new BooleanType(st.contains(sw)).noExtensions()); 3544 } 3545 return result; 3546 } 3547 3548 private List<Base> funcLength(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3549 List<Base> result = new ArrayList<Base>(); 3550 if (focus.size() == 1) { 3551 String s = convertToString(focus.get(0)); 3552 result.add(new IntegerType(s.length()).noExtensions()); 3553 } 3554 return result; 3555 } 3556 3557 private List<Base> funcHasValue(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3558 List<Base> result = new ArrayList<Base>(); 3559 if (focus.size() == 1) { 3560 String s = convertToString(focus.get(0)); 3561 result.add(new BooleanType(!Utilities.noString(s)).noExtensions()); 3562 } else 3563 result.add(new BooleanType(false).noExtensions()); 3564 return result; 3565 } 3566 3567 private List<Base> funcStartsWith(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3568 List<Base> result = new ArrayList<Base>(); 3569 String sw = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 3570 3571 if (focus.size() == 0) { 3572 result.add(new BooleanType(false).noExtensions()); 3573 } else if (Utilities.noString(sw)) { 3574 result.add(new BooleanType(true).noExtensions()); 3575 } else { 3576 String s = convertToString(focus.get(0)); 3577 if (s == null) 3578 result.add(new BooleanType(false).noExtensions()); 3579 else 3580 result.add(new BooleanType(s.startsWith(sw)).noExtensions()); 3581 } 3582 return result; 3583 } 3584 3585 private List<Base> funcLower(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3586 List<Base> result = new ArrayList<Base>(); 3587 if (focus.size() == 1) { 3588 String s = convertToString(focus.get(0)); 3589 if (!Utilities.noString(s)) 3590 result.add(new StringType(s.toLowerCase()).noExtensions()); 3591 } 3592 return result; 3593 } 3594 3595 private List<Base> funcUpper(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3596 List<Base> result = new ArrayList<Base>(); 3597 if (focus.size() == 1) { 3598 String s = convertToString(focus.get(0)); 3599 if (!Utilities.noString(s)) 3600 result.add(new StringType(s.toUpperCase()).noExtensions()); 3601 } 3602 return result; 3603 } 3604 3605 private List<Base> funcToChars(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3606 List<Base> result = new ArrayList<Base>(); 3607 if (focus.size() == 1) { 3608 String s = convertToString(focus.get(0)); 3609 for (char c : s.toCharArray()) 3610 result.add(new StringType(String.valueOf(c)).noExtensions()); 3611 } 3612 return result; 3613 } 3614 3615 private List<Base> funcSubstring(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3616 List<Base> result = new ArrayList<Base>(); 3617 List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true); 3618 int i1 = Integer.parseInt(n1.get(0).primitiveValue()); 3619 int i2 = -1; 3620 if (exp.parameterCount() == 2) { 3621 List<Base> n2 = execute(context, focus, exp.getParameters().get(1), true); 3622 i2 = Integer.parseInt(n2.get(0).primitiveValue()); 3623 } 3624 3625 if (focus.size() == 1) { 3626 String sw = convertToString(focus.get(0)); 3627 String s; 3628 if (i1 < 0 || i1 >= sw.length()) 3629 return new ArrayList<Base>(); 3630 if (exp.parameterCount() == 2) 3631 s = sw.substring(i1, Math.min(sw.length(), i1+i2)); 3632 else 3633 s = sw.substring(i1); 3634 if (!Utilities.noString(s)) 3635 result.add(new StringType(s).noExtensions()); 3636 } 3637 return result; 3638 } 3639 3640 private List<Base> funcToInteger(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3641 String s = convertToString(focus); 3642 List<Base> result = new ArrayList<Base>(); 3643 if (Utilities.isInteger(s)) 3644 result.add(new IntegerType(s).noExtensions()); 3645 else if ("true".equals(s)) 3646 result.add(new IntegerType(1).noExtensions()); 3647 else if ("false".equals(s)) 3648 result.add(new IntegerType(0).noExtensions()); 3649 return result; 3650 } 3651 3652 private List<Base> funcIsInteger(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3653 List<Base> result = new ArrayList<Base>(); 3654 if (focus.size() != 1) 3655 result.add(new BooleanType(false).noExtensions()); 3656 else if (focus.get(0) instanceof IntegerType) 3657 result.add(new BooleanType(true).noExtensions()); 3658 else if (focus.get(0) instanceof BooleanType) 3659 result.add(new BooleanType(true).noExtensions()); 3660 else if (focus.get(0) instanceof StringType) 3661 result.add(new BooleanType(Utilities.isInteger(convertToString(focus.get(0)))).noExtensions()); 3662 else 3663 result.add(new BooleanType(false).noExtensions()); 3664 return result; 3665 } 3666 3667 private List<Base> funcIsBoolean(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3668 List<Base> result = new ArrayList<Base>(); 3669 if (focus.size() != 1) 3670 result.add(new BooleanType(false).noExtensions()); 3671 else if (focus.get(0) instanceof IntegerType) 3672 result.add(new BooleanType(((IntegerType) focus.get(0)).getValue() >= 0 && ((IntegerType) focus.get(0)).getValue() <= 1).noExtensions()); 3673 else if (focus.get(0) instanceof DecimalType) 3674 result.add(new BooleanType(((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ZERO) == 0 || ((DecimalType) focus.get(0)).getValue().compareTo(BigDecimal.ONE) == 0).noExtensions()); 3675 else if (focus.get(0) instanceof BooleanType) 3676 result.add(new BooleanType(true).noExtensions()); 3677 else if (focus.get(0) instanceof StringType) 3678 result.add(new BooleanType(Utilities.existsInList(convertToString(focus.get(0)).toLowerCase(), "true", "false")).noExtensions()); 3679 else 3680 result.add(new BooleanType(false).noExtensions()); 3681 return result; 3682 } 3683 3684 private List<Base> funcIsDateTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3685 List<Base> result = new ArrayList<Base>(); 3686 if (focus.size() != 1) 3687 result.add(new BooleanType(false).noExtensions()); 3688 else if (focus.get(0) instanceof DateTimeType || focus.get(0) instanceof DateType) 3689 result.add(new BooleanType(true).noExtensions()); 3690 else if (focus.get(0) instanceof StringType) 3691 result.add(new BooleanType((convertToString(focus.get(0)).matches 3692 ("([0-9]([0-9]([0-9][1-9]|[1-9]0)|[1-9]00)|[1-9]000)(-(0[1-9]|1[0-2])(-(0[1-9]|[1-2][0-9]|3[0-1])(T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?)?)?)?"))).noExtensions()); 3693 else 3694 result.add(new BooleanType(false).noExtensions()); 3695 return result; 3696 } 3697 3698 private List<Base> funcConformsTo(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3699 if (hostServices == null) 3700 throw new FHIRException("Unable to check conformsTo - no hostservices provided"); 3701 List<Base> result = new ArrayList<Base>(); 3702 if (focus.size() != 1) 3703 result.add(new BooleanType(false).noExtensions()); 3704 else { 3705 String url = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 3706 result.add(new BooleanType(hostServices.conformsToProfile(context.appInfo, focus.get(0), url)).noExtensions()); 3707 } 3708 return result; 3709 } 3710 3711 private List<Base> funcIsTime(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3712 List<Base> result = new ArrayList<Base>(); 3713 if (focus.size() != 1) 3714 result.add(new BooleanType(false).noExtensions()); 3715 else if (focus.get(0) instanceof TimeType) 3716 result.add(new BooleanType(true).noExtensions()); 3717 else if (focus.get(0) instanceof StringType) 3718 result.add(new BooleanType((convertToString(focus.get(0)).matches 3719 ("T([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?(Z|(\\+|-)((0[0-9]|1[0-3]):[0-5][0-9]|14:00))?"))).noExtensions()); 3720 else 3721 result.add(new BooleanType(false).noExtensions()); 3722 return result; 3723 } 3724 3725 private List<Base> funcIsString(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3726 List<Base> result = new ArrayList<Base>(); 3727 if (focus.size() != 1) 3728 result.add(new BooleanType(false).noExtensions()); 3729 else if (!(focus.get(0) instanceof DateTimeType) && !(focus.get(0) instanceof TimeType)) 3730 result.add(new BooleanType(true).noExtensions()); 3731 else 3732 result.add(new BooleanType(false).noExtensions()); 3733 return result; 3734 } 3735 3736 private List<Base> funcIsQuantity(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3737 List<Base> result = new ArrayList<Base>(); 3738 if (focus.size() != 1) 3739 result.add(new BooleanType(false).noExtensions()); 3740 else if (focus.get(0) instanceof IntegerType) 3741 result.add(new BooleanType(true).noExtensions()); 3742 else if (focus.get(0) instanceof DecimalType) 3743 result.add(new BooleanType(true).noExtensions()); 3744 else if (focus.get(0) instanceof Quantity) 3745 result.add(new BooleanType(true).noExtensions()); 3746 else if (focus.get(0) instanceof BooleanType) 3747 result.add(new BooleanType(true).noExtensions()); 3748 else if (focus.get(0) instanceof StringType) { 3749 Quantity q = parseQuantityString(focus.get(0).primitiveValue()); 3750 result.add(new BooleanType(q != null).noExtensions()); 3751 } else 3752 result.add(new BooleanType(false).noExtensions()); 3753 return result; 3754 } 3755 3756 public Quantity parseQuantityString(String s) { 3757 if (s == null) 3758 return null; 3759 s = s.trim(); 3760 if (s.contains(" ")) { 3761 String v = s.substring(0, s.indexOf(" ")).trim(); 3762 s = s.substring(s.indexOf(" ")).trim(); 3763 if (!Utilities.isDecimal(v, false)) 3764 return null; 3765 if (s.startsWith("'") && s.endsWith("'")) 3766 return Quantity.fromUcum(v, s.substring(1, s.length()-1)); 3767 if (s.equals("year") || s.equals("years")) 3768 return Quantity.fromUcum(v, "a"); 3769 else if (s.equals("month") || s.equals("months")) 3770 return Quantity.fromUcum(v, "mo"); 3771 else if (s.equals("week") || s.equals("weeks")) 3772 return Quantity.fromUcum(v, "wk"); 3773 else if (s.equals("day") || s.equals("days")) 3774 return Quantity.fromUcum(v, "d"); 3775 else if (s.equals("hour") || s.equals("hours")) 3776 return Quantity.fromUcum(v, "h"); 3777 else if (s.equals("minute") || s.equals("minutes")) 3778 return Quantity.fromUcum(v, "min"); 3779 else if (s.equals("second") || s.equals("seconds")) 3780 return Quantity.fromUcum(v, "s"); 3781 else if (s.equals("millisecond") || s.equals("milliseconds")) 3782 return Quantity.fromUcum(v, "ms"); 3783 else 3784 return null; 3785 } else { 3786 if (Utilities.isDecimal(s, true)) 3787 return new Quantity().setValue(new BigDecimal(s)).setSystem("http://unitsofmeasure.org").setCode("1"); 3788 else 3789 return null; 3790 } 3791 } 3792 3793 3794 private List<Base> funcIsDecimal(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3795 List<Base> result = new ArrayList<Base>(); 3796 if (focus.size() != 1) 3797 result.add(new BooleanType(false).noExtensions()); 3798 else if (focus.get(0) instanceof IntegerType) 3799 result.add(new BooleanType(true).noExtensions()); 3800 else if (focus.get(0) instanceof BooleanType) 3801 result.add(new BooleanType(true).noExtensions()); 3802 else if (focus.get(0) instanceof DecimalType) 3803 result.add(new BooleanType(true).noExtensions()); 3804 else if (focus.get(0) instanceof StringType) 3805 result.add(new BooleanType(Utilities.isDecimal(convertToString(focus.get(0)), true)).noExtensions()); 3806 else 3807 result.add(new BooleanType(false).noExtensions()); 3808 return result; 3809 } 3810 3811 private List<Base> funcCount(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3812 List<Base> result = new ArrayList<Base>(); 3813 result.add(new IntegerType(focus.size()).noExtensions()); 3814 return result; 3815 } 3816 3817 private List<Base> funcSkip(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3818 List<Base> n1 = execute(context, focus, exp.getParameters().get(0), true); 3819 int i1 = Integer.parseInt(n1.get(0).primitiveValue()); 3820 3821 List<Base> result = new ArrayList<Base>(); 3822 for (int i = i1; i < focus.size(); i++) 3823 result.add(focus.get(i)); 3824 return result; 3825 } 3826 3827 private List<Base> funcTail(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3828 List<Base> result = new ArrayList<Base>(); 3829 for (int i = 1; i < focus.size(); i++) 3830 result.add(focus.get(i)); 3831 return result; 3832 } 3833 3834 private List<Base> funcLast(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3835 List<Base> result = new ArrayList<Base>(); 3836 if (focus.size() > 0) 3837 result.add(focus.get(focus.size()-1)); 3838 return result; 3839 } 3840 3841 private List<Base> funcFirst(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3842 List<Base> result = new ArrayList<Base>(); 3843 if (focus.size() > 0) 3844 result.add(focus.get(0)); 3845 return result; 3846 } 3847 3848 3849 private List<Base> funcWhere(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3850 List<Base> result = new ArrayList<Base>(); 3851 List<Base> pc = new ArrayList<Base>(); 3852 for (Base item : focus) { 3853 pc.clear(); 3854 pc.add(item); 3855 Equality v = asBool(execute(changeThis(context, item), pc, exp.getParameters().get(0), true)); 3856 if (v == Equality.True) 3857 result.add(item); 3858 } 3859 return result; 3860 } 3861 3862 private List<Base> funcSelect(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3863 List<Base> result = new ArrayList<Base>(); 3864 List<Base> pc = new ArrayList<Base>(); 3865 for (Base item : focus) { 3866 pc.clear(); 3867 pc.add(item); 3868 result.addAll(execute(changeThis(context, item), pc, exp.getParameters().get(0), true)); 3869 } 3870 return result; 3871 } 3872 3873 3874 private List<Base> funcItem(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws FHIRException { 3875 List<Base> result = new ArrayList<Base>(); 3876 String s = convertToString(execute(context, focus, exp.getParameters().get(0), true)); 3877 if (Utilities.isInteger(s) && Integer.parseInt(s) < focus.size()) 3878 result.add(focus.get(Integer.parseInt(s))); 3879 return result; 3880 } 3881 3882 private List<Base> funcEmpty(ExecutionContext context, List<Base> focus, ExpressionNode exp) { 3883 List<Base> result = new ArrayList<Base>(); 3884 result.add(new BooleanType(ElementUtil.isEmpty(focus)).noExtensions()); 3885 return result; 3886 } 3887 3888 private List<Base> funcNot(ExecutionContext context, List<Base> focus, ExpressionNode exp) throws PathEngineException { 3889 List<Base> result = new ArrayList<Base>(); 3890 Equality v = asBool(focus); 3891 if (v != Equality.Null) 3892 result.add(new BooleanType(v != Equality.True)); 3893 return result; 3894 } 3895 3896 public class ElementDefinitionMatch { 3897 private ElementDefinition definition; 3898 private String fixedType; 3899 public ElementDefinitionMatch(ElementDefinition definition, String fixedType) { 3900 super(); 3901 this.definition = definition; 3902 this.fixedType = fixedType; 3903 } 3904 public ElementDefinition getDefinition() { 3905 return definition; 3906 } 3907 public String getFixedType() { 3908 return fixedType; 3909 } 3910 3911 } 3912 3913 private void getChildTypesByName(String type, String name, TypeDetails result) throws PathEngineException, DefinitionException { 3914 if (Utilities.noString(type)) 3915 throw new PathEngineException("No type provided in BuildToolPathEvaluator.getChildTypesByName"); 3916 if (type.equals("http://hl7.org/fhir/StructureDefinition/xhtml")) 3917 return; 3918 if (type.startsWith(Constants.NS_SYSTEM_TYPE)) 3919 return; 3920 3921 if (type.equals(TypeDetails.FP_SimpleTypeInfo)) { 3922 getSimpleTypeChildTypesByName(name, result); 3923 } else if (type.equals(TypeDetails.FP_ClassInfo)) { 3924 getClassInfoChildTypesByName(name, result); 3925 } else { 3926 String url = null; 3927 if (type.contains("#")) { 3928 url = type.substring(0, type.indexOf("#")); 3929 } else { 3930 url = type; 3931 } 3932 String tail = ""; 3933 StructureDefinition sd = worker.fetchResource(StructureDefinition.class, url); 3934 if (sd == null) 3935 throw new DefinitionException("Unknown type "+type); // this really is an error, because we can only get to here if the internal infrastrucgture is wrong 3936 List<StructureDefinition> sdl = new ArrayList<StructureDefinition>(); 3937 ElementDefinitionMatch m = null; 3938 if (type.contains("#")) 3939 m = getElementDefinition(sd, type.substring(type.indexOf("#")+1), false); 3940 if (m != null && hasDataType(m.definition)) { 3941 if (m.fixedType != null) 3942 { 3943 StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(m.fixedType, worker.getOverrideVersionNs())); 3944 if (dt == null) 3945 throw new DefinitionException("unknown data type "+m.fixedType); 3946 sdl.add(dt); 3947 } else 3948 for (TypeRefComponent t : m.definition.getType()) { 3949 StructureDefinition dt = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(t.getCode(), worker.getOverrideVersionNs())); 3950 if (dt == null) 3951 throw new DefinitionException("unknown data type "+t.getCode()); 3952 sdl.add(dt); 3953 } 3954 } else { 3955 sdl.add(sd); 3956 if (type.contains("#")) { 3957 tail = type.substring(type.indexOf("#")+1); 3958 tail = tail.substring(tail.indexOf(".")); 3959 } 3960 } 3961 3962 for (StructureDefinition sdi : sdl) { 3963 String path = sdi.getSnapshot().getElement().get(0).getPath()+tail+"."; 3964 if (name.equals("**")) { 3965 assert(result.getCollectionStatus() == CollectionStatus.UNORDERED); 3966 for (ElementDefinition ed : sdi.getSnapshot().getElement()) { 3967 if (ed.getPath().startsWith(path)) 3968 for (TypeRefComponent t : ed.getType()) { 3969 if (t.hasCode() && t.getCodeElement().hasValue()) { 3970 String tn = null; 3971 if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) 3972 tn = sdi.getType()+"#"+ed.getPath(); 3973 else 3974 tn = t.getCode(); 3975 if (t.getCode().equals("Resource")) { 3976 for (String rn : worker.getResourceNames()) { 3977 if (!result.hasType(worker, rn)) { 3978 getChildTypesByName(result.addType(rn), "**", result); 3979 } 3980 } 3981 } else if (!result.hasType(worker, tn)) { 3982 getChildTypesByName(result.addType(tn), "**", result); 3983 } 3984 } 3985 } 3986 } 3987 } else if (name.equals("*")) { 3988 assert(result.getCollectionStatus() == CollectionStatus.UNORDERED); 3989 for (ElementDefinition ed : sdi.getSnapshot().getElement()) { 3990 if (ed.getPath().startsWith(path) && !ed.getPath().substring(path.length()).contains(".")) 3991 for (TypeRefComponent t : ed.getType()) { 3992 if (Utilities.noString(t.getCode())) // Element.id or Extension.url 3993 result.addType("System.string"); 3994 else if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) 3995 result.addType(sdi.getType()+"#"+ed.getPath()); 3996 else if (t.getCode().equals("Resource")) 3997 result.addTypes(worker.getResourceNames()); 3998 else 3999 result.addType(t.getCode()); 4000 } 4001 } 4002 } else { 4003 path = sdi.getSnapshot().getElement().get(0).getPath()+tail+"."+name; 4004 4005 ElementDefinitionMatch ed = getElementDefinition(sdi, path, false); 4006 if (ed != null) { 4007 if (!Utilities.noString(ed.getFixedType())) 4008 result.addType(ed.getFixedType()); 4009 else 4010 for (TypeRefComponent t : ed.getDefinition().getType()) { 4011 if (Utilities.noString(t.getCode())) { 4012 if (Utilities.existsInList(ed.getDefinition().getId(), "Element.id", "Extension.url") || Utilities.existsInList(ed.getDefinition().getBase().getPath(), "Resource.id", "Element.id", "Extension.url")) 4013 result.addType(TypeDetails.FP_NS, "string"); 4014 break; // throw new PathEngineException("Illegal reference to primitive value attribute @ "+path); 4015 } 4016 4017 ProfiledType pt = null; 4018 if (t.getCode().equals("Element") || t.getCode().equals("BackboneElement")) 4019 pt = new ProfiledType(sdi.getUrl()+"#"+path); 4020 else if (t.getCode().equals("Resource")) 4021 result.addTypes(worker.getResourceNames()); 4022 else 4023 pt = new ProfiledType(t.getCode()); 4024 if (pt != null) { 4025 if (t.hasProfile()) 4026 pt.addProfiles(t.getProfile()); 4027 if (ed.getDefinition().hasBinding()) 4028 pt.addBinding(ed.getDefinition().getBinding()); 4029 result.addType(pt); 4030 } 4031 } 4032 } 4033 } 4034 } 4035 } 4036 } 4037 4038 private void getClassInfoChildTypesByName(String name, TypeDetails result) { 4039 if (name.equals("namespace")) 4040 result.addType(TypeDetails.FP_String); 4041 if (name.equals("name")) 4042 result.addType(TypeDetails.FP_String); 4043 } 4044 4045 4046 private void getSimpleTypeChildTypesByName(String name, TypeDetails result) { 4047 if (name.equals("namespace")) 4048 result.addType(TypeDetails.FP_String); 4049 if (name.equals("name")) 4050 result.addType(TypeDetails.FP_String); 4051 } 4052 4053 4054 private ElementDefinitionMatch getElementDefinition(StructureDefinition sd, String path, boolean allowTypedName) throws PathEngineException { 4055 for (ElementDefinition ed : sd.getSnapshot().getElement()) { 4056 if (ed.getPath().equals(path)) { 4057 if (ed.hasContentReference()) { 4058 return getElementDefinitionById(sd, ed.getContentReference()); 4059 } else 4060 return new ElementDefinitionMatch(ed, null); 4061 } 4062 if (ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length()-3)) && path.length() == ed.getPath().length()-3) 4063 return new ElementDefinitionMatch(ed, null); 4064 if (allowTypedName && ed.getPath().endsWith("[x]") && path.startsWith(ed.getPath().substring(0, ed.getPath().length()-3)) && path.length() > ed.getPath().length()-3) { 4065 String s = Utilities.uncapitalize(path.substring(ed.getPath().length()-3)); 4066 if (primitiveTypes.contains(s)) 4067 return new ElementDefinitionMatch(ed, s); 4068 else 4069 return new ElementDefinitionMatch(ed, path.substring(ed.getPath().length()-3)); 4070 } 4071 if (ed.getPath().contains(".") && path.startsWith(ed.getPath()+".") && (ed.getType().size() > 0) && !isAbstractType(ed.getType())) { 4072 // now we walk into the type. 4073 if (ed.getType().size() > 1) // if there's more than one type, the test above would fail this 4074 throw new PathEngineException("Internal typing issue...."); 4075 StructureDefinition nsd = worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(ed.getType().get(0).getCode(), worker.getOverrideVersionNs())); 4076 if (nsd == null) 4077 throw new PathEngineException("Unknown type "+ed.getType().get(0).getCode()); 4078 return getElementDefinition(nsd, nsd.getId()+path.substring(ed.getPath().length()), allowTypedName); 4079 } 4080 if (ed.hasContentReference() && path.startsWith(ed.getPath()+".")) { 4081 ElementDefinitionMatch m = getElementDefinitionById(sd, ed.getContentReference()); 4082 return getElementDefinition(sd, m.definition.getPath()+path.substring(ed.getPath().length()), allowTypedName); 4083 } 4084 } 4085 return null; 4086 } 4087 4088 private boolean isAbstractType(List<TypeRefComponent> list) { 4089 return list.size() != 1 ? true : Utilities.existsInList(list.get(0).getCode(), "Element", "BackboneElement", "Resource", "DomainResource"); 4090} 4091 4092 4093 private boolean hasType(ElementDefinition ed, String s) { 4094 for (TypeRefComponent t : ed.getType()) 4095 if (s.equalsIgnoreCase(t.getCode())) 4096 return true; 4097 return false; 4098 } 4099 4100 private boolean hasDataType(ElementDefinition ed) { 4101 return ed.hasType() && !(ed.getType().get(0).getCode().equals("Element") || ed.getType().get(0).getCode().equals("BackboneElement")); 4102 } 4103 4104 private ElementDefinitionMatch getElementDefinitionById(StructureDefinition sd, String ref) { 4105 for (ElementDefinition ed : sd.getSnapshot().getElement()) { 4106 if (ref.equals("#"+ed.getId())) 4107 return new ElementDefinitionMatch(ed, null); 4108 } 4109 return null; 4110 } 4111 4112 4113 public boolean hasLog() { 4114 return log != null && log.length() > 0; 4115 } 4116 4117 4118 public String takeLog() { 4119 if (!hasLog()) 4120 return ""; 4121 String s = log.toString(); 4122 log = new StringBuilder(); 4123 return s; 4124 } 4125 4126 4127 /** given an element definition in a profile, what element contains the differentiating fixed 4128 * for the element, given the differentiating expresssion. The expression is only allowed to 4129 * use a subset of FHIRPath 4130 * 4131 * @param profile 4132 * @param element 4133 * @return 4134 * @throws PathEngineException 4135 * @throws DefinitionException 4136 */ 4137 public ElementDefinition evaluateDefinition(ExpressionNode expr, StructureDefinition profile, ElementDefinition element) throws DefinitionException { 4138 StructureDefinition sd = profile; 4139 ElementDefinition focus = null; 4140 4141 if (expr.getKind() == Kind.Name) { 4142 if (element.hasSlicing()) { 4143 ElementDefinition slice = pickMandatorySlice(sd, element); 4144 if (slice == null) 4145 throw new DefinitionException("Error in discriminator at "+element.getId()+": found a sliced element while resolving the fixed value for one of the slices"); 4146 element = slice; 4147 } 4148 4149 if (expr.getName().equals("$this")) { 4150 focus = element; 4151 } else { 4152 List<ElementDefinition> childDefinitions; 4153 childDefinitions = ProfileUtilities.getChildMap(sd, element); 4154 // if that's empty, get the children of the type 4155 if (childDefinitions.isEmpty()) { 4156 sd = fetchStructureByType(element); 4157 if (sd == null) 4158 throw new DefinitionException("Problem with use of resolve() - profile '"+element.getType().get(0).getProfile()+"' on "+element.getId()+" could not be resolved"); 4159 childDefinitions = ProfileUtilities.getChildMap(sd, sd.getSnapshot().getElementFirstRep()); 4160 } 4161 for (ElementDefinition t : childDefinitions) { 4162 if (tailMatches(t, expr.getName())) { 4163 focus = t; 4164 break; 4165 } 4166 } 4167 } 4168 } else if (expr.getKind() == Kind.Function) { 4169 if ("resolve".equals(expr.getName())) { 4170 if (!element.hasType()) 4171 throw new DefinitionException("illegal use of resolve() in discriminator - no type on element "+element.getId()); 4172 if (element.getType().size() > 1) 4173 throw new DefinitionException("illegal use of resolve() in discriminator - Multiple possible types on "+element.getId()); 4174 if (!element.getType().get(0).hasTarget()) 4175 throw new DefinitionException("illegal use of resolve() in discriminator - type on "+element.getId()+" is not Reference ("+element.getType().get(0).getCode()+")"); 4176 if (element.getType().get(0).getTargetProfile().size() > 1) 4177 throw new DefinitionException("illegal use of resolve() in discriminator - Multiple possible target type profiles on "+element.getId()); 4178 sd = worker.fetchResource(StructureDefinition.class, element.getType().get(0).getTargetProfile().get(0).getValue()); 4179 if (sd == null) 4180 throw new DefinitionException("Problem with use of resolve() - profile '"+element.getType().get(0).getTargetProfile()+"' on "+element.getId()+" could not be resolved"); 4181 focus = sd.getSnapshot().getElementFirstRep(); 4182 } else if ("extension".equals(expr.getName())) { 4183 String targetUrl = expr.getParameters().get(0).getConstant().primitiveValue(); 4184// targetUrl = targetUrl.substring(1,targetUrl.length()-1); 4185 List<ElementDefinition> childDefinitions = ProfileUtilities.getChildMap(sd, element); 4186 for (ElementDefinition t : childDefinitions) { 4187 if (t.getPath().endsWith(".extension") && t.hasSliceName()) { 4188 StructureDefinition exsd = worker.fetchResource(StructureDefinition.class, t.getType().get(0).getProfile().get(0).getValue()); 4189 while (exsd!=null && !exsd.getBaseDefinition().equals("http://hl7.org/fhir/StructureDefinition/Extension")) 4190 exsd = worker.fetchResource(StructureDefinition.class, exsd.getBaseDefinition()); 4191 if (exsd.getUrl().equals(targetUrl)) { 4192 if (ProfileUtilities.getChildMap(sd, t).isEmpty()) 4193 sd = exsd; 4194 focus = t; 4195 break; 4196 } 4197 } 4198 } 4199 } else 4200 throw new DefinitionException("illegal function name "+expr.getName()+"() in discriminator"); 4201 } else if (expr.getKind() == Kind.Group) { 4202 throw new DefinitionException("illegal expression syntax in discriminator (group)"); 4203 } else if (expr.getKind() == Kind.Constant) { 4204 throw new DefinitionException("illegal expression syntax in discriminator (const)"); 4205 } 4206 4207 if (focus == null) 4208 throw new DefinitionException("Unable to resolve discriminator in definitions: "+expr.toString()); 4209 else if (expr.getInner() == null) 4210 return focus; 4211 else { 4212 return evaluateDefinition(expr.getInner(), sd, focus); 4213 } 4214 } 4215 4216 private ElementDefinition pickMandatorySlice(StructureDefinition sd, ElementDefinition element) throws DefinitionException { 4217 List<ElementDefinition> list = ProfileUtilities.getSliceList(sd, element); 4218 for (ElementDefinition ed : list) { 4219 if (ed.getMin() > 0) 4220 return ed; 4221 } 4222 return null; 4223 } 4224 4225 4226 private StructureDefinition fetchStructureByType(ElementDefinition ed) throws DefinitionException { 4227 if (ed.getType().size() == 0) 4228 throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, no type"); 4229 if (ed.getType().size() > 1) 4230 throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, multiple types"); 4231 if (ed.getType().get(0).getProfile().size() > 1) 4232 throw new DefinitionException("Error in discriminator at "+ed.getId()+": no children, multiple type profiles"); 4233 if (ed.getType().get(0).hasProfile()) 4234 return worker.fetchResource(StructureDefinition.class, ed.getType().get(0).getProfile().get(0).getValue()); 4235 else 4236 return worker.fetchResource(StructureDefinition.class, ProfileUtilities.sdNs(ed.getType().get(0).getCode(), worker.getOverrideVersionNs())); 4237 } 4238 4239 4240 private boolean tailMatches(ElementDefinition t, String d) { 4241 String tail = tailDot(t.getPath()); 4242 if (d.contains("[")) 4243 return tail.startsWith(d.substring(0, d.indexOf('['))); 4244 else if (tail.equals(d)) 4245 return true; 4246 else if (t.getType().size() == 1 && t.getType().get(0).getCode() != null && t.getPath() != null && t.getPath().toUpperCase().endsWith(t.getType().get(0).getCode().toUpperCase())) 4247 return tail.startsWith(d); 4248 else if (t.getPath().endsWith("[x]") && tail.startsWith(d)) 4249 return true; 4250 return false; 4251 } 4252 4253 private String tailDot(String path) { 4254 return path.substring(path.lastIndexOf(".") + 1); 4255 } 4256 4257 private Equality asBool(List<Base> items) throws PathEngineException { 4258 if (items.size() == 0) 4259 return Equality.Null; 4260 else if (items.size() == 1) 4261 return asBool(items.get(0)); 4262 else 4263 throw new PathEngineException("Unable to evaluate as a boolean: "+convertToString(items)); 4264 } 4265 4266 private Equality asBoolFromInt(String s) { 4267 try { 4268 int i = Integer.parseInt(s); 4269 switch (i) { 4270 case 0: return Equality.False; 4271 case 1: return Equality.True; 4272 default: return Equality.Null; 4273 } 4274 } catch (Exception e) { 4275 return Equality.Null; 4276 } 4277 } 4278 4279 private Equality asBoolFromDec(String s) { 4280 try { 4281 BigDecimal d = new BigDecimal(s); 4282 if (d.compareTo(BigDecimal.ZERO) == 0) 4283 return Equality.False; 4284 else if (d.compareTo(BigDecimal.ONE) == 0) 4285 return Equality.True; 4286 else 4287 return Equality.Null; 4288 } catch (Exception e) { 4289 return Equality.Null; 4290 } 4291 } 4292 4293 private Equality asBool(Base item) { 4294 if (item instanceof BooleanType) 4295 return boolToTriState(((BooleanType) item).booleanValue()); 4296 else if (item.isBooleanPrimitive()) { 4297 if (Utilities.existsInList(item.primitiveValue(), "true")) 4298 return Equality.True; 4299 else if (Utilities.existsInList(item.primitiveValue(), "false")) 4300 return Equality.False; 4301 else 4302 return Equality.Null; 4303 } else if (item instanceof IntegerType || Utilities.existsInList(item.fhirType(), "integer", "positiveint", "unsignedInt")) 4304 return asBoolFromInt(item.primitiveValue()); 4305 else if (item instanceof DecimalType || Utilities.existsInList(item.fhirType(), "decimal")) 4306 return asBoolFromDec(item.primitiveValue()); 4307 else if (Utilities.existsInList(item.fhirType(), FHIR_TYPES_STRING)) { 4308 if (Utilities.existsInList(item.primitiveValue(), "true", "t", "yes", "y")) 4309 return Equality.True; 4310 else if (Utilities.existsInList(item.primitiveValue(), "false", "f", "no", "n")) 4311 return Equality.False; 4312 else if (Utilities.isInteger(item.primitiveValue())) 4313 return asBoolFromInt(item.primitiveValue()); 4314 else if (Utilities.isDecimal(item.primitiveValue(), true)) 4315 return asBoolFromDec(item.primitiveValue()); 4316 else 4317 return Equality.Null; 4318 } 4319 return Equality.Null; 4320 } 4321 4322 private Equality boolToTriState(boolean b) { 4323 return b ? Equality.True : Equality.False; 4324 } 4325 4326 4327 public TerminologyServiceOptions getTerminologyServiceOptions() { 4328 return terminologyServiceOptions; 4329 } 4330 4331 4332 public IWorkerContext getWorker() { 4333 return worker; 4334 } 4335 4336}