001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.juneau.commons.svl; 018 019import static org.apache.juneau.commons.utils.CollectionUtils.*; 020import static org.apache.juneau.commons.utils.Shorts.*; 021 022import java.io.*; 023import java.util.*; 024import java.util.concurrent.*; 025import java.util.function.*; 026 027import org.apache.juneau.commons.inject.*; 028import org.apache.juneau.commons.svl.functions.*; 029import org.apache.juneau.commons.svl.vars.*; 030 031/** 032 * Utility class for resolving variables of the form <js>"${X:key}"</js> in strings. 033 * 034 * <p> 035 * Variables are of the form <c>${X:key}</c>, where <c>X</c> can consist of zero or more ASCII characters. 036 * <br>The variable key can contain anything, even nested variables that get recursively resolved. 037 * 038 * <p> 039 * Variables are defined through the {@link Builder#vars(Class[])} method. 040 * 041 * <p> 042 * The {@link Var} interface defines how variables are converted to values. 043 * 044 * <h2 class='section'>Example:</h2> 045 * <p class='bjava'> 046 * <jk>public class</jk> SystemPropertiesVar <jk>extends</jk> SimpleVar { 047 * 048 * <jc>// Must have a no-arg constructor!</jc> 049 * <jk>public</jk> SystemPropertiesVar() { 050 * <jk>super</jk>(<js>"S"</js>); 051 * } 052 * 053 * <ja>@Override</ja> 054 * <jk>public</jk> String resolve(VarResolverSession <jv>session</jv>, String <jv>value</jv>) { 055 * <jk>return</jk> System.<jsm>getProperty</jsm>(<jv>value</jv>); 056 * } 057 * } 058 * 059 * <jc>// Create a variable resolver that resolves system properties (e.g. "${S:java.home}")</jc> 060 * VarResolver <jv>varResolver</jv> = VarResolver.<jsm>create</jsm>().vars(SystemPropertiesVar.<jk>class</jk>).build(); 061 * 062 * <jc>// Use it!</jc> 063 * System.<jsf>out</jsf>.println(<jv>varResolver</jv>.resolve(<js>"java.home is set to ${S:java.home}"</js>)); 064 * </p> 065 * 066 * <h2 class='section'>See Also:</h2><ul> 067 * <li class='link'><a class="doclink" href="https://juneau.apache.org/docs/topics/MarshallSimpleVariableLanguage">Marshall Simple Variable Language</a> 068 * </ul> 069 */ 070@SuppressWarnings({ 071 "java:S3740", // Raw Var/Class types used intentionally for dynamic variable resolver registration where type parameters are not available 072 "resource", // VarResolver manages Closeable resources 073 "unchecked" // Var class/instance registration casts (Class<? extends Var>) and the raw Class passed to addBean come from Builder-validated entries 074}) 075public class VarResolver { 076 077 /** 078 * Builder class. 079 */ 080 public static class Builder { 081 082 private final WritableBeanStore beanStore; 083 final VarList vars; 084 final LinkedHashMap<Class<?>,Object> userBeans; 085 final List<VarFunction> functions; 086 private int maxRecursionDepth = DEFAULT_MAX_RECURSION_DEPTH; 087 private boolean strict; 088 private int maxCollectionSize = DEFAULT_MAX_COLLECTION_SIZE; 089 private int maxExprDepth = DEFAULT_MAX_EXPR_DEPTH; 090 private List<String> allowedFunctions; // null = allow all 091 private Function<Object,String> valueFormatter; // null = default JsonValueFormatter 092 093 /** 094 * Constructor. 095 */ 096 protected Builder() { 097 this.beanStore = new BasicBeanStore(); 098 vars = VarList.create(); 099 userBeans = new LinkedHashMap<>(); 100 functions = l(); 101 } 102 103 /** 104 * Copy constructor. 105 * 106 * @param copyFrom The bean to copy from. Must not be {@code null}. 107 */ 108 protected Builder(VarResolver copyFrom) { 109 this.beanStore = copyFrom.beanStore; 110 vars = VarList.of(copyFrom.vars); 111 userBeans = new LinkedHashMap<>(); 112 functions = list(copyFrom.allFunctions); 113 allowedFunctions = copyFrom.allowedFunctions == null ? null : new ArrayList<>(copyFrom.allowedFunctions); 114 maxRecursionDepth = copyFrom.maxRecursionDepth; 115 strict = copyFrom.strict; 116 maxCollectionSize = copyFrom.maxCollectionSize; 117 maxExprDepth = copyFrom.maxExprDepth; 118 valueFormatter = copyFrom.customValueFormatter; 119 } 120 121 /** 122 * Sets the maximum depth for re-resolving a var's output. 123 * 124 * <p> 125 * Default is {@link VarResolver#DEFAULT_MAX_RECURSION_DEPTH} (32). Must be positive. 126 * 127 * @param value The maximum recursion depth. Must be at least 1. 128 * @return This object. 129 */ 130 public Builder maxRecursionDepth(int value) { 131 if (value < 1) 132 throw iaex("maxRecursionDepth must be positive: %s", value); 133 maxRecursionDepth = value; 134 return this; 135 } 136 137 /** 138 * Enables or disables strict expression evaluation. 139 * 140 * <p> 141 * Default is <jk>false</jk> (lenient). 142 * 143 * @param value <jk>true</jk> to enable strict mode. 144 * @return This object. 145 */ 146 public Builder strict(boolean value) { 147 strict = value; 148 return this; 149 } 150 151 /** 152 * Sets the maximum number of elements allowed in a collection built by an expression. 153 * 154 * <p> 155 * Default is {@link VarResolver#DEFAULT_MAX_COLLECTION_SIZE} (1000). Must be positive. 156 * 157 * @param value The maximum collection size. Must be at least 1. 158 * @return This object. 159 */ 160 public Builder maxCollectionSize(int value) { 161 if (value < 1) 162 throw iaex("maxCollectionSize must be positive: %s", value); 163 maxCollectionSize = value; 164 return this; 165 } 166 167 /** 168 * Sets the formatter that converts the typed result of a {@code #{...}} expression to text. 169 * 170 * <p> 171 * Default is a {@link JsonValueFormatter} honouring {@link #maxCollectionSize(int)} and strict mode. A 172 * session can replace it per render with {@link VarResolverSession#valueFormatter(Function)}. 173 * A <jk>null</jk> result from the formatter is treated as the empty string. 174 * 175 * <p> 176 * A custom formatter <em>replaces</em> the default, so it does not get the default's depth, size, node and 177 * cycle limits (it must guard itself). It is also bypassed for {@link Structure} values, which use 178 * {@link Structure#toString()} unless a session formatter is set. 179 * 180 * @param value The formatter. <jk>null</jk> restores the default. 181 * @return This object. 182 */ 183 public Builder valueFormatter(Function<Object,String> value) { 184 valueFormatter = value; 185 return this; 186 } 187 188 /** 189 * Sets the maximum expression nesting depth accepted by the parser. 190 * 191 * <p> 192 * Default is {@link VarResolver#DEFAULT_MAX_EXPR_DEPTH} (32). Must be positive. 193 * 194 * @param value The maximum expression depth. Must be at least 1. 195 * @return This object. 196 */ 197 public Builder maxExprDepth(int value) { 198 if (value < 1) 199 throw iaex("maxExprDepth must be positive: %s", value); 200 maxExprDepth = value; 201 return this; 202 } 203 204 /** 205 * Returns the bean store used by this builder. 206 * 207 * @return The bean store used by this builder. 208 */ 209 public WritableBeanStore beanStore() { 210 return beanStore; 211 } 212 213 /** 214 * Adds a bean to the resolved {@link VarResolver}'s local bean store. 215 * 216 * <p> 217 * The bean is stored on this builder and merged into the resolver's local bean store at 218 * {@link #build()} time. The parent bean store passed at construction is not mutated, so beans 219 * added here are isolated to {@link VarResolver}s built from this builder. 220 * 221 * @param <T> The bean type. 222 * @param c The bean type. 223 * @param value The bean. 224 * @return This object . 225 */ 226 public <T> Builder bean(Class<T> c, T value) { 227 userBeans.put(c, value); 228 return this; 229 } 230 231 /** 232 * Adds the default variables to this builder. 233 * 234 * <p> 235 * The default variables are: 236 * <ul> 237 * <li>{@link SystemPropertiesVar} 238 * <li>{@link EnvVariablesVar} 239 * <li>{@link EnvFileVar} 240 * <li>{@link DotenvVar} 241 * <li>{@link ArgsVar} 242 * <li>{@link ManifestFileVar} 243 * </ul> 244 * 245 * <p> 246 * The 11 transformation {@code Var}s previously listed here ({@code SwitchVar}, 247 * {@code IfVar}, {@code CoalesceVar}, {@code PatternMatchVar}, {@code PatternReplaceVar}, 248 * {@code PatternExtractVar}, {@code UpperCaseVar}, {@code LowerCaseVar}, 249 * {@code NotEmptyVar}, {@code LenVar}, {@code SubstringVar}) were deleted in 10.0.0 and 250 * replaced by the {@code #{...}} script syntax. Use {@link #defaultFunctions()} to 251 * register the built-in catalog. 252 * 253 * @return This object . 254 */ 255 public Builder defaultVars() { 256 vars.addDefault(); 257 return this; 258 } 259 260 261 /** 262 * Register new variables with this resolver. 263 * 264 * @param values 265 * The variable resolver classes. 266 * These classes must subclass from {@link Var} and have no-arg constructors. 267 * @return This object . 268 */ 269 @SafeVarargs 270 public final Builder vars(Class<? extends Var>...values) { 271 vars.append(values); 272 return this; 273 } 274 275 /** 276 * Register new variables with this resolver. 277 * 278 * @param values 279 * The variable resolver classes. 280 * These classes must subclass from {@link Var} and have no-arg constructors. 281 * @return This object . 282 */ 283 public Builder vars(Var...values) { 284 vars.append(values); 285 return this; 286 } 287 288 /** 289 * Register new variables with this resolver. 290 * 291 * @param values 292 * The variable resolver classes. 293 * These classes must subclass from {@link Var} and have no-arg constructors. 294 * @return This object . 295 */ 296 public Builder vars(VarList values) { 297 vars.append(values); 298 return this; 299 } 300 301 /** 302 * Restricts which functions (including the reserved <c>$op.*</c> operator functions) the resolver exposes. 303 * 304 * <p> 305 * Each pattern is a glob over function names: <c>*</c> matches any run of characters, anything else matches 306 * exactly. A function is permitted if its name matches at least one pattern. Operators dispatch to 307 * <c>$op.*</c> functions (<c>$op.add</c>, <c>$op.ternary</c>, <c>$op.select</c>, ...), so they are denied by 308 * the allowlist too; use <c>allowFunctions("$op.*", ...)</c> to keep them. 309 * 310 * <p> 311 * If this method is never called, every function is permitted. Calling it with no patterns denies everything, 312 * operators included. Repeated calls are additive, including after {@link VarResolver#copy()}: a copy can widen the allowlist but cannot narrow it. The filter is applied to the final function set at 313 * {@link #build()} time, and is preserved by {@link VarResolver#copy()}. 314 * 315 * <p> 316 * A denied function or operator is treated like an unknown one (strict mode: {@link ExprException} saying it 317 * is "not permitted"; lenient mode: the expression is emitted verbatim). 318 * 319 * @param patterns The glob patterns. Must not be <jk>null</jk> or contain <jk>null</jk>. 320 * @return This builder. 321 */ 322 public Builder allowFunctions(String...patterns) { 323 Objects.requireNonNull(patterns, "patterns must not be null"); 324 for (var p : patterns) 325 Objects.requireNonNull(p, "allowFunctions pattern must not be null"); 326 if (allowedFunctions == null) 327 allowedFunctions = new ArrayList<>(); 328 Collections.addAll(allowedFunctions, patterns); 329 return this; 330 } 331 332 /** 333 * Register one or more {@link VarFunction} instances on this builder. 334 * 335 * <p> 336 * Functions registered here win over {@code BeanStore} / {@code ServiceLoader} / built-in 337 * catalog entries with the same {@link VarFunction#name() name} (later-wins-on-collision). 338 * Discovery channels merge these registrations with the auto-discovered set at 339 * {@link #build()} time. 340 * 341 * @param values The functions to register. 342 * @return This builder. 343 */ 344 public Builder functions(VarFunction... values) { 345 Collections.addAll(functions, values); 346 return this; 347 } 348 349 /** 350 * Register one or more {@link VarFunction} <i>classes</i> on this builder. Each class 351 * must have a public no-arg constructor; instances are created via the bean store at 352 * {@link #build()} time so dependency injection works the same way it does for 353 * {@link Var}s. 354 * 355 * @param values The function classes to register. 356 * @return This builder. 357 */ 358 @SafeVarargs 359 public final Builder functions(Class<? extends VarFunction>... values) { 360 for (var c : values) 361 functions.add(BeanInstantiator.of(VarFunction.class, beanStore).type(c).run()); 362 return this; 363 } 364 365 /** 366 * Registers the built-in {@link VarFunction} catalog. 367 * 368 * <p> 369 * Functions on the classpath that are advertised through {@link ServiceLoader} are <i>not</i> registered 370 * by this method; call {@link #loadServices()} to opt in. 371 * Explicit {@link #functions(VarFunction...)} / {@link #functions(Class...)} calls made after this one 372 * override built-ins on name collision. 373 * 374 * @return This builder. 375 */ 376 public Builder defaultFunctions() { 377 for (var c : BUILTIN_FUNCTION_CLASSES) 378 functions.add(BeanInstantiator.of(VarFunction.class, beanStore).type(c).run()); 379 return this; 380 } 381 382 /** 383 * Registers third-party {@link VarFunction} implementations discovered through {@link ServiceLoader} 384 * ({@code META-INF/services/org.apache.juneau.commons.svl.VarFunction}). 385 * 386 * <p> 387 * This is opt-in. A discovered function never replaces a function that is already registered 388 * under the same name (including the built-ins registered by {@link #defaultFunctions()}), so call 389 * this method after {@link #defaultFunctions()}. 390 * 391 * @return This builder. 392 */ 393 public Builder loadServices() { 394 var existing = new HashSet<String>(); 395 for (var f : functions) 396 existing.add(f.name()); 397 for (var f : ServiceLoader.load(VarFunction.class, VarResolver.class.getClassLoader())) { 398 if (existing.add(f.name())) 399 functions.add(f); 400 } 401 return this; 402 } 403 404 /** 405 * Builds the var resolver. 406 * 407 * @return A new {@link VarResolver}. 408 */ 409 public VarResolver build() { 410 return new VarResolver(this); 411 } 412 } 413 414 /** 415 * Built-in {@link VarFunction} classes registered by {@link Builder#defaultFunctions()}. 416 * 417 * <p> 418 * Order matters only for collisions inside the built-in catalog itself (and there should be 419 * none). 420 */ 421 private static final Class<? extends VarFunction>[] BUILTIN_FUNCTION_CLASSES = (Class<? extends VarFunction>[]) concat( 422 StringFunctions.ALL, 423 TypeConversionFunctions.ALL, 424 ArithmeticFunctions.ALL, 425 BooleanFunctions.ALL, 426 ConditionalFunctions.ALL, 427 RegexFunctions.ALL, 428 EncodingFunctions.ALL, 429 DateFunctions.ALL, 430 RandomFunctions.ALL, 431 JsonFunctions.ALL, 432 OpFunctions.ALL, 433 StructureFunctions.ALL, 434 CollectionFunctions.ALL 435 ); 436 437 @SafeVarargs 438 private static <T> Class<? extends T>[] concat(Class<? extends T>[]... arrays) { 439 var total = 0; 440 for (var a : arrays) total += a.length; 441 var out = new Class[total]; 442 var idx = 0; 443 for (var a : arrays) { 444 System.arraycopy(a, 0, out, idx, a.length); 445 idx += a.length; 446 } 447 return out; 448 } 449 450 /** 451 * Default string variable resolver with support for system properties, environment 452 * variables, and the built-in {@link VarFunction} catalog. 453 * 454 * <h4 class='section'>Built-in {@link Var} bindings:</h4> 455 * <ul> 456 * <li><c>${S:key[:default]}</c> - {@link SystemPropertiesVar} 457 * <li><c>${E:key[:default]}</c> - {@link EnvVariablesVar} 458 * <li><c>${EF:key[:default]}</c> - {@link EnvFileVar} 459 * <li><c>${DE:key[:default]}</c> - {@link DotenvVar} 460 * <li><c>${A:key[:default]}</c> - {@link ArgsVar} 461 * <li><c>${MF:key[:default]}</c> - {@link ManifestFileVar} 462 * </ul> 463 * 464 * <h4 class='section'>Built-in {@link VarFunction} catalog:</h4> 465 * <p> 466 * Ships ~68 built-in functions across 10 categories — string, type-conversion, arithmetic, 467 * boolean, conditional, regex, encoding, date/time, random/UUID, and JSON-navigation. 468 * Functions are invoked via the {@code #{name(args...)}} syntax. See 469 * {@link Builder#defaultFunctions()} for the registration mechanism. 470 * 471 * <p> 472 * The 11 transformation/conditional {@code Var}s previously bundled here 473 * ({@code SwitchVar}, {@code IfVar}, {@code CoalesceVar}, {@code PatternMatchVar}, 474 * {@code PatternReplaceVar}, {@code PatternExtractVar}, {@code UpperCaseVar}, 475 * {@code LowerCaseVar}, {@code NotEmptyVar}, {@code LenVar}, {@code SubstringVar}) were 476 * deleted in 10.0.0; their behavior is now covered by the {@code #{...}} script syntax. 477 */ 478 public static final VarResolver DEFAULT = create().defaultVars().defaultFunctions().build(); 479 480 /** 481 * Instantiates a new clean-slate {@link Builder} object. 482 * 483 * @return A new {@link Builder} object. 484 */ 485 public static Builder create() { 486 return new Builder(); 487 } 488 489 private static Var toVar(BeanStore bs, Object o) { 490 if (o instanceof Class<?> o2) { 491 var subType = (Class<? extends Var>) o2; 492 return BeanInstantiator.of(Var.class, bs).type(subType).run(); 493 } 494 return (Var)o; 495 } 496 497 /** Default maximum depth for re-resolving a var's output. */ 498 public static final int DEFAULT_MAX_RECURSION_DEPTH = 32; 499 500 /** Default maximum number of elements in an expression-built collection. */ 501 public static final int DEFAULT_MAX_COLLECTION_SIZE = 1000; 502 503 /** Default maximum expression nesting depth accepted by the parser. */ 504 public static final int DEFAULT_MAX_EXPR_DEPTH = 32; 505 506 final int maxRecursionDepth; 507 final boolean strict; 508 final int maxCollectionSize; 509 final int maxExprDepth; 510 final Function<Object,String> valueFormatter; // effective 511 final Function<Object,String> customValueFormatter; // as set on the builder; null = default 512 final Var[] vars; 513 private final Map<String,Var> varMap; 514 515 final VarFunction[] functions; // after allowlist filtering 516 final VarFunction[] allFunctions; // before allowlist filtering (used by copy()) 517 final List<String> allowedFunctions; // null = allow all 518 private final Map<String,VarFunction> functionMap; 519 private final Set<String> deniedNames; 520 521 final WritableBeanStore beanStore; 522 523 /** 524 * Constructor. 525 * 526 * @param builder The builder for this object. 527 */ 528 @SuppressWarnings({ 529 "rawtypes" // Same reason — Builder.bean(Class<T>, T) ensures Class/value pairing 530 }) 531 protected VarResolver(Builder builder) { 532 this.maxRecursionDepth = builder.maxRecursionDepth; 533 this.strict = builder.strict; 534 this.maxCollectionSize = builder.maxCollectionSize; 535 this.maxExprDepth = builder.maxExprDepth; 536 this.customValueFormatter = builder.valueFormatter; 537 this.valueFormatter = builder.valueFormatter != null ? builder.valueFormatter : new JsonValueFormatter(builder.maxCollectionSize, builder.strict); 538 this.vars = builder.vars.stream().map(x -> toVar(builder.beanStore(), x)).toArray(Var[]::new); 539 540 var m = new ConcurrentSkipListMap<String,Var>(); 541 for (var v : vars) 542 m.put(v.getName(), v); 543 544 this.varMap = u(m); 545 this.allFunctions = builder.functions.toArray(new VarFunction[0]); 546 this.allowedFunctions = builder.allowedFunctions == null ? null : u(new ArrayList<>(builder.allowedFunctions)); 547 548 var fm = new ConcurrentSkipListMap<String,VarFunction>(); 549 var denied = new TreeSet<String>(); 550 for (var f : allFunctions) { 551 if (isAllowed(f.name())) { 552 fm.put(f.name(), f); 553 denied.remove(f.name()); 554 } else { 555 fm.remove(f.name()); 556 denied.add(f.name()); 557 } 558 } 559 this.functions = fm.values().toArray(new VarFunction[0]); 560 this.functionMap = u(fm); 561 this.deniedNames = u(denied); 562 563 var bs = new BasicBeanStore(builder.beanStore()); 564 builder.userBeans.forEach((c, v) -> bs.addBean((Class) c, v)); 565 this.beanStore = bs; 566 } 567 568 /** 569 * Adds a bean to this session. 570 * 571 * @param <T> The bean type. 572 * @param c The bean type. 573 * @param value The bean. 574 * @return This object . 575 */ 576 public <T> VarResolver addBean(Class<T> c, T value) { 577 beanStore.addBean(c, value); 578 return this; 579 } 580 581 /** 582 * Returns a new builder object using the settings in this resolver as a base. 583 * 584 * @return A new var resolver builder. 585 */ 586 public Builder copy() { 587 return new Builder(this); 588 } 589 590 /** 591 * Creates a new resolver session with no session objects. 592 * 593 * @return A new resolver session. 594 */ 595 public VarResolverSession createSession() { 596 return new VarResolverSession(this, null); 597 } 598 599 /** 600 * Same as {@link #createSession()} except allows you to specify a bean store for resolving beans. 601 * 602 * @param beanStore The bean store to associate with this session. May be {@code null}. 603 * @return A new resolver session. 604 */ 605 public VarResolverSession createSession(WritableBeanStore beanStore) { 606 return new VarResolverSession(this, beanStore); 607 } 608 609 /** 610 * Resolve variables in the specified string. 611 * 612 * <p> 613 * This is a shortcut for calling <code>createSession(<jk>null</jk>).resolve(s);</code>. 614 * <br>This method can only be used if the string doesn't contain variables that rely on the existence of session 615 * variables. 616 * 617 * @param s The input string. May be {@code null}. 618 * @return The string with variables resolved, or the same string if it doesn't contain any variables to resolve. Returns {@code null} if the input was {@code null}. 619 */ 620 public String resolve(String s) { 621 return createSession(null).resolve(s); 622 } 623 624 /** 625 * Compiles a template string into a reusable {@link VarTemplate}. 626 * 627 * <p> 628 * Compilation is the dual of {@link #resolve(String)} — instead of tokenizing and resolving 629 * in one pass, the input is parsed once and the result returned as an immutable 630 * {@link VarTemplate} that callers can reuse across many resolutions: 631 * 632 * <p class='bjava'> 633 * <jc>// Compile once...</jc> 634 * <jk>var</jk> <jv>tpl</jv> = <jv>vr</jv>.compile(<js>"hello, ${name:world}"</js>); 635 * 636 * <jc>// ...resolve many times.</jc> 637 * <jk>for</jk> (<jk>var</jk> <jv>req</jv> : <jv>requests</jv>) { 638 * <jk>var</jk> <jv>session</jv> = <jv>vr</jv>.createSession().bean(<jv>req</jv>); 639 * <jv>writer</jv>.write(<jv>tpl</jv>.resolve(<jv>session</jv>)); 640 * } 641 * </p> 642 * 643 * <p> 644 * The returned {@link VarTemplate} is immutable and threadsafe; the {@link VarResolverSession} 645 * passed to {@link VarTemplate#resolve(VarResolverSession)} inherits its own threadsafety 646 * contract (sessions are <b>not</b> threadsafe). Use {@link #resolveSupplier(String)} or 647 * {@link VarTemplate#asSupplierWithFreshSessions(VarResolver)} for a threadsafe re-evaluating 648 * Supplier. 649 * 650 * <h4 class='section'>Compile-binding contract:</h4> 651 * <p> 652 * The compiled template is bound to <i>this</i> resolver. Cached {@link Var} (and, in the 653 * future, function) references are resolved at compile time. Passing the compiled template 654 * to a session belonging to a different {@link VarResolver} is undefined behavior. 655 * Rebuilding the resolver invalidates compiled templates from the previous instance. 656 * 657 * <p> 658 * Templates are <b>not</b> cached on the resolver. Callers that compile the same input 659 * repeatedly (e.g. framework consumers compiling per {@code @Value} field) should cache 660 * the returned {@link VarTemplate} on their own per-site metadata. 661 * 662 * @param input The template string to compile. May be {@code null}. 663 * @return A new {@link VarTemplate} bound to this resolver. 664 */ 665 public VarTemplate compile(String input) { 666 return VarTemplateCompiler.compile(this, input); 667 } 668 669 /** 670 * Returns a threadsafe {@link Supplier} that resolves the given template against this 671 * resolver each time {@link Supplier#get()} is called. 672 * 673 * <p> 674 * Each call to {@link Supplier#get()} opens a fresh {@link VarResolverSession}, so the 675 * returned {@code Supplier} is safe to share across threads — making it the recommended 676 * default for user-facing code (e.g. {@code @Value Supplier<String>} field types, 677 * hot-reload config patterns). 678 * 679 * <p> 680 * Equivalent to {@code compile(input).asSupplierWithFreshSessions(this)}. 681 * 682 * <p> 683 * For a session-bound (and therefore <i>not</i> threadsafe) variant, see 684 * {@link VarResolverSession#resolveSupplier(String)}. 685 * 686 * @param input The template string. May be {@code null}. 687 * @return A threadsafe {@code Supplier<String>}. 688 */ 689 public Supplier<String> resolveSupplier(String input) { 690 return compile(input).asSupplierWithFreshSessions(this); 691 } 692 693 /** 694 * Resolve variables in the specified string and sends the results to the specified writer. 695 * 696 * <p> 697 * This is a shortcut for calling <code>createSession(<jk>null</jk>).resolveTo(s, w);</code>. 698 * <br>This method can only be used if the string doesn't contain variables that rely on the existence of session 699 * variables. 700 * 701 * @param s The input string. May be {@code null}, in which case the writer is left unchanged. 702 * @param w The writer to send the result to. Must not be {@code null}. 703 * @throws IOException Thrown by underlying stream. 704 */ 705 public void resolveTo(String s, Writer w) throws IOException { 706 createSession(null).resolveTo(s, w); 707 } 708 709 /** 710 * Returns an unmodifiable map of {@link Var Vars} associated with this context. 711 * 712 * @return A map whose keys are var names (e.g. <js>"S"</js>) and values are {@link Var} instances. 713 */ 714 protected Map<String,Var> getVarMap() { return varMap; } 715 716 /** 717 * Returns an array of variables define in this variable resolver context. 718 * 719 * @return A new array containing the variables in this context. 720 */ 721 protected Var[] getVars() { return Arrays.copyOf(vars, vars.length); } 722 723 /** 724 * Returns an unmodifiable map of {@link VarFunction VarFunctions} associated with this context. 725 * 726 * @return A map whose keys are function names (e.g. <js>"upper"</js>) and values are 727 * {@link VarFunction} instances. 728 */ 729 protected Map<String,VarFunction> getFunctionMap() { return functionMap; } 730 731 /** 732 * Looks up a registered function by exact name. 733 * 734 * @param name The function name (e.g. <js>"upper"</js> or <js>"$op.add"</js>). 735 * @return The function, or <jk>null</jk> if no function with that name is registered. 736 */ 737 VarFunction findFunction(String name) { return functionMap.get(name); } 738 739 /** 740 * Returns <jk>true</jk> if a function with this name is registered but excluded by the 741 * {@link Builder#allowFunctions(String...) allowlist}. 742 * 743 * @param name The function name. 744 * @return <jk>true</jk> if the function was registered and denied. 745 */ 746 boolean isDenied(String name) { return deniedNames.contains(name); } 747 748 /** 749 * Returns <jk>true</jk> if the allowlist (if any) permits the given function name. 750 * 751 * <p> 752 * Also applies to names with no registered function, so an operator can be reported as denied even when its 753 * function is not registered. 754 * 755 * @param name The function name. 756 * @return <jk>true</jk> if permitted. 757 */ 758 boolean isAllowed(String name) { 759 if (allowedFunctions == null) 760 return true; 761 for (var pat : allowedFunctions) 762 if (globMatches(pat, name)) 763 return true; 764 return false; 765 } 766 767 private static boolean globMatches(String pattern, String name) { 768 if (pattern.indexOf('*') < 0) 769 return pattern.equals(name); 770 var parts = pattern.split("\\*", -1); 771 var pos = 0; 772 if (! name.startsWith(parts[0])) 773 return false; 774 pos = parts[0].length(); 775 for (var i = 1; i < parts.length - 1; i++) { 776 var idx = name.indexOf(parts[i], pos); 777 if (idx < 0) 778 return false; 779 pos = idx + parts[i].length(); 780 } 781 var last = parts[parts.length - 1]; 782 return name.length() - pos >= last.length() && name.endsWith(last); 783 } 784}