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.commons.text; 018 019import java.util.ArrayList; 020import java.util.Enumeration; 021import java.util.HashMap; 022import java.util.List; 023import java.util.Map; 024import java.util.Objects; 025import java.util.Properties; 026 027import org.apache.commons.lang3.Validate; 028import org.apache.commons.text.lookup.StringLookup; 029import org.apache.commons.text.lookup.StringLookupFactory; 030import org.apache.commons.text.matcher.StringMatcher; 031import org.apache.commons.text.matcher.StringMatcherFactory; 032 033/** 034 * Substitutes variables within a string by values. 035 * <p> 036 * This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is 037 * {@code ${variableName}}. The prefix and suffix can be changed via constructors and set methods. 038 * </p> 039 * <p> 040 * Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying 041 * a custom variable resolver. 042 * </p> 043 * <h2>Using System Properties</h2> 044 * <p> 045 * The simplest example is to use this class to replace Java System properties. For example: 046 * </p> 047 * 048 * <pre> 049 * StringSubstitutor 050 * .replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}."); 051 * </pre> 052 * 053 * <h2>Using a Custom Map</h2> 054 * <p> 055 * Typical usage of this class follows the following pattern: 056 * </p> 057 * <ul> 058 * <li>Create and initialize a StringSubstitutor with the map that contains the values for the variables you want to 059 * make available.</li> 060 * <li>Optionally set attributes like variable prefix, variable suffix, default value delimiter, and so on.</li> 061 * <li>Call the {@code replace()} method with in the source text for interpolation.</li> 062 * <li>The returned text contains all variable references (as long as their values are known) as resolved.</li> 063 * </ul> 064 * <p> 065 * For example: 066 * </p> 067 * 068 * <pre> 069 * // Build map 070 * Map<String, String> valuesMap = new HashMap<>(); 071 * valuesMap.put("animal", "quick brown fox"); 072 * valuesMap.put("target", "lazy dog"); 073 * String templateString = "The ${animal} jumped over the ${target}."; 074 * 075 * // Build StringSubstitutor 076 * StringSubstitutor sub = new StringSubstitutor(valuesMap); 077 * 078 * // Replace 079 * String resolvedString = sub.replace(templateString); 080 * </pre> 081 * 082 * <p> 083 * yielding: 084 * </p> 085 * 086 * <pre> 087 * "The quick brown fox jumped over the lazy dog." 088 * </pre> 089 * 090 * <h2>Providing Default Values</h2> 091 * <p> 092 * You can set a default value for unresolved variables. The default value for a variable can be appended to the 093 * variable name after the variable default value delimiter. The default value of the variable default value delimiter 094 * is ":-", as in bash and other *nix shells. 095 * </p> 096 * <p> 097 * You can set the variable value delimiter with {@link #setValueDelimiterMatcher(StringMatcher)}, 098 * {@link #setValueDelimiter(char)} or {@link #setValueDelimiter(String)}. 099 * </p> 100 * <p> 101 * For example: 102 * </p> 103 * 104 * <pre> 105 * // Build map 106 * Map<String, String> valuesMap = new HashMap<>(); 107 * valuesMap.put("animal", "quick brown fox"); 108 * valuesMap.put("target", "lazy dog"); 109 * String templateString = "The ${animal} jumped over the ${target} ${undefined.number:-1234567890} times."; 110 * 111 * // Build StringSubstitutor 112 * StringSubstitutor sub = new StringSubstitutor(valuesMap); 113 * 114 * // Replace 115 * String resolvedString = sub.replace(templateString); 116 * </pre> 117 * 118 * <p> 119 * yielding: 120 * </p> 121 * 122 * <pre> 123 * "The quick brown fox jumped over the lazy dog 1234567890 times." 124 * </pre> 125 * 126 * <p> 127 * {@code StringSubstitutor} supports throwing exceptions for unresolved variables, you enable this by setting calling 128 * {@link #setEnableUndefinedVariableException(boolean)} with {@code true}. 129 * </p> 130 * 131 * <h2>Reusing Instances</h2> 132 * <p> 133 * Static shortcut methods cover the most common use cases. If multiple replace operations are to be performed, creating 134 * and reusing an instance of this class will be more efficient. 135 * </p> 136 * 137 * <h2>Using Interpolation</h2> 138 * <p> 139 * The default interpolator lets you use string lookups like: 140 * </p> 141 * 142 * <pre> 143 * final StringSubstitutor interpolator = StringSubstitutor.createInterpolator(); 144 * final String text = interpolator.replace( 145 * "Base64 Decoder: ${base64Decoder:SGVsbG9Xb3JsZCE=}\n" 146 * + "Base64 Encoder: ${base64Encoder:HelloWorld!}\n" 147 * + "Java Constant: ${const:java.awt.event.KeyEvent.VK_ESCAPE}\n" 148 * + "Date: ${date:yyyy-MM-dd}\n" 149 * + "Environment Variable: ${env:USERNAME}\n" 150 * + "File Content: ${file:UTF-8:src/test/resources/document.properties}\n" 151 * + "Java: ${java:version}\n" 152 * + "Localhost: ${localhost:canonical-name}\n" 153 * + "Properties File: ${properties:src/test/resources/document.properties::mykey}\n" 154 * + "Resource Bundle: ${resourceBundle:org.apache.commons.text.example.testResourceBundleLookup:mykey}\n" 155 * + "System Property: ${sys:user.dir}\n" 156 * + "URL Decoder: ${urlDecoder:Hello%20World%21}\n" 157 * + "URL Encoder: ${urlEncoder:Hello World!}\n" 158 * + "XML XPath: ${xml:src/test/resources/document.xml:/root/path/to/node}\n"); 159 * </pre> 160 * <p> 161 * For documentation and a full list of available lookups, see {@link StringLookupFactory}. 162 * </p> 163 * <p><strong>NOTE:</strong> The list of lookups available by default in {@link #createInterpolator()} changed 164 * in version {@code 1.10.0}. See the {@link StringLookupFactory} documentation for details and an explanation 165 * on how to reproduce the previous functionality. 166 * </p> 167 * 168 * <h2>Using Recursive Variable Replacement</h2> 169 * <p> 170 * Variable replacement can work recursively by calling {@link #setEnableSubstitutionInVariables(boolean)} with 171 * {@code true}. If a variable value contains a variable then that variable will also be replaced. Cyclic replacements 172 * are detected and will throw an exception. 173 * </p> 174 * <p> 175 * You can get the replace result to contain a variable prefix. For example: 176 * </p> 177 * 178 * <pre> 179 * "The variable ${${name}} must be used." 180 * </pre> 181 * 182 * <p> 183 * If the value of the "name" variable is "x", then only the variable "name" is replaced resulting in: 184 * </p> 185 * 186 * <pre> 187 * "The variable ${x} must be used." 188 * </pre> 189 * 190 * <p> 191 * To achieve this effect there are two possibilities: Either set a different prefix and suffix for variables which do 192 * not conflict with the result text you want to produce. The other possibility is to use the escape character, by 193 * default '$'. If this character is placed before a variable reference, this reference is ignored and won't be 194 * replaced. For example: 195 * </p> 196 * 197 * <pre> 198 * "The variable $${${name}} must be used." 199 * </pre> 200 * <p> 201 * In some complex scenarios you might even want to perform substitution in the names of variables, for instance 202 * </p> 203 * 204 * <pre> 205 * ${jre-${java.specification.version}} 206 * </pre> 207 * 208 * <p> 209 * {@code StringSubstitutor} supports this recursive substitution in variable names, but it has to be enabled explicitly 210 * by calling {@link #setEnableSubstitutionInVariables(boolean)} with {@code true}. 211 * </p> 212 * 213 * <h2>Thread Safety</h2> 214 * <p> 215 * This class is <b>not</b> thread safe. 216 * </p> 217 * 218 * @since 1.3 219 */ 220public class StringSubstitutor { 221 222 /** 223 * The low-level result of a substitution. 224 * 225 * @since 1.9 226 */ 227 private static final class Result { 228 229 /** Whether the buffer is altered. */ 230 public final boolean altered; 231 232 /** The length of change. */ 233 public final int lengthChange; 234 235 private Result(final boolean altered, final int lengthChange) { 236 this.altered = altered; 237 this.lengthChange = lengthChange; 238 } 239 240 @Override 241 public String toString() { 242 return "Result [altered=" + altered + ", lengthChange=" + lengthChange + "]"; 243 } 244 } 245 246 /** 247 * Constant for the default escape character. 248 */ 249 public static final char DEFAULT_ESCAPE = '$'; 250 251 /** 252 * The default variable default separator. 253 * 254 * @since 1.5. 255 */ 256 public static final String DEFAULT_VAR_DEFAULT = ":-"; 257 258 /** 259 * The default variable end separator. 260 * 261 * @since 1.5. 262 */ 263 public static final String DEFAULT_VAR_END = "}"; 264 265 /** 266 * The default variable start separator. 267 * 268 * @since 1.5. 269 */ 270 public static final String DEFAULT_VAR_START = "${"; 271 272 /** 273 * Constant for the default variable prefix. 274 */ 275 public static final StringMatcher DEFAULT_PREFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_START); 276 277 /** 278 * Constant for the default variable suffix. 279 */ 280 public static final StringMatcher DEFAULT_SUFFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_END); 281 282 /** 283 * Constant for the default value delimiter of a variable. 284 */ 285 public static final StringMatcher DEFAULT_VALUE_DELIMITER = StringMatcherFactory.INSTANCE 286 .stringMatcher(DEFAULT_VAR_DEFAULT); 287 288 /** 289 * Creates a new instance using the interpolator string lookup 290 * {@link StringLookupFactory#interpolatorStringLookup()}. 291 * <p> 292 * This StringSubstitutor lets you perform substitutions like: 293 * </p> 294 * 295 * <pre> 296 * StringSubstitutor.createInterpolator().replace( 297 * "OS name: ${sys:os.name}, user: ${env:USER}"); 298 * </pre> 299 * 300 * <p>The table below lists the lookups available by default in the returned instance. These 301 * may be modified through the use of the {@value StringLookupFactory#DEFAULT_STRING_LOOKUPS_PROPERTY} 302 * system property, as described in the {@link StringLookupFactory} documentation.</p> 303 * 304 * <p><strong>NOTE:</strong> The list of lookups available by default changed in version {@code 1.10.0}. 305 * Configuration via system property (as mentioned above) may be necessary to reproduce previous functionality. 306 * </p> 307 * 308 * <table> 309 * <caption>Default Lookups</caption> 310 * <tr> 311 * <th>Key</th> 312 * <th>Lookup</th> 313 * </tr> 314 * <tr> 315 * <td>{@value StringLookupFactory#KEY_BASE64_DECODER}</td> 316 * <td>{@link StringLookupFactory#base64DecoderStringLookup()}</td> 317 * </tr> 318 * <tr> 319 * <td>{@value StringLookupFactory#KEY_BASE64_ENCODER}</td> 320 * <td>{@link StringLookupFactory#base64EncoderStringLookup()}</td> 321 * </tr> 322 * <tr> 323 * <td>{@value StringLookupFactory#KEY_CONST}</td> 324 * <td>{@link StringLookupFactory#constantStringLookup()}</td> 325 * </tr> 326 * <tr> 327 * <td>{@value StringLookupFactory#KEY_DATE}</td> 328 * <td>{@link StringLookupFactory#dateStringLookup()}</td> 329 * </tr> 330 * <tr> 331 * <td>{@value StringLookupFactory#KEY_ENV}</td> 332 * <td>{@link StringLookupFactory#environmentVariableStringLookup()}</td> 333 * </tr> 334 * <tr> 335 * <td>{@value StringLookupFactory#KEY_FILE}</td> 336 * <td>{@link StringLookupFactory#fileStringLookup()}</td> 337 * </tr> 338 * <tr> 339 * <td>{@value StringLookupFactory#KEY_JAVA}</td> 340 * <td>{@link StringLookupFactory#javaPlatformStringLookup()}</td> 341 * </tr> 342 * <tr> 343 * <td>{@value StringLookupFactory#KEY_LOCALHOST}</td> 344 * <td>{@link StringLookupFactory#localHostStringLookup()}</td> 345 * </tr> 346 * <tr> 347 * <td>{@value StringLookupFactory#KEY_PROPERTIES}</td> 348 * <td>{@link StringLookupFactory#propertiesStringLookup()}</td> 349 * </tr> 350 * <tr> 351 * <td>{@value StringLookupFactory#KEY_RESOURCE_BUNDLE}</td> 352 * <td>{@link StringLookupFactory#resourceBundleStringLookup()}</td> 353 * </tr> 354 * <tr> 355 * <td>{@value StringLookupFactory#KEY_SYS}</td> 356 * <td>{@link StringLookupFactory#systemPropertyStringLookup()}</td> 357 * </tr> 358 * <tr> 359 * <td>{@value StringLookupFactory#KEY_URL_DECODER}</td> 360 * <td>{@link StringLookupFactory#urlDecoderStringLookup()}</td> 361 * </tr> 362 * <tr> 363 * <td>{@value StringLookupFactory#KEY_URL_ENCODER}</td> 364 * <td>{@link StringLookupFactory#urlEncoderStringLookup()}</td> 365 * </tr> 366 * <tr> 367 * <td>{@value StringLookupFactory#KEY_XML}</td> 368 * <td>{@link StringLookupFactory#xmlStringLookup()}</td> 369 * </tr> 370 * </table> 371 * 372 * @return a new instance using the interpolator string lookup. 373 * @see StringLookupFactory#interpolatorStringLookup() 374 * @since 1.8 375 */ 376 public static StringSubstitutor createInterpolator() { 377 return new StringSubstitutor(StringLookupFactory.INSTANCE.interpolatorStringLookup()); 378 } 379 380 /** 381 * Replaces all the occurrences of variables in the given source object with their matching values from the map. 382 * 383 * @param <V> the type of the values in the map 384 * @param source the source text containing the variables to substitute, null returns null 385 * @param valueMap the map with the values, may be null 386 * @return The result of the replace operation 387 * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true 388 */ 389 public static <V> String replace(final Object source, final Map<String, V> valueMap) { 390 return new StringSubstitutor(valueMap).replace(source); 391 } 392 393 /** 394 * Replaces all the occurrences of variables in the given source object with their matching values from the map. 395 * This method allows to specify a custom variable prefix and suffix 396 * 397 * @param <V> the type of the values in the map 398 * @param source the source text containing the variables to substitute, null returns null 399 * @param valueMap the map with the values, may be null 400 * @param prefix the prefix of variables, not null 401 * @param suffix the suffix of variables, not null 402 * @return The result of the replace operation 403 * @throws IllegalArgumentException if the prefix or suffix is null 404 * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true 405 */ 406 public static <V> String replace(final Object source, final Map<String, V> valueMap, final String prefix, 407 final String suffix) { 408 return new StringSubstitutor(valueMap, prefix, suffix).replace(source); 409 } 410 411 /** 412 * Replaces all the occurrences of variables in the given source object with their matching values from the 413 * properties. 414 * 415 * @param source the source text containing the variables to substitute, null returns null 416 * @param valueProperties the properties with values, may be null 417 * @return The result of the replace operation 418 * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true 419 */ 420 public static String replace(final Object source, final Properties valueProperties) { 421 if (valueProperties == null) { 422 return source.toString(); 423 } 424 final Map<String, String> valueMap = new HashMap<>(); 425 final Enumeration<?> propNames = valueProperties.propertyNames(); 426 while (propNames.hasMoreElements()) { 427 final String propName = String.valueOf(propNames.nextElement()); 428 final String propValue = valueProperties.getProperty(propName); 429 valueMap.put(propName, propValue); 430 } 431 return StringSubstitutor.replace(source, valueMap); 432 } 433 434 /** 435 * Replaces all the occurrences of variables in the given source object with their matching values from the system 436 * properties. 437 * 438 * @param source the source text containing the variables to substitute, null returns null 439 * @return The result of the replace operation 440 * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true 441 */ 442 public static String replaceSystemProperties(final Object source) { 443 return new StringSubstitutor(StringLookupFactory.INSTANCE.systemPropertyStringLookup()).replace(source); 444 } 445 446 /** 447 * The flag whether substitution in variable values is disabled. 448 */ 449 private boolean disableSubstitutionInValues; 450 451 /** 452 * The flag whether substitution in variable names is enabled. 453 */ 454 private boolean enableSubstitutionInVariables; 455 456 /** 457 * The flag whether exception should be thrown on undefined variable. 458 */ 459 private boolean enableUndefinedVariableException; 460 461 /** 462 * Stores the escape character. 463 */ 464 private char escapeChar; 465 466 /** 467 * Stores the variable prefix. 468 */ 469 private StringMatcher prefixMatcher; 470 471 /** 472 * Whether escapes should be preserved. Default is false; 473 */ 474 private boolean preserveEscapes; 475 476 /** 477 * Stores the variable suffix. 478 */ 479 private StringMatcher suffixMatcher; 480 481 /** 482 * Stores the default variable value delimiter. 483 */ 484 private StringMatcher valueDelimiterMatcher; 485 486 /** 487 * Variable resolution is delegated to an implementor of {@link StringLookup}. 488 */ 489 private StringLookup variableResolver; 490 491 /** 492 * Creates a new instance with defaults for variable prefix and suffix and the escaping character. 493 */ 494 public StringSubstitutor() { 495 this((StringLookup) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); 496 } 497 498 /** 499 * Creates a new instance and initializes it. Uses defaults for variable prefix and suffix and the escaping 500 * character. 501 * 502 * @param <V> the type of the values in the map 503 * @param valueMap the map with the variables' values, may be null 504 */ 505 public <V> StringSubstitutor(final Map<String, V> valueMap) { 506 this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); 507 } 508 509 /** 510 * Creates a new instance and initializes it. Uses a default escaping character. 511 * 512 * @param <V> the type of the values in the map 513 * @param valueMap the map with the variables' values, may be null 514 * @param prefix the prefix for variables, not null 515 * @param suffix the suffix for variables, not null 516 * @throws IllegalArgumentException if the prefix or suffix is null 517 */ 518 public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) { 519 this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE); 520 } 521 522 /** 523 * Creates a new instance and initializes it. 524 * 525 * @param <V> the type of the values in the map 526 * @param valueMap the map with the variables' values, may be null 527 * @param prefix the prefix for variables, not null 528 * @param suffix the suffix for variables, not null 529 * @param escape the escape character 530 * @throws IllegalArgumentException if the prefix or suffix is null 531 */ 532 public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix, 533 final char escape) { 534 this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape); 535 } 536 537 /** 538 * Creates a new instance and initializes it. 539 * 540 * @param <V> the type of the values in the map 541 * @param valueMap the map with the variables' values, may be null 542 * @param prefix the prefix for variables, not null 543 * @param suffix the suffix for variables, not null 544 * @param escape the escape character 545 * @param valueDelimiter the variable default value delimiter, may be null 546 * @throws IllegalArgumentException if the prefix or suffix is null 547 */ 548 public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix, 549 final char escape, final String valueDelimiter) { 550 this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape, valueDelimiter); 551 } 552 553 /** 554 * Creates a new instance and initializes it. 555 * 556 * @param variableResolver the variable resolver, may be null 557 */ 558 public StringSubstitutor(final StringLookup variableResolver) { 559 this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE); 560 } 561 562 /** 563 * Creates a new instance and initializes it. 564 * 565 * @param variableResolver the variable resolver, may be null 566 * @param prefix the prefix for variables, not null 567 * @param suffix the suffix for variables, not null 568 * @param escape the escape character 569 * @throws IllegalArgumentException if the prefix or suffix is null 570 */ 571 public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix, 572 final char escape) { 573 this.setVariableResolver(variableResolver); 574 this.setVariablePrefix(prefix); 575 this.setVariableSuffix(suffix); 576 this.setEscapeChar(escape); 577 this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER); 578 } 579 580 /** 581 * Creates a new instance and initializes it. 582 * 583 * @param variableResolver the variable resolver, may be null 584 * @param prefix the prefix for variables, not null 585 * @param suffix the suffix for variables, not null 586 * @param escape the escape character 587 * @param valueDelimiter the variable default value delimiter string, may be null 588 * @throws IllegalArgumentException if the prefix or suffix is null 589 */ 590 public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix, 591 final char escape, final String valueDelimiter) { 592 this.setVariableResolver(variableResolver); 593 this.setVariablePrefix(prefix); 594 this.setVariableSuffix(suffix); 595 this.setEscapeChar(escape); 596 this.setValueDelimiter(valueDelimiter); 597 } 598 599 /** 600 * Creates a new instance and initializes it. 601 * 602 * @param variableResolver the variable resolver, may be null 603 * @param prefixMatcher the prefix for variables, not null 604 * @param suffixMatcher the suffix for variables, not null 605 * @param escape the escape character 606 * @throws IllegalArgumentException if the prefix or suffix is null 607 */ 608 public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher, 609 final StringMatcher suffixMatcher, final char escape) { 610 this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER); 611 } 612 613 /** 614 * Creates a new instance and initializes it. 615 * 616 * @param variableResolver the variable resolver, may be null 617 * @param prefixMatcher the prefix for variables, not null 618 * @param suffixMatcher the suffix for variables, not null 619 * @param escape the escape character 620 * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null 621 * @throws IllegalArgumentException if the prefix or suffix is null 622 */ 623 public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher, 624 final StringMatcher suffixMatcher, final char escape, final StringMatcher valueDelimiterMatcher) { 625 this.setVariableResolver(variableResolver); 626 this.setVariablePrefixMatcher(prefixMatcher); 627 this.setVariableSuffixMatcher(suffixMatcher); 628 this.setEscapeChar(escape); 629 this.setValueDelimiterMatcher(valueDelimiterMatcher); 630 } 631 632 /** 633 * Creates a new instance based on the given StringSubstitutor. 634 * 635 * @param other The StringSubstitutor used as the source. 636 * @since 1.9 637 */ 638 public StringSubstitutor(final StringSubstitutor other) { 639 disableSubstitutionInValues = other.isDisableSubstitutionInValues(); 640 enableSubstitutionInVariables = other.isEnableSubstitutionInVariables(); 641 enableUndefinedVariableException = other.isEnableUndefinedVariableException(); 642 escapeChar = other.getEscapeChar(); 643 prefixMatcher = other.getVariablePrefixMatcher(); 644 preserveEscapes = other.isPreserveEscapes(); 645 suffixMatcher = other.getVariableSuffixMatcher(); 646 valueDelimiterMatcher = other.getValueDelimiterMatcher(); 647 variableResolver = other.getStringLookup(); 648 } 649 650 /** 651 * Checks if the specified variable is already in the stack (list) of variables. 652 * 653 * @param varName the variable name to check 654 * @param priorVariables the list of prior variables 655 */ 656 private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) { 657 if (!priorVariables.contains(varName)) { 658 return; 659 } 660 final TextStringBuilder buf = new TextStringBuilder(256); 661 buf.append("Infinite loop in property interpolation of "); 662 buf.append(priorVariables.remove(0)); 663 buf.append(": "); 664 buf.appendWithSeparators(priorVariables, "->"); 665 throw new IllegalStateException(buf.toString()); 666 } 667 668 // Escape 669 /** 670 * Returns the escape character. 671 * 672 * @return The character used for escaping variable references 673 */ 674 public char getEscapeChar() { 675 return this.escapeChar; 676 } 677 678 /** 679 * Gets the StringLookup that is used to lookup variables. 680 * 681 * @return The StringLookup 682 */ 683 public StringLookup getStringLookup() { 684 return this.variableResolver; 685 } 686 687 /** 688 * Gets the variable default value delimiter matcher currently in use. 689 * <p> 690 * The variable default value delimiter is the character or characters that delimit the variable name and the 691 * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default 692 * value delimiter matches. 693 * </p> 694 * <p> 695 * If it returns null, then the variable default value resolution is disabled. 696 * 697 * @return The variable default value delimiter matcher in use, may be null 698 */ 699 public StringMatcher getValueDelimiterMatcher() { 700 return valueDelimiterMatcher; 701 } 702 703 /** 704 * Gets the variable prefix matcher currently in use. 705 * <p> 706 * The variable prefix is the character or characters that identify the start of a variable. This prefix is 707 * expressed in terms of a matcher allowing advanced prefix matches. 708 * </p> 709 * 710 * @return The prefix matcher in use 711 */ 712 public StringMatcher getVariablePrefixMatcher() { 713 return prefixMatcher; 714 } 715 716 /** 717 * Gets the variable suffix matcher currently in use. 718 * <p> 719 * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed 720 * in terms of a matcher allowing advanced suffix matches. 721 * </p> 722 * 723 * @return The suffix matcher in use 724 */ 725 public StringMatcher getVariableSuffixMatcher() { 726 return suffixMatcher; 727 } 728 729 /** 730 * Returns a flag whether substitution is disabled in variable values.If set to <b>true</b>, the values of variables 731 * can contain other variables will not be processed and substituted original variable is evaluated, e.g. 732 * 733 * <pre> 734 * Map<String, String> valuesMap = new HashMap<>(); 735 * valuesMap.put("name", "Douglas ${surname}"); 736 * valuesMap.put("surname", "Crockford"); 737 * String templateString = "Hi ${name}"; 738 * StrSubstitutor sub = new StrSubstitutor(valuesMap); 739 * String resolvedString = sub.replace(templateString); 740 * </pre> 741 * 742 * yielding: 743 * 744 * <pre> 745 * Hi Douglas ${surname} 746 * </pre> 747 * 748 * @return The substitution in variable values flag 749 */ 750 public boolean isDisableSubstitutionInValues() { 751 return disableSubstitutionInValues; 752 } 753 754 /** 755 * Returns a flag whether substitution is done in variable names. 756 * 757 * @return The substitution in variable names flag 758 */ 759 public boolean isEnableSubstitutionInVariables() { 760 return enableSubstitutionInVariables; 761 } 762 763 /** 764 * Returns a flag whether exception can be thrown upon undefined variable. 765 * 766 * @return The fail on undefined variable flag 767 */ 768 public boolean isEnableUndefinedVariableException() { 769 return enableUndefinedVariableException; 770 } 771 772 /** 773 * Returns the flag controlling whether escapes are preserved during substitution. 774 * 775 * @return The preserve escape flag 776 */ 777 public boolean isPreserveEscapes() { 778 return preserveEscapes; 779 } 780 781 /** 782 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 783 * array as a template. The array is not altered by this method. 784 * 785 * @param source the character array to replace in, not altered, null returns null 786 * @return The result of the replace operation 787 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 788 */ 789 public String replace(final char[] source) { 790 if (source == null) { 791 return null; 792 } 793 final TextStringBuilder buf = new TextStringBuilder(source.length).append(source); 794 substitute(buf, 0, source.length); 795 return buf.toString(); 796 } 797 798 /** 799 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 800 * array as a template. The array is not altered by this method. 801 * <p> 802 * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not 803 * returned. 804 * </p> 805 * 806 * @param source the character array to replace in, not altered, null returns null 807 * @param offset the start offset within the array, must be valid 808 * @param length the length within the array to be processed, must be valid 809 * @return The result of the replace operation 810 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 811 * @throws StringIndexOutOfBoundsException if {@code offset} is not in the 812 * range {@code 0 <= offset <= chars.length} 813 * @throws StringIndexOutOfBoundsException if {@code length < 0} 814 * @throws StringIndexOutOfBoundsException if {@code offset + length > chars.length} 815 */ 816 public String replace(final char[] source, final int offset, final int length) { 817 if (source == null) { 818 return null; 819 } 820 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 821 substitute(buf, 0, length); 822 return buf.toString(); 823 } 824 825 /** 826 * Replaces all the occurrences of variables with their matching values from the resolver using the given source as 827 * a template. The source is not altered by this method. 828 * 829 * @param source the buffer to use as a template, not changed, null returns null 830 * @return The result of the replace operation 831 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 832 */ 833 public String replace(final CharSequence source) { 834 if (source == null) { 835 return null; 836 } 837 return replace(source, 0, source.length()); 838 } 839 840 /** 841 * Replaces all the occurrences of variables with their matching values from the resolver using the given source as 842 * a template. The source is not altered by this method. 843 * <p> 844 * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not 845 * returned. 846 * </p> 847 * 848 * @param source the buffer to use as a template, not changed, null returns null 849 * @param offset the start offset within the array, must be valid 850 * @param length the length within the array to be processed, must be valid 851 * @return The result of the replace operation 852 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 853 */ 854 public String replace(final CharSequence source, final int offset, final int length) { 855 if (source == null) { 856 return null; 857 } 858 final TextStringBuilder buf = new TextStringBuilder(length).append(source.toString(), offset, length); 859 substitute(buf, 0, length); 860 return buf.toString(); 861 } 862 863 /** 864 * Replaces all the occurrences of variables in the given source object with their matching values from the 865 * resolver. The input source object is converted to a string using {@code toString} and is not altered. 866 * 867 * @param source the source to replace in, null returns null 868 * @return The result of the replace operation 869 * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true 870 */ 871 public String replace(final Object source) { 872 if (source == null) { 873 return null; 874 } 875 final TextStringBuilder buf = new TextStringBuilder().append(source); 876 substitute(buf, 0, buf.length()); 877 return buf.toString(); 878 } 879 880 /** 881 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 882 * string as a template. 883 * 884 * @param source the string to replace in, null returns null 885 * @return The result of the replace operation 886 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 887 */ 888 public String replace(final String source) { 889 if (source == null) { 890 return null; 891 } 892 final TextStringBuilder buf = new TextStringBuilder(source); 893 if (!substitute(buf, 0, source.length())) { 894 return source; 895 } 896 return buf.toString(); 897 } 898 899 /** 900 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 901 * string as a template. 902 * <p> 903 * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not 904 * returned. 905 * </p> 906 * 907 * @param source the string to replace in, null returns null 908 * @param offset the start offset within the source, must be valid 909 * @param length the length within the source to be processed, must be valid 910 * @return The result of the replace operation 911 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 912 * @throws StringIndexOutOfBoundsException if {@code offset} is not in the 913 * range {@code 0 <= offset <= source.length()} 914 * @throws StringIndexOutOfBoundsException if {@code length < 0} 915 * @throws StringIndexOutOfBoundsException if {@code offset + length > source.length()} 916 */ 917 public String replace(final String source, final int offset, final int length) { 918 if (source == null) { 919 return null; 920 } 921 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 922 if (!substitute(buf, 0, length)) { 923 return source.substring(offset, offset + length); 924 } 925 return buf.toString(); 926 } 927 928 /** 929 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 930 * buffer as a template. The buffer is not altered by this method. 931 * 932 * @param source the buffer to use as a template, not changed, null returns null 933 * @return The result of the replace operation 934 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 935 */ 936 public String replace(final StringBuffer source) { 937 if (source == null) { 938 return null; 939 } 940 final TextStringBuilder buf = new TextStringBuilder(source.length()).append(source); 941 substitute(buf, 0, buf.length()); 942 return buf.toString(); 943 } 944 945 /** 946 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 947 * buffer as a template. The buffer is not altered by this method. 948 * <p> 949 * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not 950 * returned. 951 * </p> 952 * 953 * @param source the buffer to use as a template, not changed, null returns null 954 * @param offset the start offset within the source, must be valid 955 * @param length the length within the source to be processed, must be valid 956 * @return The result of the replace operation 957 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 958 */ 959 public String replace(final StringBuffer source, final int offset, final int length) { 960 if (source == null) { 961 return null; 962 } 963 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 964 substitute(buf, 0, length); 965 return buf.toString(); 966 } 967 968 /** 969 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 970 * builder as a template. The builder is not altered by this method. 971 * 972 * @param source the builder to use as a template, not changed, null returns null 973 * @return The result of the replace operation 974 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 975 */ 976 public String replace(final TextStringBuilder source) { 977 if (source == null) { 978 return null; 979 } 980 final TextStringBuilder builder = new TextStringBuilder(source.length()).append(source); 981 substitute(builder, 0, builder.length()); 982 return builder.toString(); 983 } 984 985 /** 986 * Replaces all the occurrences of variables with their matching values from the resolver using the given source 987 * builder as a template. The builder is not altered by this method. 988 * <p> 989 * Only the specified portion of the builder will be processed. The rest of the builder is not processed, and is not 990 * returned. 991 * </p> 992 * 993 * @param source the builder to use as a template, not changed, null returns null 994 * @param offset the start offset within the source, must be valid 995 * @param length the length within the source to be processed, must be valid 996 * @return The result of the replace operation 997 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 998 */ 999 public String replace(final TextStringBuilder source, final int offset, final int length) { 1000 if (source == null) { 1001 return null; 1002 } 1003 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 1004 substitute(buf, 0, length); 1005 return buf.toString(); 1006 } 1007 1008 /** 1009 * Replaces all the occurrences of variables within the given source buffer with their matching values from the 1010 * resolver. The buffer is updated with the result. 1011 * 1012 * @param source the buffer to replace in, updated, null returns zero 1013 * @return true if altered 1014 */ 1015 public boolean replaceIn(final StringBuffer source) { 1016 if (source == null) { 1017 return false; 1018 } 1019 return replaceIn(source, 0, source.length()); 1020 } 1021 1022 /** 1023 * Replaces all the occurrences of variables within the given source buffer with their matching values from the 1024 * resolver. The buffer is updated with the result. 1025 * <p> 1026 * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is 1027 * not deleted. 1028 * </p> 1029 * 1030 * @param source the buffer to replace in, updated, null returns zero 1031 * @param offset the start offset within the source, must be valid 1032 * @param length the length within the source to be processed, must be valid 1033 * @return true if altered 1034 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 1035 */ 1036 public boolean replaceIn(final StringBuffer source, final int offset, final int length) { 1037 if (source == null) { 1038 return false; 1039 } 1040 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 1041 if (!substitute(buf, 0, length)) { 1042 return false; 1043 } 1044 source.replace(offset, offset + length, buf.toString()); 1045 return true; 1046 } 1047 1048 /** 1049 * Replaces all the occurrences of variables within the given source buffer with their matching values from the 1050 * resolver. The buffer is updated with the result. 1051 * 1052 * @param source the buffer to replace in, updated, null returns zero 1053 * @return true if altered 1054 */ 1055 public boolean replaceIn(final StringBuilder source) { 1056 if (source == null) { 1057 return false; 1058 } 1059 return replaceIn(source, 0, source.length()); 1060 } 1061 1062 /** 1063 * Replaces all the occurrences of variables within the given source builder with their matching values from the 1064 * resolver. The builder is updated with the result. 1065 * <p> 1066 * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is 1067 * not deleted. 1068 * </p> 1069 * 1070 * @param source the buffer to replace in, updated, null returns zero 1071 * @param offset the start offset within the source, must be valid 1072 * @param length the length within the source to be processed, must be valid 1073 * @return true if altered 1074 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 1075 */ 1076 public boolean replaceIn(final StringBuilder source, final int offset, final int length) { 1077 if (source == null) { 1078 return false; 1079 } 1080 final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length); 1081 if (!substitute(buf, 0, length)) { 1082 return false; 1083 } 1084 source.replace(offset, offset + length, buf.toString()); 1085 return true; 1086 } 1087 1088 /** 1089 * Replaces all the occurrences of variables within the given source builder with their matching values from the 1090 * resolver. 1091 * 1092 * @param source the builder to replace in, updated, null returns zero 1093 * @return true if altered 1094 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 1095 */ 1096 public boolean replaceIn(final TextStringBuilder source) { 1097 if (source == null) { 1098 return false; 1099 } 1100 return substitute(source, 0, source.length()); 1101 } 1102 1103 /** 1104 * Replaces all the occurrences of variables within the given source builder with their matching values from the 1105 * resolver. 1106 * <p> 1107 * Only the specified portion of the builder will be processed. The rest of the builder is not processed, but it is 1108 * not deleted. 1109 * </p> 1110 * 1111 * @param source the builder to replace in, null returns zero 1112 * @param offset the start offset within the source, must be valid 1113 * @param length the length within the source to be processed, must be valid 1114 * @return true if altered 1115 * @throws IllegalArgumentException if variable is not found when its allowed to throw exception 1116 */ 1117 public boolean replaceIn(final TextStringBuilder source, final int offset, final int length) { 1118 if (source == null) { 1119 return false; 1120 } 1121 return substitute(source, offset, length); 1122 } 1123 1124 /** 1125 * Internal method that resolves the value of a variable. 1126 * <p> 1127 * Most users of this class do not need to call this method. This method is called automatically by the substitution 1128 * process. 1129 * </p> 1130 * <p> 1131 * Writers of subclasses can override this method if they need to alter how each substitution occurs. The method is 1132 * passed the variable's name and must return the corresponding value. This implementation uses the 1133 * {@link #getStringLookup()} with the variable's name as the key. 1134 * </p> 1135 * 1136 * @param variableName the name of the variable, not null 1137 * @param buf the buffer where the substitution is occurring, not null 1138 * @param startPos the start position of the variable including the prefix, valid 1139 * @param endPos the end position of the variable including the suffix, valid 1140 * @return The variable's value or <b>null</b> if the variable is unknown 1141 */ 1142 protected String resolveVariable(final String variableName, final TextStringBuilder buf, final int startPos, 1143 final int endPos) { 1144 final StringLookup resolver = getStringLookup(); 1145 if (resolver == null) { 1146 return null; 1147 } 1148 return resolver.lookup(variableName); 1149 } 1150 1151 /** 1152 * Sets a flag whether substitution is done in variable values (recursive). 1153 * 1154 * @param disableSubstitutionInValues true if substitution in variable value are disabled 1155 * @return this, to enable chaining 1156 */ 1157 public StringSubstitutor setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) { 1158 this.disableSubstitutionInValues = disableSubstitutionInValues; 1159 return this; 1160 } 1161 1162 /** 1163 * Sets a flag whether substitution is done in variable names. If set to <b>true</b>, the names of variables can 1164 * contain other variables which are processed first before the original variable is evaluated, e.g. 1165 * {@code ${jre-${java.version}}}. The default value is <b>false</b>. 1166 * 1167 * @param enableSubstitutionInVariables the new value of the flag 1168 * @return this, to enable chaining 1169 */ 1170 public StringSubstitutor setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) { 1171 this.enableSubstitutionInVariables = enableSubstitutionInVariables; 1172 return this; 1173 } 1174 1175 /** 1176 * Sets a flag whether exception should be thrown if any variable is undefined. 1177 * 1178 * @param failOnUndefinedVariable true if exception should be thrown on undefined variable 1179 * @return this, to enable chaining 1180 */ 1181 public StringSubstitutor setEnableUndefinedVariableException(final boolean failOnUndefinedVariable) { 1182 this.enableUndefinedVariableException = failOnUndefinedVariable; 1183 return this; 1184 } 1185 1186 /** 1187 * Sets the escape character. If this character is placed before a variable reference in the source text, this 1188 * variable will be ignored. 1189 * 1190 * @param escapeCharacter the escape character (0 for disabling escaping) 1191 * @return this, to enable chaining 1192 */ 1193 public StringSubstitutor setEscapeChar(final char escapeCharacter) { 1194 this.escapeChar = escapeCharacter; 1195 return this; 1196 } 1197 1198 /** 1199 * Sets a flag controlling whether escapes are preserved during substitution. If set to <b>true</b>, the escape 1200 * character is retained during substitution (e.g. {@code $${this-is-escaped}} remains {@code $${this-is-escaped}}). 1201 * If set to <b>false</b>, the escape character is removed during substitution (e.g. {@code $${this-is-escaped}} 1202 * becomes {@code ${this-is-escaped}}). The default value is <b>false</b> 1203 * 1204 * @param preserveEscapes true if escapes are to be preserved 1205 * @return this, to enable chaining 1206 */ 1207 public StringSubstitutor setPreserveEscapes(final boolean preserveEscapes) { 1208 this.preserveEscapes = preserveEscapes; 1209 return this; 1210 } 1211 1212 /** 1213 * Sets the variable default value delimiter to use. 1214 * <p> 1215 * The variable default value delimiter is the character or characters that delimit the variable name and the 1216 * variable default value. This method allows a single character variable default value delimiter to be easily set. 1217 * </p> 1218 * 1219 * @param valueDelimiter the variable default value delimiter character to use 1220 * @return this, to enable chaining 1221 */ 1222 public StringSubstitutor setValueDelimiter(final char valueDelimiter) { 1223 return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(valueDelimiter)); 1224 } 1225 1226 /** 1227 * Sets the variable default value delimiter to use. 1228 * <p> 1229 * The variable default value delimiter is the character or characters that delimit the variable name and the 1230 * variable default value. This method allows a string variable default value delimiter to be easily set. 1231 * </p> 1232 * <p> 1233 * If the {@code valueDelimiter} is null or empty string, then the variable default value resolution becomes 1234 * disabled. 1235 * </p> 1236 * 1237 * @param valueDelimiter the variable default value delimiter string to use, may be null or empty 1238 * @return this, to enable chaining 1239 */ 1240 public StringSubstitutor setValueDelimiter(final String valueDelimiter) { 1241 if (valueDelimiter == null || valueDelimiter.isEmpty()) { 1242 setValueDelimiterMatcher(null); 1243 return this; 1244 } 1245 return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.stringMatcher(valueDelimiter)); 1246 } 1247 1248 /** 1249 * Sets the variable default value delimiter matcher to use. 1250 * <p> 1251 * The variable default value delimiter is the character or characters that delimit the variable name and the 1252 * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default 1253 * value delimiter matches. 1254 * </p> 1255 * <p> 1256 * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution becomes disabled. 1257 * </p> 1258 * 1259 * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null 1260 * @return this, to enable chaining 1261 */ 1262 public StringSubstitutor setValueDelimiterMatcher(final StringMatcher valueDelimiterMatcher) { 1263 this.valueDelimiterMatcher = valueDelimiterMatcher; 1264 return this; 1265 } 1266 1267 /** 1268 * Sets the variable prefix to use. 1269 * <p> 1270 * The variable prefix is the character or characters that identify the start of a variable. This method allows a 1271 * single character prefix to be easily set. 1272 * </p> 1273 * 1274 * @param prefix the prefix character to use 1275 * @return this, to enable chaining 1276 */ 1277 public StringSubstitutor setVariablePrefix(final char prefix) { 1278 return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.charMatcher(prefix)); 1279 } 1280 1281 /** 1282 * Sets the variable prefix to use. 1283 * <p> 1284 * The variable prefix is the character or characters that identify the start of a variable. This method allows a 1285 * string prefix to be easily set. 1286 * </p> 1287 * 1288 * @param prefix the prefix for variables, not null 1289 * @return this, to enable chaining 1290 * @throws IllegalArgumentException if the prefix is null 1291 */ 1292 public StringSubstitutor setVariablePrefix(final String prefix) { 1293 Validate.isTrue(prefix != null, "Variable prefix must not be null!"); 1294 return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(prefix)); 1295 } 1296 1297 /** 1298 * Sets the variable prefix matcher currently in use. 1299 * <p> 1300 * The variable prefix is the character or characters that identify the start of a variable. This prefix is 1301 * expressed in terms of a matcher allowing advanced prefix matches. 1302 * </p> 1303 * 1304 * @param prefixMatcher the prefix matcher to use, null ignored 1305 * @return this, to enable chaining 1306 * @throws IllegalArgumentException if the prefix matcher is null 1307 */ 1308 public StringSubstitutor setVariablePrefixMatcher(final StringMatcher prefixMatcher) { 1309 Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!"); 1310 this.prefixMatcher = prefixMatcher; 1311 return this; 1312 } 1313 1314 /** 1315 * Sets the VariableResolver that is used to lookup variables. 1316 * 1317 * @param variableResolver the VariableResolver 1318 * @return this, to enable chaining 1319 */ 1320 public StringSubstitutor setVariableResolver(final StringLookup variableResolver) { 1321 this.variableResolver = variableResolver; 1322 return this; 1323 } 1324 1325 /** 1326 * Sets the variable suffix to use. 1327 * <p> 1328 * The variable suffix is the character or characters that identify the end of a variable. This method allows a 1329 * single character suffix to be easily set. 1330 * </p> 1331 * 1332 * @param suffix the suffix character to use 1333 * @return this, to enable chaining 1334 */ 1335 public StringSubstitutor setVariableSuffix(final char suffix) { 1336 return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.charMatcher(suffix)); 1337 } 1338 1339 /** 1340 * Sets the variable suffix to use. 1341 * <p> 1342 * The variable suffix is the character or characters that identify the end of a variable. This method allows a 1343 * string suffix to be easily set. 1344 * </p> 1345 * 1346 * @param suffix the suffix for variables, not null 1347 * @return this, to enable chaining 1348 * @throws IllegalArgumentException if the suffix is null 1349 */ 1350 public StringSubstitutor setVariableSuffix(final String suffix) { 1351 Validate.isTrue(suffix != null, "Variable suffix must not be null!"); 1352 return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(suffix)); 1353 } 1354 1355 /** 1356 * Sets the variable suffix matcher currently in use. 1357 * <p> 1358 * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed 1359 * in terms of a matcher allowing advanced suffix matches. 1360 * </p> 1361 * 1362 * @param suffixMatcher the suffix matcher to use, null ignored 1363 * @return this, to enable chaining 1364 * @throws IllegalArgumentException if the suffix matcher is null 1365 */ 1366 public StringSubstitutor setVariableSuffixMatcher(final StringMatcher suffixMatcher) { 1367 Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!"); 1368 this.suffixMatcher = suffixMatcher; 1369 return this; 1370 } 1371 1372 /** 1373 * Internal method that substitutes the variables. 1374 * <p> 1375 * Most users of this class do not need to call this method. This method will be called automatically by another 1376 * (public) method. 1377 * </p> 1378 * <p> 1379 * Writers of subclasses can override this method if they need access to the substitution process at the start or 1380 * end. 1381 * </p> 1382 * 1383 * @param builder the string builder to substitute into, not null 1384 * @param offset the start offset within the builder, must be valid 1385 * @param length the length within the builder to be processed, must be valid 1386 * @return true if altered 1387 */ 1388 protected boolean substitute(final TextStringBuilder builder, final int offset, final int length) { 1389 return substitute(builder, offset, length, null).altered; 1390 } 1391 1392 /** 1393 * Recursive handler for multiple levels of interpolation. This is the main interpolation method, which resolves the 1394 * values of all variable references contained in the passed in text. 1395 * 1396 * @param builder the string builder to substitute into, not null 1397 * @param offset the start offset within the builder, must be valid 1398 * @param length the length within the builder to be processed, must be valid 1399 * @param priorVariables the stack keeping track of the replaced variables, may be null 1400 * @return The result. 1401 * @throws IllegalArgumentException if variable is not found and <pre>isEnableUndefinedVariableException()==true</pre> 1402 * @since 1.9 1403 */ 1404 private Result substitute(final TextStringBuilder builder, final int offset, final int length, 1405 List<String> priorVariables) { 1406 Objects.requireNonNull(builder, "builder"); 1407 final StringMatcher prefixMatcher = getVariablePrefixMatcher(); 1408 final StringMatcher suffixMatcher = getVariableSuffixMatcher(); 1409 final char escapeCh = getEscapeChar(); 1410 final StringMatcher valueDelimMatcher = getValueDelimiterMatcher(); 1411 final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables(); 1412 final boolean substitutionInValuesDisabled = isDisableSubstitutionInValues(); 1413 final boolean undefinedVariableException = isEnableUndefinedVariableException(); 1414 final boolean preserveEscapes = isPreserveEscapes(); 1415 1416 boolean altered = false; 1417 int lengthChange = 0; 1418 int bufEnd = offset + length; 1419 int pos = offset; 1420 int escPos = -1; 1421 outer: while (pos < bufEnd) { 1422 final int startMatchLen = prefixMatcher.isMatch(builder, pos, offset, bufEnd); 1423 if (startMatchLen == 0) { 1424 pos++; 1425 } else { 1426 // found variable start marker 1427 if (pos > offset && builder.charAt(pos - 1) == escapeCh) { 1428 // escape detected 1429 if (preserveEscapes) { 1430 // keep escape 1431 pos++; 1432 continue; 1433 } 1434 // mark esc ch for deletion if we find a complete variable 1435 escPos = pos - 1; 1436 } 1437 // find suffix 1438 int startPos = pos; 1439 pos += startMatchLen; 1440 int endMatchLen = 0; 1441 int nestedVarCount = 0; 1442 while (pos < bufEnd) { 1443 if (substitutionInVariablesEnabled && prefixMatcher.isMatch(builder, pos, offset, bufEnd) != 0) { 1444 // found a nested variable start 1445 endMatchLen = prefixMatcher.isMatch(builder, pos, offset, bufEnd); 1446 nestedVarCount++; 1447 pos += endMatchLen; 1448 continue; 1449 } 1450 1451 endMatchLen = suffixMatcher.isMatch(builder, pos, offset, bufEnd); 1452 if (endMatchLen == 0) { 1453 pos++; 1454 } else { 1455 // found variable end marker 1456 if (nestedVarCount == 0) { 1457 if (escPos >= 0) { 1458 // delete escape 1459 builder.deleteCharAt(escPos); 1460 escPos = -1; 1461 lengthChange--; 1462 altered = true; 1463 bufEnd--; 1464 pos = startPos + 1; 1465 startPos--; 1466 continue outer; 1467 } 1468 // get var name 1469 String varNameExpr = builder.midString(startPos + startMatchLen, 1470 pos - startPos - startMatchLen); 1471 if (substitutionInVariablesEnabled) { 1472 final TextStringBuilder bufName = new TextStringBuilder(varNameExpr); 1473 substitute(bufName, 0, bufName.length()); 1474 varNameExpr = bufName.toString(); 1475 } 1476 pos += endMatchLen; 1477 final int endPos = pos; 1478 1479 String varName = varNameExpr; 1480 String varDefaultValue = null; 1481 1482 if (valueDelimMatcher != null) { 1483 final char[] varNameExprChars = varNameExpr.toCharArray(); 1484 int valueDelimiterMatchLen = 0; 1485 for (int i = 0; i < varNameExprChars.length; i++) { 1486 // if there's any nested variable when nested variable substitution disabled, 1487 // then stop resolving name and default value. 1488 if (!substitutionInVariablesEnabled && prefixMatcher.isMatch(varNameExprChars, i, i, 1489 varNameExprChars.length) != 0) { 1490 break; 1491 } 1492 if (valueDelimMatcher.isMatch(varNameExprChars, i, 0, 1493 varNameExprChars.length) != 0) { 1494 valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i, 0, 1495 varNameExprChars.length); 1496 varName = varNameExpr.substring(0, i); 1497 varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen); 1498 break; 1499 } 1500 } 1501 } 1502 1503 // on the first call initialize priorVariables 1504 if (priorVariables == null) { 1505 priorVariables = new ArrayList<>(); 1506 priorVariables.add(builder.midString(offset, length)); 1507 } 1508 1509 // handle cyclic substitution 1510 checkCyclicSubstitution(varName, priorVariables); 1511 priorVariables.add(varName); 1512 1513 // resolve the variable 1514 String varValue = resolveVariable(varName, builder, startPos, endPos); 1515 if (varValue == null) { 1516 varValue = varDefaultValue; 1517 } 1518 if (varValue != null) { 1519 final int varLen = varValue.length(); 1520 builder.replace(startPos, endPos, varValue); 1521 altered = true; 1522 int change = 0; 1523 if (!substitutionInValuesDisabled) { // recursive replace 1524 change = substitute(builder, startPos, varLen, priorVariables).lengthChange; 1525 } 1526 change = change + varLen - (endPos - startPos); 1527 pos += change; 1528 bufEnd += change; 1529 lengthChange += change; 1530 } else if (undefinedVariableException) { 1531 throw new IllegalArgumentException( 1532 String.format("Cannot resolve variable '%s' (enableSubstitutionInVariables=%s).", 1533 varName, substitutionInVariablesEnabled)); 1534 } 1535 1536 // remove variable from the cyclic stack 1537 priorVariables.remove(priorVariables.size() - 1); 1538 break; 1539 } 1540 nestedVarCount--; 1541 pos += endMatchLen; 1542 } 1543 } 1544 } 1545 } 1546 return new Result(altered, lengthChange); 1547 } 1548}