You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2020/06/22 15:48:09 UTC
[commons-text] branch master updated: Checktyle: Use LF EOL in repo.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-text.git
The following commit(s) were added to refs/heads/master by this push:
new 617780c Checktyle: Use LF EOL in repo.
617780c is described below
commit 617780cbb1249d60d651a9ad07e79eae48eab1c8
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Mon Jun 22 11:48:02 2020 -0400
Checktyle: Use LF EOL in repo.
---
.../java/org/apache/commons/text/StrMatcher.java | 900 +++----
.../org/apache/commons/text/StrSubstitutor.java | 2550 +++++++++---------
.../org/apache/commons/text/StringSubstitutor.java | 2842 ++++++++++----------
.../commons/text/diff/ReplacementsFinder.java | 252 +-
.../commons/text/lookup/DateStringLookup.java | 188 +-
.../lookup/EnvironmentVariableStringLookup.java | 140 +-
.../text/lookup/IllegalArgumentExceptions.java | 122 +-
.../commons/text/lookup/MapStringLookup.java | 196 +-
.../commons/text/lookup/NullStringLookup.java | 94 +-
.../text/lookup/SystemPropertyStringLookup.java | 110 +-
.../text/matcher/AbstractStringMatcher.java | 518 ++--
.../apache/commons/text/matcher/StringMatcher.java | 118 +-
.../commons/text/matcher/StringMatcherFactory.java | 456 ++--
.../apache/commons/text/matcher/package-info.java | 50 +-
.../commons/text/translate/CsvTranslators.java | 188 +-
.../text/translate/NumericEntityUnescaper.java | 276 +-
.../text/translate/SinglePassTranslator.java | 116 +-
17 files changed, 4558 insertions(+), 4558 deletions(-)
diff --git a/src/main/java/org/apache/commons/text/StrMatcher.java b/src/main/java/org/apache/commons/text/StrMatcher.java
index 23cfccd..d7a0348 100644
--- a/src/main/java/org/apache/commons/text/StrMatcher.java
+++ b/src/main/java/org/apache/commons/text/StrMatcher.java
@@ -1,450 +1,450 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text;
-
-import java.util.Arrays;
-
-import org.apache.commons.text.matcher.StringMatcherFactory;
-
-/**
- * A matcher class that can be queried to determine if a character array
- * portion matches.
- * <p>
- * This class comes complete with various factory methods.
- * If these do not suffice, you can subclass and implement your own matcher.
- *
- * @since 1.0
- * @deprecated Deprecated as of 1.3, use {@link StringMatcherFactory} instead. This class will be removed in 2.0.
- */
-@Deprecated
-public abstract class StrMatcher {
-
- /**
- * Matches the comma character.
- */
- private static final StrMatcher COMMA_MATCHER = new CharMatcher(',');
-
- /**
- * Matches the tab character.
- */
- private static final StrMatcher TAB_MATCHER = new CharMatcher('\t');
-
- /**
- * Matches the space character.
- */
- private static final StrMatcher SPACE_MATCHER = new CharMatcher(' ');
-
- /**
- * Matches the same characters as StringTokenizer,
- * namely space, tab, newline, form feed.
- */
- private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray());
-
- /**
- * Matches the String trim() whitespace characters.
- */
- private static final StrMatcher TRIM_MATCHER = new TrimMatcher();
-
- /**
- * Matches the double quote character.
- */
- private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\'');
-
- /**
- * Matches the double quote character.
- */
- private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"');
-
- /**
- * Matches the single or double quote character.
- */
- private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray());
-
- /**
- * Matches no characters.
- */
- private static final StrMatcher NONE_MATCHER = new NoMatcher();
-
- // -----------------------------------------------------------------------
-
- /**
- * Returns a matcher which matches the comma character.
- *
- * @return a matcher for a comma
- */
- public static StrMatcher commaMatcher() {
- return COMMA_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the tab character.
- *
- * @return a matcher for a tab
- */
- public static StrMatcher tabMatcher() {
- return TAB_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the space character.
- *
- * @return a matcher for a space
- */
- public static StrMatcher spaceMatcher() {
- return SPACE_MATCHER;
- }
-
- /**
- * Matches the same characters as StringTokenizer,
- * namely space, tab, newline and form feed.
- *
- * @return The split matcher
- */
- public static StrMatcher splitMatcher() {
- return SPLIT_MATCHER;
- }
-
- /**
- * Matches the String trim() whitespace characters.
- *
- * @return The trim matcher
- */
- public static StrMatcher trimMatcher() {
- return TRIM_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the single quote character.
- *
- * @return a matcher for a single quote
- */
- public static StrMatcher singleQuoteMatcher() {
- return SINGLE_QUOTE_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the double quote character.
- *
- * @return a matcher for a double quote
- */
- public static StrMatcher doubleQuoteMatcher() {
- return DOUBLE_QUOTE_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the single or double quote character.
- *
- * @return a matcher for a single or double quote
- */
- public static StrMatcher quoteMatcher() {
- return QUOTE_MATCHER;
- }
-
- /**
- * Matches no characters.
- *
- * @return a matcher that matches nothing
- */
- public static StrMatcher noneMatcher() {
- return NONE_MATCHER;
- }
-
- /**
- * Creates a matcher from a character.
- *
- * @param ch the character to match, must not be null
- * @return a new Matcher for the given char
- */
- public static StrMatcher charMatcher(final char ch) {
- return new CharMatcher(ch);
- }
-
- /**
- * Creates a matcher from a set of characters.
- *
- * @param chars the characters to match, null or empty matches nothing
- * @return a new matcher for the given char[]
- */
- public static StrMatcher charSetMatcher(final char... chars) {
- if (chars == null || chars.length == 0) {
- return NONE_MATCHER;
- }
- if (chars.length == 1) {
- return new CharMatcher(chars[0]);
- }
- return new CharSetMatcher(chars);
- }
-
- /**
- * Creates a matcher from a string representing a set of characters.
- *
- * @param chars the characters to match, null or empty matches nothing
- * @return a new Matcher for the given characters
- */
- public static StrMatcher charSetMatcher(final String chars) {
- if (chars == null || chars.length() == 0) {
- return NONE_MATCHER;
- }
- if (chars.length() == 1) {
- return new CharMatcher(chars.charAt(0));
- }
- return new CharSetMatcher(chars.toCharArray());
- }
-
- /**
- * Creates a matcher from a string.
- *
- * @param str the string to match, null or empty matches nothing
- * @return a new Matcher for the given String
- */
- public static StrMatcher stringMatcher(final String str) {
- if (str == null || str.length() == 0) {
- return NONE_MATCHER;
- }
- return new StringMatcher(str);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Constructor.
- */
- protected StrMatcher() {
- super();
- }
-
- /**
- * Returns the number of matching characters, or zero if there is no match.
- * <p>
- * This method is called to check for a match.
- * The parameter {@code pos} represents the current position to be
- * checked in the string {@code buffer} (a character array which must
- * not be changed).
- * The API guarantees that {@code pos} is a valid index for {@code buffer}.
- * <p>
- * The character array may be larger than the active area to be matched.
- * Only values in the buffer between the specified indices may be accessed.
- * <p>
- * The matching code may check one character or many.
- * It may check characters preceding {@code pos} as well as those
- * after, so long as no checks exceed the bounds specified.
- * <p>
- * It must return zero for no match, or a positive number if a match was found.
- * The number indicates the number of characters that matched.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
-
- /**
- * Returns the number of matching characters, or zero if there is no match.
- * <p>
- * This method is called to check for a match.
- * The parameter {@code pos} represents the current position to be
- * checked in the string {@code buffer} (a character array which must
- * not be changed).
- * The API guarantees that {@code pos} is a valid index for {@code buffer}.
- * <p>
- * The matching code may check one character or many.
- * It may check characters preceding {@code pos} as well as those after.
- * <p>
- * It must return zero for no match, or a positive number if a match was found.
- * The number indicates the number of characters that matched.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- public int isMatch(final char[] buffer, final int pos) {
- return isMatch(buffer, pos, 0, buffer.length);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Class used to define a set of characters for matching purposes.
- */
- static final class CharSetMatcher extends StrMatcher {
- /** The set of characters to match. */
- private final char[] chars;
-
- /**
- * Constructor that creates a matcher from a character array.
- *
- * @param chars the characters to match, must not be null
- */
- CharSetMatcher(final char[] chars) {
- super();
- this.chars = chars.clone();
- Arrays.sort(this.chars);
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- @Override
- public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
- return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Class used to define a character for matching purposes.
- */
- static final class CharMatcher extends StrMatcher {
- /** The character to match. */
- private final char ch;
-
- /**
- * Constructor that creates a matcher that matches a single character.
- *
- * @param ch the character to match
- */
- CharMatcher(final char ch) {
- super();
- this.ch = ch;
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- @Override
- public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
- return ch == buffer[pos] ? 1 : 0;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Class used to define a set of characters for matching purposes.
- */
- static final class StringMatcher extends StrMatcher {
- /** The string to match, as a character array. */
- private final char[] chars;
-
- /**
- * Constructor that creates a matcher from a String.
- *
- * @param str the string to match, must not be null
- */
- StringMatcher(final String str) {
- super();
- chars = str.toCharArray();
- }
-
- /**
- * Returns whether or not the given text matches the stored string.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- @Override
- public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
- final int len = chars.length;
- if (pos + len > bufferEnd) {
- return 0;
- }
- for (int i = 0; i < chars.length; i++, pos++) {
- if (chars[i] != buffer[pos]) {
- return 0;
- }
- }
- return len;
- }
-
- @Override
- public String toString() {
- return super.toString() + ' ' + Arrays.toString(chars);
- }
-
- }
-
- //-----------------------------------------------------------------------
- /**
- * Class used to match no characters.
- */
- static final class NoMatcher extends StrMatcher {
-
- /**
- * Constructs a new instance of {@code NoMatcher}.
- */
- NoMatcher() {
- super();
- }
-
- /**
- * Always returns {@code false}.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- @Override
- public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
- return 0;
- }
- }
-
- //-----------------------------------------------------------------------
- /**
- * Class used to match whitespace as per trim().
- */
- static final class TrimMatcher extends StrMatcher {
-
- /**
- * Constructs a new instance of {@code TrimMatcher}.
- */
- TrimMatcher() {
- super();
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer the text content to match against, do not change
- * @param pos the starting position for the match, valid for buffer
- * @param bufferStart the first active index in the buffer, valid for buffer
- * @param bufferEnd the end index of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- @Override
- public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
- return buffer[pos] <= 32 ? 1 : 0;
- }
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text;
+
+import java.util.Arrays;
+
+import org.apache.commons.text.matcher.StringMatcherFactory;
+
+/**
+ * A matcher class that can be queried to determine if a character array
+ * portion matches.
+ * <p>
+ * This class comes complete with various factory methods.
+ * If these do not suffice, you can subclass and implement your own matcher.
+ *
+ * @since 1.0
+ * @deprecated Deprecated as of 1.3, use {@link StringMatcherFactory} instead. This class will be removed in 2.0.
+ */
+@Deprecated
+public abstract class StrMatcher {
+
+ /**
+ * Matches the comma character.
+ */
+ private static final StrMatcher COMMA_MATCHER = new CharMatcher(',');
+
+ /**
+ * Matches the tab character.
+ */
+ private static final StrMatcher TAB_MATCHER = new CharMatcher('\t');
+
+ /**
+ * Matches the space character.
+ */
+ private static final StrMatcher SPACE_MATCHER = new CharMatcher(' ');
+
+ /**
+ * Matches the same characters as StringTokenizer,
+ * namely space, tab, newline, form feed.
+ */
+ private static final StrMatcher SPLIT_MATCHER = new CharSetMatcher(" \t\n\r\f".toCharArray());
+
+ /**
+ * Matches the String trim() whitespace characters.
+ */
+ private static final StrMatcher TRIM_MATCHER = new TrimMatcher();
+
+ /**
+ * Matches the double quote character.
+ */
+ private static final StrMatcher SINGLE_QUOTE_MATCHER = new CharMatcher('\'');
+
+ /**
+ * Matches the double quote character.
+ */
+ private static final StrMatcher DOUBLE_QUOTE_MATCHER = new CharMatcher('"');
+
+ /**
+ * Matches the single or double quote character.
+ */
+ private static final StrMatcher QUOTE_MATCHER = new CharSetMatcher("'\"".toCharArray());
+
+ /**
+ * Matches no characters.
+ */
+ private static final StrMatcher NONE_MATCHER = new NoMatcher();
+
+ // -----------------------------------------------------------------------
+
+ /**
+ * Returns a matcher which matches the comma character.
+ *
+ * @return a matcher for a comma
+ */
+ public static StrMatcher commaMatcher() {
+ return COMMA_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the tab character.
+ *
+ * @return a matcher for a tab
+ */
+ public static StrMatcher tabMatcher() {
+ return TAB_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the space character.
+ *
+ * @return a matcher for a space
+ */
+ public static StrMatcher spaceMatcher() {
+ return SPACE_MATCHER;
+ }
+
+ /**
+ * Matches the same characters as StringTokenizer,
+ * namely space, tab, newline and form feed.
+ *
+ * @return The split matcher
+ */
+ public static StrMatcher splitMatcher() {
+ return SPLIT_MATCHER;
+ }
+
+ /**
+ * Matches the String trim() whitespace characters.
+ *
+ * @return The trim matcher
+ */
+ public static StrMatcher trimMatcher() {
+ return TRIM_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the single quote character.
+ *
+ * @return a matcher for a single quote
+ */
+ public static StrMatcher singleQuoteMatcher() {
+ return SINGLE_QUOTE_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the double quote character.
+ *
+ * @return a matcher for a double quote
+ */
+ public static StrMatcher doubleQuoteMatcher() {
+ return DOUBLE_QUOTE_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the single or double quote character.
+ *
+ * @return a matcher for a single or double quote
+ */
+ public static StrMatcher quoteMatcher() {
+ return QUOTE_MATCHER;
+ }
+
+ /**
+ * Matches no characters.
+ *
+ * @return a matcher that matches nothing
+ */
+ public static StrMatcher noneMatcher() {
+ return NONE_MATCHER;
+ }
+
+ /**
+ * Creates a matcher from a character.
+ *
+ * @param ch the character to match, must not be null
+ * @return a new Matcher for the given char
+ */
+ public static StrMatcher charMatcher(final char ch) {
+ return new CharMatcher(ch);
+ }
+
+ /**
+ * Creates a matcher from a set of characters.
+ *
+ * @param chars the characters to match, null or empty matches nothing
+ * @return a new matcher for the given char[]
+ */
+ public static StrMatcher charSetMatcher(final char... chars) {
+ if (chars == null || chars.length == 0) {
+ return NONE_MATCHER;
+ }
+ if (chars.length == 1) {
+ return new CharMatcher(chars[0]);
+ }
+ return new CharSetMatcher(chars);
+ }
+
+ /**
+ * Creates a matcher from a string representing a set of characters.
+ *
+ * @param chars the characters to match, null or empty matches nothing
+ * @return a new Matcher for the given characters
+ */
+ public static StrMatcher charSetMatcher(final String chars) {
+ if (chars == null || chars.length() == 0) {
+ return NONE_MATCHER;
+ }
+ if (chars.length() == 1) {
+ return new CharMatcher(chars.charAt(0));
+ }
+ return new CharSetMatcher(chars.toCharArray());
+ }
+
+ /**
+ * Creates a matcher from a string.
+ *
+ * @param str the string to match, null or empty matches nothing
+ * @return a new Matcher for the given String
+ */
+ public static StrMatcher stringMatcher(final String str) {
+ if (str == null || str.length() == 0) {
+ return NONE_MATCHER;
+ }
+ return new StringMatcher(str);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Constructor.
+ */
+ protected StrMatcher() {
+ super();
+ }
+
+ /**
+ * Returns the number of matching characters, or zero if there is no match.
+ * <p>
+ * This method is called to check for a match.
+ * The parameter {@code pos} represents the current position to be
+ * checked in the string {@code buffer} (a character array which must
+ * not be changed).
+ * The API guarantees that {@code pos} is a valid index for {@code buffer}.
+ * <p>
+ * The character array may be larger than the active area to be matched.
+ * Only values in the buffer between the specified indices may be accessed.
+ * <p>
+ * The matching code may check one character or many.
+ * It may check characters preceding {@code pos} as well as those
+ * after, so long as no checks exceed the bounds specified.
+ * <p>
+ * It must return zero for no match, or a positive number if a match was found.
+ * The number indicates the number of characters that matched.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index (exclusive) of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ public abstract int isMatch(char[] buffer, int pos, int bufferStart, int bufferEnd);
+
+ /**
+ * Returns the number of matching characters, or zero if there is no match.
+ * <p>
+ * This method is called to check for a match.
+ * The parameter {@code pos} represents the current position to be
+ * checked in the string {@code buffer} (a character array which must
+ * not be changed).
+ * The API guarantees that {@code pos} is a valid index for {@code buffer}.
+ * <p>
+ * The matching code may check one character or many.
+ * It may check characters preceding {@code pos} as well as those after.
+ * <p>
+ * It must return zero for no match, or a positive number if a match was found.
+ * The number indicates the number of characters that matched.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ public int isMatch(final char[] buffer, final int pos) {
+ return isMatch(buffer, pos, 0, buffer.length);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Class used to define a set of characters for matching purposes.
+ */
+ static final class CharSetMatcher extends StrMatcher {
+ /** The set of characters to match. */
+ private final char[] chars;
+
+ /**
+ * Constructor that creates a matcher from a character array.
+ *
+ * @param chars the characters to match, must not be null
+ */
+ CharSetMatcher(final char[] chars) {
+ super();
+ this.chars = chars.clone();
+ Arrays.sort(this.chars);
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+ return Arrays.binarySearch(chars, buffer[pos]) >= 0 ? 1 : 0;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Class used to define a character for matching purposes.
+ */
+ static final class CharMatcher extends StrMatcher {
+ /** The character to match. */
+ private final char ch;
+
+ /**
+ * Constructor that creates a matcher that matches a single character.
+ *
+ * @param ch the character to match
+ */
+ CharMatcher(final char ch) {
+ super();
+ this.ch = ch;
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+ return ch == buffer[pos] ? 1 : 0;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Class used to define a set of characters for matching purposes.
+ */
+ static final class StringMatcher extends StrMatcher {
+ /** The string to match, as a character array. */
+ private final char[] chars;
+
+ /**
+ * Constructor that creates a matcher from a String.
+ *
+ * @param str the string to match, must not be null
+ */
+ StringMatcher(final String str) {
+ super();
+ chars = str.toCharArray();
+ }
+
+ /**
+ * Returns whether or not the given text matches the stored string.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, int pos, final int bufferStart, final int bufferEnd) {
+ final int len = chars.length;
+ if (pos + len > bufferEnd) {
+ return 0;
+ }
+ for (int i = 0; i < chars.length; i++, pos++) {
+ if (chars[i] != buffer[pos]) {
+ return 0;
+ }
+ }
+ return len;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + ' ' + Arrays.toString(chars);
+ }
+
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Class used to match no characters.
+ */
+ static final class NoMatcher extends StrMatcher {
+
+ /**
+ * Constructs a new instance of {@code NoMatcher}.
+ */
+ NoMatcher() {
+ super();
+ }
+
+ /**
+ * Always returns {@code false}.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+ return 0;
+ }
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Class used to match whitespace as per trim().
+ */
+ static final class TrimMatcher extends StrMatcher {
+
+ /**
+ * Constructs a new instance of {@code TrimMatcher}.
+ */
+ TrimMatcher() {
+ super();
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer the text content to match against, do not change
+ * @param pos the starting position for the match, valid for buffer
+ * @param bufferStart the first active index in the buffer, valid for buffer
+ * @param bufferEnd the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int pos, final int bufferStart, final int bufferEnd) {
+ return buffer[pos] <= 32 ? 1 : 0;
+ }
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/StrSubstitutor.java b/src/main/java/org/apache/commons/text/StrSubstitutor.java
index 9d6f4e0..5216a07 100644
--- a/src/main/java/org/apache/commons/text/StrSubstitutor.java
+++ b/src/main/java/org/apache/commons/text/StrSubstitutor.java
@@ -1,1275 +1,1275 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text;
-
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.lang3.Validate;
-
-/**
- * Substitutes variables within a string by values.
- * <p>
- * This class takes a piece of text and substitutes all the variables within it.
- * The default definition of a variable is {@code ${variableName}}.
- * The prefix and suffix can be changed via constructors and set methods.
- * <p>
- * Variable values are typically resolved from a map, but could also be resolved
- * from system properties, or by supplying a custom variable resolver.
- * <p>
- * The simplest example is to use this class to replace Java System properties. For example:
- * <pre>
- * StrSubstitutor.replaceSystemProperties(
- * "You are running with java.version = ${java.version} and os.name = ${os.name}.");
- * </pre>
- * <p>
- * Typical usage of this class follows the following pattern: First an instance is created
- * and initialized with the map that contains the values for the available variables.
- * If a prefix and/or suffix for variables should be used other than the default ones,
- * the appropriate settings can be performed. After that the {@code replace()}
- * method can be called passing in the source text for interpolation. In the returned
- * text all variable references (as long as their values are known) will be resolved.
- * The following example demonstrates this:
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("animal", "quick brown fox");
- * valuesMap.put("target", "lazy dog");
- * String templateString = "The ${animal} jumped over the ${target}.";
- * StrSubstitutor sub = new StrSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- * yielding:
- * <pre>
- * The quick brown fox jumped over the lazy dog.
- * </pre>
- * <p>
- * Also, this class allows to set a default value for unresolved variables.
- * The default value for a variable can be appended to the variable name after the variable
- * default value delimiter. The default value of the variable default value delimiter is ':-',
- * as in bash and other *nix shells, as those are arguably where the default ${} delimiter set originated.
- * The variable default value delimiter can be manually set by calling {@link #setValueDelimiterMatcher(StrMatcher)},
- * {@link #setValueDelimiter(char)} or {@link #setValueDelimiter(String)}.
- * The following shows an example with variable default value settings:
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("animal", "quick brown fox");
- * valuesMap.put("target", "lazy dog");
- * String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
- * StrSubstitutor sub = new StrSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- * yielding:
- * <pre>
- * The quick brown fox jumped over the lazy dog. 1234567890.
- * </pre>
- * <p>
- * In addition to this usage pattern there are some static convenience methods that
- * cover the most common use cases. These methods can be used without the need of
- * manually creating an instance. However if multiple replace operations are to be
- * performed, creating and reusing an instance of this class will be more efficient.
- * <p>
- * Variable replacement works in a recursive way. Thus, if a variable value contains
- * a variable then that variable will also be replaced. Cyclic replacements are
- * detected and will cause an exception to be thrown.
- * <p>
- * Sometimes the interpolation's result must contain a variable prefix. As an example
- * take the following source text:
- * <pre>
- * The variable ${${name}} must be used.
- * </pre>
- * Here only the variable's name referred to in the text should be replaced resulting
- * in the text (assuming that the value of the {@code name} variable is {@code x}):
- * <pre>
- * The variable ${x} must be used.
- * </pre>
- * To achieve this effect there are two possibilities: Either set a different prefix
- * and suffix for variables which do not conflict with the result text you want to
- * produce. The other possibility is to use the escape character, by default '$'.
- * If this character is placed before a variable reference, this reference is ignored
- * and won't be replaced. For example:
- * <pre>
- * The variable $${${name}} must be used.
- * </pre>
- * <p>
- * In some complex scenarios you might even want to perform substitution in the
- * names of variables, for instance
- * <pre>
- * ${jre-${java.specification.version}}
- * </pre>
- * {@code StrSubstitutor} supports this recursive substitution in variable
- * names, but it has to be enabled explicitly by setting the
- * {@link #setEnableSubstitutionInVariables(boolean) enableSubstitutionInVariables}
- * property to <b>true</b>.
- * <p>This class is <b>not</b> thread safe.</p>
- *
- * @since 1.0
- * @deprecated Deprecated as of 1.3, use {@link StringSubstitutor} instead. This class will be removed in 2.0.
- */
-@Deprecated
-public class StrSubstitutor {
-
- /**
- * Constant for the default escape character.
- */
- public static final char DEFAULT_ESCAPE = '$';
-
- /**
- * Constant for the default variable prefix.
- */
- public static final StrMatcher DEFAULT_PREFIX = StrMatcher.stringMatcher("${");
-
- /**
- * Constant for the default variable suffix.
- */
- public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}");
-
- /**
- * Constant for the default value delimiter of a variable.
- */
- public static final StrMatcher DEFAULT_VALUE_DELIMITER = StrMatcher.stringMatcher(":-");
-
- /**
- * Stores the escape character.
- */
- private char escapeChar;
-
- /**
- * Stores the variable prefix.
- */
- private StrMatcher prefixMatcher;
-
- /**
- * Stores the variable suffix.
- */
- private StrMatcher suffixMatcher;
-
- /**
- * Stores the default variable value delimiter.
- */
- private StrMatcher valueDelimiterMatcher;
-
- /**
- * Variable resolution is delegated to an implementor of VariableResolver.
- */
- private StrLookup<?> variableResolver;
-
- /**
- * The flag whether substitution in variable names is enabled.
- */
- private boolean enableSubstitutionInVariables;
-
- /**
- * Whether escapes should be preserved. Default is false;
- */
- private boolean preserveEscapes = false;
-
- /**
- * The flag whether substitution in variable values is disabled.
- */
- private boolean disableSubstitutionInValues;
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables in the given source object with
- * their matching values from the map.
- *
- * @param <V> the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @return The result of the replace operation
- */
- public static <V> String replace(final Object source, final Map<String, V> valueMap) {
- return new StrSubstitutor(valueMap).replace(source);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with
- * their matching values from the map. This method allows to specify a
- * custom variable prefix and suffix
- *
- * @param <V> the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @param prefix the prefix of variables, not null
- * @param suffix the suffix of variables, not null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public static <V> String replace(final Object source,
- final Map<String, V> valueMap,
- final String prefix,
- final String suffix) {
- return new StrSubstitutor(valueMap, prefix, suffix).replace(source);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with their matching
- * values from the properties.
- *
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueProperties the properties with values, may be null
- * @return The result of the replace operation
- */
- public static String replace(final Object source, final Properties valueProperties) {
- if (valueProperties == null) {
- return source.toString();
- }
- final Map<String, String> valueMap = new HashMap<>();
- final Enumeration<?> propNames = valueProperties.propertyNames();
- while (propNames.hasMoreElements()) {
- final String propName = (String) propNames.nextElement();
- final String propValue = valueProperties.getProperty(propName);
- valueMap.put(propName, propValue);
- }
- return StrSubstitutor.replace(source, valueMap);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with
- * their matching values from the system properties.
- *
- * @param source the source text containing the variables to substitute, null returns null
- * @return The result of the replace operation
- */
- public static String replaceSystemProperties(final Object source) {
- return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Creates a new instance with defaults for variable prefix and suffix
- * and the escaping character.
- */
- public StrSubstitutor() {
- this((StrLookup<?>) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it. Uses defaults for variable
- * prefix and suffix and the escaping character.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- */
- public <V> StrSubstitutor(final Map<String, V> valueMap) {
- this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it. Uses a default escaping character.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) {
- this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
- final char escape) {
- this(StrLookup.mapLookup(valueMap), prefix, suffix, escape);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
- final char escape, final String valueDelimiter) {
- this(StrLookup.mapLookup(valueMap), prefix, suffix, escape, valueDelimiter);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- */
- public StrSubstitutor(final StrLookup<?> variableResolver) {
- this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
- final char escape) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefix(prefix);
- this.setVariableSuffix(suffix);
- this.setEscapeChar(escape);
- this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter string, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
- final char escape, final String valueDelimiter) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefix(prefix);
- this.setVariableSuffix(suffix);
- this.setEscapeChar(escape);
- this.setValueDelimiter(valueDelimiter);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StrSubstitutor(
- final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
- final char escape) {
- this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StrSubstitutor(
- final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
- final char escape, final StrMatcher valueDelimiterMatcher) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefixMatcher(prefixMatcher);
- this.setVariableSuffixMatcher(suffixMatcher);
- this.setEscapeChar(escape);
- this.setValueDelimiterMatcher(valueDelimiterMatcher);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source string as a template.
- *
- * @param source the string to replace in, null returns null
- * @return The result of the replace operation
- */
- public String replace(final String source) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(source);
- if (!substitute(buf, 0, source.length())) {
- return source;
- }
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source string as a template.
- * <p>
- * Only the specified portion of the string will be processed.
- * The rest of the string is not processed, and is not returned.
- *
- * @param source the string to replace in, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- */
- public String replace(final String source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return source.substring(offset, offset + length);
- }
- return buf.toString();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source array as a template.
- * The array is not altered by this method.
- *
- * @param source the character array to replace in, not altered, null returns null
- * @return The result of the replace operation
- */
- public String replace(final char[] source) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(source.length).append(source);
- substitute(buf, 0, source.length);
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source array as a template.
- * The array is not altered by this method.
- * <p>
- * Only the specified portion of the array will be processed.
- * The rest of the array is not processed, and is not returned.
- *
- * @param source the character array to replace in, not altered, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- */
- public String replace(final char[] source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source buffer as a template.
- * The buffer is not altered by this method.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- */
- public String replace(final StringBuffer source) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(source.length()).append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source buffer as a template.
- * The buffer is not altered by this method.
- * <p>
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, and is not returned.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- */
- public String replace(final StringBuffer source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source as a template.
- * The source is not altered by this method.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- */
- public String replace(final CharSequence source) {
- if (source == null) {
- return null;
- }
- return replace(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source as a template.
- * The source is not altered by this method.
- * <p>
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, and is not returned.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- */
- public String replace(final CharSequence source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source builder as a template.
- * The builder is not altered by this method.
- *
- * @param source the builder to use as a template, not changed, null returns null
- * @return The result of the replace operation
- */
- public String replace(final StrBuilder source) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(source.length()).append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values
- * from the resolver using the given source builder as a template.
- * The builder is not altered by this method.
- * <p>
- * Only the specified portion of the builder will be processed.
- * The rest of the builder is not processed, and is not returned.
- *
- * @param source the builder to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- */
- public String replace(final StrBuilder source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables in the given source object with
- * their matching values from the resolver. The input source object is
- * converted to a string using {@code toString} and is not altered.
- *
- * @param source the source to replace in, null returns null
- * @return The result of the replace operation
- */
- public String replace(final Object source) {
- if (source == null) {
- return null;
- }
- final StrBuilder buf = new StrBuilder().append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
- */
- public boolean replaceIn(final StringBuffer source) {
- if (source == null) {
- return false;
- }
- return replaceIn(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
- * <p>
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, but it is not deleted.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the buffer to be processed, must be valid
- * @return true if altered
- */
- public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return false;
- }
- source.replace(offset, offset + length, buf.toString());
- return true;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source buffer
- * with their matching values from the resolver.
- * The buffer is updated with the result.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
- */
- public boolean replaceIn(final StringBuilder source) {
- if (source == null) {
- return false;
- }
- return replaceIn(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source builder
- * with their matching values from the resolver.
- * The builder is updated with the result.
- * <p>
- * Only the specified portion of the buffer will be processed.
- * The rest of the buffer is not processed, but it is not deleted.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the buffer to be processed, must be valid
- * @return true if altered
- */
- public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return false;
- }
- source.replace(offset, offset + length, buf.toString());
- return true;
- }
-
- //-----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source
- * builder with their matching values from the resolver.
- *
- * @param source the builder to replace in, updated, null returns zero
- * @return true if altered
- */
- public boolean replaceIn(final StrBuilder source) {
- if (source == null) {
- return false;
- }
- return substitute(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source
- * builder with their matching values from the resolver.
- * <p>
- * Only the specified portion of the builder will be processed.
- * The rest of the builder is not processed, but it is not deleted.
- *
- * @param source the builder to replace in, null returns zero
- * @param offset the start offset within the array, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
- */
- public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- return substitute(source, offset, length);
- }
-
- //-----------------------------------------------------------------------
- /**
- * Internal method that substitutes the variables.
- * <p>
- * Most users of this class do not need to call this method. This method will
- * be called automatically by another (public) method.
- * <p>
- * Writers of subclasses can override this method if they need access to
- * the substitution process at the start or end.
- *
- * @param buf the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
- */
- protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
- return substitute(buf, offset, length, null) > 0;
- }
-
- /**
- * Recursive handler for multiple levels of interpolation. This is the main
- * interpolation method, which resolves the values of all variable references
- * contained in the passed in text.
- *
- * @param buf the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @param priorVariables the stack keeping track of the replaced variables, may be null
- * @return The length change that occurs, unless priorVariables is null when the int
- * represents a boolean flag as to whether any change occurred.
- */
- private int substitute(final StrBuilder buf, final int offset, final int length, List<String> priorVariables) {
- final StrMatcher pfxMatcher = getVariablePrefixMatcher();
- final StrMatcher suffMatcher = getVariableSuffixMatcher();
- final char escape = getEscapeChar();
- final StrMatcher valueDelimMatcher = getValueDelimiterMatcher();
- final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables();
- final boolean substitutionInValuesDisabled = isDisableSubstitutionInValues();
-
- final boolean top = priorVariables == null;
- boolean altered = false;
- int lengthChange = 0;
- char[] chars = buf.buffer;
- int bufEnd = offset + length;
- int pos = offset;
- while (pos < bufEnd) {
- final int startMatchLen = pfxMatcher.isMatch(chars, pos, offset,
- bufEnd);
- if (startMatchLen == 0) {
- pos++;
- } else {
- // found variable start marker
- if (pos > offset && chars[pos - 1] == escape) {
- // escaped
- if (preserveEscapes) {
- pos++;
- continue;
- }
- buf.deleteCharAt(pos - 1);
- chars = buf.buffer; // in case buffer was altered
- lengthChange--;
- altered = true;
- bufEnd--;
- } else {
- // find suffix
- final int startPos = pos;
- pos += startMatchLen;
- int endMatchLen = 0;
- int nestedVarCount = 0;
- while (pos < bufEnd) {
- if (substitutionInVariablesEnabled
- && pfxMatcher.isMatch(chars,
- pos, offset, bufEnd) != 0) {
- // found a nested variable start
- endMatchLen = pfxMatcher.isMatch(chars,
- pos, offset, bufEnd);
- nestedVarCount++;
- pos += endMatchLen;
- continue;
- }
-
- endMatchLen = suffMatcher.isMatch(chars, pos, offset,
- bufEnd);
- if (endMatchLen == 0) {
- pos++;
- } else {
- // found variable end marker
- if (nestedVarCount == 0) {
- String varNameExpr = new String(chars, startPos
- + startMatchLen, pos - startPos
- - startMatchLen);
- if (substitutionInVariablesEnabled) {
- final StrBuilder bufName = new StrBuilder(varNameExpr);
- substitute(bufName, 0, bufName.length());
- varNameExpr = bufName.toString();
- }
- pos += endMatchLen;
- final int endPos = pos;
-
- String varName = varNameExpr;
- String varDefaultValue = null;
-
- if (valueDelimMatcher != null) {
- final char[] varNameExprChars = varNameExpr.toCharArray();
- int valueDelimiterMatchLen = 0;
- for (int i = 0; i < varNameExprChars.length; i++) {
- // if there's any nested variable when nested variable substitution disabled,
- // then stop resolving name and default value.
- if (!substitutionInVariablesEnabled
- && pfxMatcher.isMatch(varNameExprChars,
- i,
- i,
- varNameExprChars.length) != 0) {
- break;
- }
- if (valueDelimMatcher.isMatch(varNameExprChars, i) != 0) {
- valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i);
- varName = varNameExpr.substring(0, i);
- varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
- break;
- }
- }
- }
-
- // on the first call initialize priorVariables
- if (priorVariables == null) {
- priorVariables = new ArrayList<>();
- priorVariables.add(new String(chars,
- offset, length));
- }
-
- // handle cyclic substitution
- checkCyclicSubstitution(varName, priorVariables);
- priorVariables.add(varName);
-
- // resolve the variable
- String varValue = resolveVariable(varName, buf,
- startPos, endPos);
- if (varValue == null) {
- varValue = varDefaultValue;
- }
- if (varValue != null) {
- final int varLen = varValue.length();
- buf.replace(startPos, endPos, varValue);
- altered = true;
- int change = 0;
- if (!substitutionInValuesDisabled) { // recursive replace
- change = substitute(buf, startPos,
- varLen, priorVariables);
- }
- change = change
- + varLen - (endPos - startPos);
- pos += change;
- bufEnd += change;
- lengthChange += change;
- chars = buf.buffer; // in case buffer was
- // altered
- }
-
- // remove variable from the cyclic stack
- priorVariables
- .remove(priorVariables.size() - 1);
- break;
- }
- nestedVarCount--;
- pos += endMatchLen;
- }
- }
- }
- }
- }
- if (top) {
- return altered ? 1 : 0;
- }
- return lengthChange;
- }
-
- /**
- * Checks if the specified variable is already in the stack (list) of variables.
- *
- * @param varName the variable name to check
- * @param priorVariables the list of prior variables
- */
- private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
- if (!priorVariables.contains(varName)) {
- return;
- }
- final StrBuilder buf = new StrBuilder(256);
- buf.append("Infinite loop in property interpolation of ");
- buf.append(priorVariables.remove(0));
- buf.append(": ");
- buf.appendWithSeparators(priorVariables, "->");
- throw new IllegalStateException(buf.toString());
- }
-
- /**
- * Internal method that resolves the value of a variable.
- * <p>
- * Most users of this class do not need to call this method. This method is
- * called automatically by the substitution process.
- * <p>
- * Writers of subclasses can override this method if they need to alter
- * how each substitution occurs. The method is passed the variable's name
- * and must return the corresponding value. This implementation uses the
- * {@link #getVariableResolver()} with the variable's name as the key.
- *
- * @param variableName the name of the variable, not null
- * @param buf the buffer where the substitution is occurring, not null
- * @param startPos the start position of the variable including the prefix, valid
- * @param endPos the end position of the variable including the suffix, valid
- * @return The variable's value or <b>null</b> if the variable is unknown
- */
- protected String resolveVariable(final String variableName,
- final StrBuilder buf,
- final int startPos,
- final int endPos) {
- final StrLookup<?> resolver = getVariableResolver();
- if (resolver == null) {
- return null;
- }
- return resolver.lookup(variableName);
- }
-
- // Escape
- //-----------------------------------------------------------------------
- /**
- * Returns the escape character.
- *
- * @return The character used for escaping variable references
- */
- public char getEscapeChar() {
- return this.escapeChar;
- }
-
- /**
- * Sets the escape character.
- * If this character is placed before a variable reference in the source
- * text, this variable will be ignored.
- *
- * @param escapeCharacter the escape character (0 for disabling escaping)
- */
- public void setEscapeChar(final char escapeCharacter) {
- this.escapeChar = escapeCharacter;
- }
-
- // Prefix
- //-----------------------------------------------------------------------
- /**
- * Gets the variable prefix matcher currently in use.
- * <p>
- * The variable prefix is the character or characters that identify the
- * start of a variable. This prefix is expressed in terms of a matcher
- * allowing advanced prefix matches.
- *
- * @return The prefix matcher in use
- */
- public StrMatcher getVariablePrefixMatcher() {
- return prefixMatcher;
- }
-
- /**
- * Sets the variable prefix matcher currently in use.
- * <p>
- * The variable prefix is the character or characters that identify the
- * start of a variable. This prefix is expressed in terms of a matcher
- * allowing advanced prefix matches.
- *
- * @param prefixMatcher the prefix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix matcher is null
- */
- public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
- Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
- this.prefixMatcher = prefixMatcher;
- return this;
- }
-
- /**
- * Sets the variable prefix to use.
- * <p>
- * The variable prefix is the character or characters that identify the
- * start of a variable. This method allows a single character prefix to
- * be easily set.
- *
- * @param prefix the prefix character to use
- * @return this, to enable chaining
- */
- public StrSubstitutor setVariablePrefix(final char prefix) {
- return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
- }
-
- /**
- * Sets the variable prefix to use.
- * <p>
- * The variable prefix is the character or characters that identify the
- * start of a variable. This method allows a string prefix to be easily set.
- *
- * @param prefix the prefix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix is null
- */
- public StrSubstitutor setVariablePrefix(final String prefix) {
- Validate.isTrue(prefix != null, "Variable prefix must not be null!");
- return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
- }
-
- // Suffix
- //-----------------------------------------------------------------------
- /**
- * Gets the variable suffix matcher currently in use.
- * <p>
- * The variable suffix is the character or characters that identify the
- * end of a variable. This suffix is expressed in terms of a matcher
- * allowing advanced suffix matches.
- *
- * @return The suffix matcher in use
- */
- public StrMatcher getVariableSuffixMatcher() {
- return suffixMatcher;
- }
-
- /**
- * Sets the variable suffix matcher currently in use.
- * <p>
- * The variable suffix is the character or characters that identify the
- * end of a variable. This suffix is expressed in terms of a matcher
- * allowing advanced suffix matches.
- *
- * @param suffixMatcher the suffix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix matcher is null
- */
- public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
- Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
- this.suffixMatcher = suffixMatcher;
- return this;
- }
-
- /**
- * Sets the variable suffix to use.
- * <p>
- * The variable suffix is the character or characters that identify the
- * end of a variable. This method allows a single character suffix to
- * be easily set.
- *
- * @param suffix the suffix character to use
- * @return this, to enable chaining
- */
- public StrSubstitutor setVariableSuffix(final char suffix) {
- return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
- }
-
- /**
- * Sets the variable suffix to use.
- * <p>
- * The variable suffix is the character or characters that identify the
- * end of a variable. This method allows a string suffix to be easily set.
- *
- * @param suffix the suffix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix is null
- */
- public StrSubstitutor setVariableSuffix(final String suffix) {
- Validate.isTrue(suffix != null, "Variable suffix must not be null!");
- return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
- }
-
- // Variable Default Value Delimiter
- //-----------------------------------------------------------------------
- /**
- * Gets the variable default value delimiter matcher currently in use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the
- * variable name and the variable default value. This delimiter is expressed in terms of a matcher
- * allowing advanced variable default value delimiter matches.
- * <p>
- * If it returns null, then the variable default value resolution is disabled.
- *
- * @return The variable default value delimiter matcher in use, may be null
- */
- public StrMatcher getValueDelimiterMatcher() {
- return valueDelimiterMatcher;
- }
-
- /**
- * Sets the variable default value delimiter matcher to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the
- * variable name and the variable default value. This delimiter is expressed in terms of a matcher
- * allowing advanced variable default value delimiter matches.
- * <p>
- * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution
- * becomes disabled.
- *
- * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
- * @return this, to enable chaining
- */
- public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
- this.valueDelimiterMatcher = valueDelimiterMatcher;
- return this;
- }
-
- /**
- * Sets the variable default value delimiter to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the
- * variable name and the variable default value. This method allows a single character
- * variable default value delimiter to be easily set.
- *
- * @param valueDelimiter the variable default value delimiter character to use
- * @return this, to enable chaining
- */
- public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
- return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
- }
-
- /**
- * Sets the variable default value delimiter to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the
- * variable name and the variable default value. This method allows a string
- * variable default value delimiter to be easily set.
- * <p>
- * If the {@code valueDelimiter} is null or empty string, then the variable default
- * value resolution becomes disabled.
- *
- * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
- * @return this, to enable chaining
- */
- public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
- if (valueDelimiter == null || valueDelimiter.length() == 0) {
- setValueDelimiterMatcher(null);
- return this;
- }
- return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
- }
-
- // Resolver
- //-----------------------------------------------------------------------
- /**
- * Gets the VariableResolver that is used to lookup variables.
- *
- * @return The VariableResolver
- */
- public StrLookup<?> getVariableResolver() {
- return this.variableResolver;
- }
-
- /**
- * Sets the VariableResolver that is used to lookup variables.
- *
- * @param variableResolver the VariableResolver
- */
- public void setVariableResolver(final StrLookup<?> variableResolver) {
- this.variableResolver = variableResolver;
- }
-
- // Substitution support in variable names
- //-----------------------------------------------------------------------
- /**
- * Returns a flag whether substitution is done in variable names.
- *
- * @return The substitution in variable names flag
- */
- public boolean isEnableSubstitutionInVariables() {
- return enableSubstitutionInVariables;
- }
-
- /**
- * Sets a flag whether substitution is done in variable names. If set to
- * <b>true</b>, the names of variables can contain other variables which are
- * processed first before the original variable is evaluated, e.g.
- * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
- *
- * @param enableSubstitutionInVariables the new value of the flag
- */
- public void setEnableSubstitutionInVariables(
- final boolean enableSubstitutionInVariables) {
- this.enableSubstitutionInVariables = enableSubstitutionInVariables;
- }
-
- /**
- * Returns a flag whether substitution is disabled in variable values.If set to
- * <b>true</b>, the values of variables can contain other variables will not be
- * processed and substituted original variable is evaluated, e.g.
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("name", "Douglas ${surname}");
- * valuesMap.put("surname", "Crockford");
- * String templateString = "Hi ${name}";
- * StrSubstitutor sub = new StrSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- * yielding:
- * <pre>
- * Hi Douglas ${surname}
- * </pre>
- *
- * @return The substitution in variable values flag
- *
- * @since 1.2
- */
- public boolean isDisableSubstitutionInValues() {
- return disableSubstitutionInValues;
- }
-
- /**
- * Sets a flag whether substitution is done in variable values (recursive).
- *
- * @param disableSubstitutionInValues true if substitution in variable value are disabled
- *
- * @since 1.2
- */
- public void setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
- this.disableSubstitutionInValues = disableSubstitutionInValues;
- }
-
- /**
- * Returns the flag controlling whether escapes are preserved during
- * substitution.
- *
- * @return The preserve escape flag
- */
- public boolean isPreserveEscapes() {
- return preserveEscapes;
- }
-
- /**
- * Sets a flag controlling whether escapes are preserved during
- * substitution. If set to <b>true</b>, the escape character is retained
- * during substitution (e.g. {@code $${this-is-escaped}} remains
- * {@code $${this-is-escaped}}). If set to <b>false</b>, the escape
- * character is removed during substitution (e.g.
- * {@code $${this-is-escaped}} becomes
- * {@code ${this-is-escaped}}). The default value is <b>false</b>
- *
- * @param preserveEscapes true if escapes are to be preserved
- */
- public void setPreserveEscapes(final boolean preserveEscapes) {
- this.preserveEscapes = preserveEscapes;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.lang3.Validate;
+
+/**
+ * Substitutes variables within a string by values.
+ * <p>
+ * This class takes a piece of text and substitutes all the variables within it.
+ * The default definition of a variable is {@code ${variableName}}.
+ * The prefix and suffix can be changed via constructors and set methods.
+ * <p>
+ * Variable values are typically resolved from a map, but could also be resolved
+ * from system properties, or by supplying a custom variable resolver.
+ * <p>
+ * The simplest example is to use this class to replace Java System properties. For example:
+ * <pre>
+ * StrSubstitutor.replaceSystemProperties(
+ * "You are running with java.version = ${java.version} and os.name = ${os.name}.");
+ * </pre>
+ * <p>
+ * Typical usage of this class follows the following pattern: First an instance is created
+ * and initialized with the map that contains the values for the available variables.
+ * If a prefix and/or suffix for variables should be used other than the default ones,
+ * the appropriate settings can be performed. After that the {@code replace()}
+ * method can be called passing in the source text for interpolation. In the returned
+ * text all variable references (as long as their values are known) will be resolved.
+ * The following example demonstrates this:
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("animal", "quick brown fox");
+ * valuesMap.put("target", "lazy dog");
+ * String templateString = "The ${animal} jumped over the ${target}.";
+ * StrSubstitutor sub = new StrSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ * yielding:
+ * <pre>
+ * The quick brown fox jumped over the lazy dog.
+ * </pre>
+ * <p>
+ * Also, this class allows to set a default value for unresolved variables.
+ * The default value for a variable can be appended to the variable name after the variable
+ * default value delimiter. The default value of the variable default value delimiter is ':-',
+ * as in bash and other *nix shells, as those are arguably where the default ${} delimiter set originated.
+ * The variable default value delimiter can be manually set by calling {@link #setValueDelimiterMatcher(StrMatcher)},
+ * {@link #setValueDelimiter(char)} or {@link #setValueDelimiter(String)}.
+ * The following shows an example with variable default value settings:
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("animal", "quick brown fox");
+ * valuesMap.put("target", "lazy dog");
+ * String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
+ * StrSubstitutor sub = new StrSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ * yielding:
+ * <pre>
+ * The quick brown fox jumped over the lazy dog. 1234567890.
+ * </pre>
+ * <p>
+ * In addition to this usage pattern there are some static convenience methods that
+ * cover the most common use cases. These methods can be used without the need of
+ * manually creating an instance. However if multiple replace operations are to be
+ * performed, creating and reusing an instance of this class will be more efficient.
+ * <p>
+ * Variable replacement works in a recursive way. Thus, if a variable value contains
+ * a variable then that variable will also be replaced. Cyclic replacements are
+ * detected and will cause an exception to be thrown.
+ * <p>
+ * Sometimes the interpolation's result must contain a variable prefix. As an example
+ * take the following source text:
+ * <pre>
+ * The variable ${${name}} must be used.
+ * </pre>
+ * Here only the variable's name referred to in the text should be replaced resulting
+ * in the text (assuming that the value of the {@code name} variable is {@code x}):
+ * <pre>
+ * The variable ${x} must be used.
+ * </pre>
+ * To achieve this effect there are two possibilities: Either set a different prefix
+ * and suffix for variables which do not conflict with the result text you want to
+ * produce. The other possibility is to use the escape character, by default '$'.
+ * If this character is placed before a variable reference, this reference is ignored
+ * and won't be replaced. For example:
+ * <pre>
+ * The variable $${${name}} must be used.
+ * </pre>
+ * <p>
+ * In some complex scenarios you might even want to perform substitution in the
+ * names of variables, for instance
+ * <pre>
+ * ${jre-${java.specification.version}}
+ * </pre>
+ * {@code StrSubstitutor} supports this recursive substitution in variable
+ * names, but it has to be enabled explicitly by setting the
+ * {@link #setEnableSubstitutionInVariables(boolean) enableSubstitutionInVariables}
+ * property to <b>true</b>.
+ * <p>This class is <b>not</b> thread safe.</p>
+ *
+ * @since 1.0
+ * @deprecated Deprecated as of 1.3, use {@link StringSubstitutor} instead. This class will be removed in 2.0.
+ */
+@Deprecated
+public class StrSubstitutor {
+
+ /**
+ * Constant for the default escape character.
+ */
+ public static final char DEFAULT_ESCAPE = '$';
+
+ /**
+ * Constant for the default variable prefix.
+ */
+ public static final StrMatcher DEFAULT_PREFIX = StrMatcher.stringMatcher("${");
+
+ /**
+ * Constant for the default variable suffix.
+ */
+ public static final StrMatcher DEFAULT_SUFFIX = StrMatcher.stringMatcher("}");
+
+ /**
+ * Constant for the default value delimiter of a variable.
+ */
+ public static final StrMatcher DEFAULT_VALUE_DELIMITER = StrMatcher.stringMatcher(":-");
+
+ /**
+ * Stores the escape character.
+ */
+ private char escapeChar;
+
+ /**
+ * Stores the variable prefix.
+ */
+ private StrMatcher prefixMatcher;
+
+ /**
+ * Stores the variable suffix.
+ */
+ private StrMatcher suffixMatcher;
+
+ /**
+ * Stores the default variable value delimiter.
+ */
+ private StrMatcher valueDelimiterMatcher;
+
+ /**
+ * Variable resolution is delegated to an implementor of VariableResolver.
+ */
+ private StrLookup<?> variableResolver;
+
+ /**
+ * The flag whether substitution in variable names is enabled.
+ */
+ private boolean enableSubstitutionInVariables;
+
+ /**
+ * Whether escapes should be preserved. Default is false;
+ */
+ private boolean preserveEscapes = false;
+
+ /**
+ * The flag whether substitution in variable values is disabled.
+ */
+ private boolean disableSubstitutionInValues;
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables in the given source object with
+ * their matching values from the map.
+ *
+ * @param <V> the type of the values in the map
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueMap the map with the values, may be null
+ * @return The result of the replace operation
+ */
+ public static <V> String replace(final Object source, final Map<String, V> valueMap) {
+ return new StrSubstitutor(valueMap).replace(source);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with
+ * their matching values from the map. This method allows to specify a
+ * custom variable prefix and suffix
+ *
+ * @param <V> the type of the values in the map
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueMap the map with the values, may be null
+ * @param prefix the prefix of variables, not null
+ * @param suffix the suffix of variables, not null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public static <V> String replace(final Object source,
+ final Map<String, V> valueMap,
+ final String prefix,
+ final String suffix) {
+ return new StrSubstitutor(valueMap, prefix, suffix).replace(source);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching
+ * values from the properties.
+ *
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueProperties the properties with values, may be null
+ * @return The result of the replace operation
+ */
+ public static String replace(final Object source, final Properties valueProperties) {
+ if (valueProperties == null) {
+ return source.toString();
+ }
+ final Map<String, String> valueMap = new HashMap<>();
+ final Enumeration<?> propNames = valueProperties.propertyNames();
+ while (propNames.hasMoreElements()) {
+ final String propName = (String) propNames.nextElement();
+ final String propValue = valueProperties.getProperty(propName);
+ valueMap.put(propName, propValue);
+ }
+ return StrSubstitutor.replace(source, valueMap);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with
+ * their matching values from the system properties.
+ *
+ * @param source the source text containing the variables to substitute, null returns null
+ * @return The result of the replace operation
+ */
+ public static String replaceSystemProperties(final Object source) {
+ return new StrSubstitutor(StrLookup.systemPropertiesLookup()).replace(source);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Creates a new instance with defaults for variable prefix and suffix
+ * and the escaping character.
+ */
+ public StrSubstitutor() {
+ this((StrLookup<?>) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it. Uses defaults for variable
+ * prefix and suffix and the escaping character.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ */
+ public <V> StrSubstitutor(final Map<String, V> valueMap) {
+ this(StrLookup.mapLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it. Uses a default escaping character.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) {
+ this(StrLookup.mapLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
+ final char escape) {
+ this(StrLookup.mapLookup(valueMap), prefix, suffix, escape);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiter the variable default value delimiter, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StrSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
+ final char escape, final String valueDelimiter) {
+ this(StrLookup.mapLookup(valueMap), prefix, suffix, escape, valueDelimiter);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ */
+ public StrSubstitutor(final StrLookup<?> variableResolver) {
+ this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
+ final char escape) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefix(prefix);
+ this.setVariableSuffix(suffix);
+ this.setEscapeChar(escape);
+ this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiter the variable default value delimiter string, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StrSubstitutor(final StrLookup<?> variableResolver, final String prefix, final String suffix,
+ final char escape, final String valueDelimiter) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefix(prefix);
+ this.setVariableSuffix(suffix);
+ this.setEscapeChar(escape);
+ this.setValueDelimiter(valueDelimiter);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefixMatcher the prefix for variables, not null
+ * @param suffixMatcher the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StrSubstitutor(
+ final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
+ final char escape) {
+ this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefixMatcher the prefix for variables, not null
+ * @param suffixMatcher the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StrSubstitutor(
+ final StrLookup<?> variableResolver, final StrMatcher prefixMatcher, final StrMatcher suffixMatcher,
+ final char escape, final StrMatcher valueDelimiterMatcher) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefixMatcher(prefixMatcher);
+ this.setVariableSuffixMatcher(suffixMatcher);
+ this.setEscapeChar(escape);
+ this.setValueDelimiterMatcher(valueDelimiterMatcher);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source string as a template.
+ *
+ * @param source the string to replace in, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final String source) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(source);
+ if (!substitute(buf, 0, source.length())) {
+ return source;
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source string as a template.
+ * <p>
+ * Only the specified portion of the string will be processed.
+ * The rest of the string is not processed, and is not returned.
+ *
+ * @param source the string to replace in, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ */
+ public String replace(final String source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return source.substring(offset, offset + length);
+ }
+ return buf.toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source array as a template.
+ * The array is not altered by this method.
+ *
+ * @param source the character array to replace in, not altered, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final char[] source) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(source.length).append(source);
+ substitute(buf, 0, source.length);
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source array as a template.
+ * The array is not altered by this method.
+ * <p>
+ * Only the specified portion of the array will be processed.
+ * The rest of the array is not processed, and is not returned.
+ *
+ * @param source the character array to replace in, not altered, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ */
+ public String replace(final char[] source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source buffer as a template.
+ * The buffer is not altered by this method.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final StringBuffer source) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(source.length()).append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source buffer as a template.
+ * The buffer is not altered by this method.
+ * <p>
+ * Only the specified portion of the buffer will be processed.
+ * The rest of the buffer is not processed, and is not returned.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ */
+ public String replace(final StringBuffer source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source as a template.
+ * The source is not altered by this method.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final CharSequence source) {
+ if (source == null) {
+ return null;
+ }
+ return replace(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source as a template.
+ * The source is not altered by this method.
+ * <p>
+ * Only the specified portion of the buffer will be processed.
+ * The rest of the buffer is not processed, and is not returned.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ */
+ public String replace(final CharSequence source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source builder as a template.
+ * The builder is not altered by this method.
+ *
+ * @param source the builder to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final StrBuilder source) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(source.length()).append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values
+ * from the resolver using the given source builder as a template.
+ * The builder is not altered by this method.
+ * <p>
+ * Only the specified portion of the builder will be processed.
+ * The rest of the builder is not processed, and is not returned.
+ *
+ * @param source the builder to use as a template, not changed, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ */
+ public String replace(final StrBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables in the given source object with
+ * their matching values from the resolver. The input source object is
+ * converted to a string using {@code toString} and is not altered.
+ *
+ * @param source the source to replace in, null returns null
+ * @return The result of the replace operation
+ */
+ public String replace(final Object source) {
+ if (source == null) {
+ return null;
+ }
+ final StrBuilder buf = new StrBuilder().append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source buffer
+ * with their matching values from the resolver.
+ * The buffer is updated with the result.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuffer source) {
+ if (source == null) {
+ return false;
+ }
+ return replaceIn(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source buffer
+ * with their matching values from the resolver.
+ * The buffer is updated with the result.
+ * <p>
+ * Only the specified portion of the buffer will be processed.
+ * The rest of the buffer is not processed, but it is not deleted.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the buffer to be processed, must be valid
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return false;
+ }
+ source.replace(offset, offset + length, buf.toString());
+ return true;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source buffer
+ * with their matching values from the resolver.
+ * The buffer is updated with the result.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuilder source) {
+ if (source == null) {
+ return false;
+ }
+ return replaceIn(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source builder
+ * with their matching values from the resolver.
+ * The builder is updated with the result.
+ * <p>
+ * Only the specified portion of the buffer will be processed.
+ * The rest of the buffer is not processed, but it is not deleted.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the buffer to be processed, must be valid
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ final StrBuilder buf = new StrBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return false;
+ }
+ source.replace(offset, offset + length, buf.toString());
+ return true;
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source
+ * builder with their matching values from the resolver.
+ *
+ * @param source the builder to replace in, updated, null returns zero
+ * @return true if altered
+ */
+ public boolean replaceIn(final StrBuilder source) {
+ if (source == null) {
+ return false;
+ }
+ return substitute(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source
+ * builder with their matching values from the resolver.
+ * <p>
+ * Only the specified portion of the builder will be processed.
+ * The rest of the builder is not processed, but it is not deleted.
+ *
+ * @param source the builder to replace in, null returns zero
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the builder to be processed, must be valid
+ * @return true if altered
+ */
+ public boolean replaceIn(final StrBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ return substitute(source, offset, length);
+ }
+
+ //-----------------------------------------------------------------------
+ /**
+ * Internal method that substitutes the variables.
+ * <p>
+ * Most users of this class do not need to call this method. This method will
+ * be called automatically by another (public) method.
+ * <p>
+ * Writers of subclasses can override this method if they need access to
+ * the substitution process at the start or end.
+ *
+ * @param buf the string builder to substitute into, not null
+ * @param offset the start offset within the builder, must be valid
+ * @param length the length within the builder to be processed, must be valid
+ * @return true if altered
+ */
+ protected boolean substitute(final StrBuilder buf, final int offset, final int length) {
+ return substitute(buf, offset, length, null) > 0;
+ }
+
+ /**
+ * Recursive handler for multiple levels of interpolation. This is the main
+ * interpolation method, which resolves the values of all variable references
+ * contained in the passed in text.
+ *
+ * @param buf the string builder to substitute into, not null
+ * @param offset the start offset within the builder, must be valid
+ * @param length the length within the builder to be processed, must be valid
+ * @param priorVariables the stack keeping track of the replaced variables, may be null
+ * @return The length change that occurs, unless priorVariables is null when the int
+ * represents a boolean flag as to whether any change occurred.
+ */
+ private int substitute(final StrBuilder buf, final int offset, final int length, List<String> priorVariables) {
+ final StrMatcher pfxMatcher = getVariablePrefixMatcher();
+ final StrMatcher suffMatcher = getVariableSuffixMatcher();
+ final char escape = getEscapeChar();
+ final StrMatcher valueDelimMatcher = getValueDelimiterMatcher();
+ final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables();
+ final boolean substitutionInValuesDisabled = isDisableSubstitutionInValues();
+
+ final boolean top = priorVariables == null;
+ boolean altered = false;
+ int lengthChange = 0;
+ char[] chars = buf.buffer;
+ int bufEnd = offset + length;
+ int pos = offset;
+ while (pos < bufEnd) {
+ final int startMatchLen = pfxMatcher.isMatch(chars, pos, offset,
+ bufEnd);
+ if (startMatchLen == 0) {
+ pos++;
+ } else {
+ // found variable start marker
+ if (pos > offset && chars[pos - 1] == escape) {
+ // escaped
+ if (preserveEscapes) {
+ pos++;
+ continue;
+ }
+ buf.deleteCharAt(pos - 1);
+ chars = buf.buffer; // in case buffer was altered
+ lengthChange--;
+ altered = true;
+ bufEnd--;
+ } else {
+ // find suffix
+ final int startPos = pos;
+ pos += startMatchLen;
+ int endMatchLen = 0;
+ int nestedVarCount = 0;
+ while (pos < bufEnd) {
+ if (substitutionInVariablesEnabled
+ && pfxMatcher.isMatch(chars,
+ pos, offset, bufEnd) != 0) {
+ // found a nested variable start
+ endMatchLen = pfxMatcher.isMatch(chars,
+ pos, offset, bufEnd);
+ nestedVarCount++;
+ pos += endMatchLen;
+ continue;
+ }
+
+ endMatchLen = suffMatcher.isMatch(chars, pos, offset,
+ bufEnd);
+ if (endMatchLen == 0) {
+ pos++;
+ } else {
+ // found variable end marker
+ if (nestedVarCount == 0) {
+ String varNameExpr = new String(chars, startPos
+ + startMatchLen, pos - startPos
+ - startMatchLen);
+ if (substitutionInVariablesEnabled) {
+ final StrBuilder bufName = new StrBuilder(varNameExpr);
+ substitute(bufName, 0, bufName.length());
+ varNameExpr = bufName.toString();
+ }
+ pos += endMatchLen;
+ final int endPos = pos;
+
+ String varName = varNameExpr;
+ String varDefaultValue = null;
+
+ if (valueDelimMatcher != null) {
+ final char[] varNameExprChars = varNameExpr.toCharArray();
+ int valueDelimiterMatchLen = 0;
+ for (int i = 0; i < varNameExprChars.length; i++) {
+ // if there's any nested variable when nested variable substitution disabled,
+ // then stop resolving name and default value.
+ if (!substitutionInVariablesEnabled
+ && pfxMatcher.isMatch(varNameExprChars,
+ i,
+ i,
+ varNameExprChars.length) != 0) {
+ break;
+ }
+ if (valueDelimMatcher.isMatch(varNameExprChars, i) != 0) {
+ valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i);
+ varName = varNameExpr.substring(0, i);
+ varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
+ break;
+ }
+ }
+ }
+
+ // on the first call initialize priorVariables
+ if (priorVariables == null) {
+ priorVariables = new ArrayList<>();
+ priorVariables.add(new String(chars,
+ offset, length));
+ }
+
+ // handle cyclic substitution
+ checkCyclicSubstitution(varName, priorVariables);
+ priorVariables.add(varName);
+
+ // resolve the variable
+ String varValue = resolveVariable(varName, buf,
+ startPos, endPos);
+ if (varValue == null) {
+ varValue = varDefaultValue;
+ }
+ if (varValue != null) {
+ final int varLen = varValue.length();
+ buf.replace(startPos, endPos, varValue);
+ altered = true;
+ int change = 0;
+ if (!substitutionInValuesDisabled) { // recursive replace
+ change = substitute(buf, startPos,
+ varLen, priorVariables);
+ }
+ change = change
+ + varLen - (endPos - startPos);
+ pos += change;
+ bufEnd += change;
+ lengthChange += change;
+ chars = buf.buffer; // in case buffer was
+ // altered
+ }
+
+ // remove variable from the cyclic stack
+ priorVariables
+ .remove(priorVariables.size() - 1);
+ break;
+ }
+ nestedVarCount--;
+ pos += endMatchLen;
+ }
+ }
+ }
+ }
+ }
+ if (top) {
+ return altered ? 1 : 0;
+ }
+ return lengthChange;
+ }
+
+ /**
+ * Checks if the specified variable is already in the stack (list) of variables.
+ *
+ * @param varName the variable name to check
+ * @param priorVariables the list of prior variables
+ */
+ private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
+ if (!priorVariables.contains(varName)) {
+ return;
+ }
+ final StrBuilder buf = new StrBuilder(256);
+ buf.append("Infinite loop in property interpolation of ");
+ buf.append(priorVariables.remove(0));
+ buf.append(": ");
+ buf.appendWithSeparators(priorVariables, "->");
+ throw new IllegalStateException(buf.toString());
+ }
+
+ /**
+ * Internal method that resolves the value of a variable.
+ * <p>
+ * Most users of this class do not need to call this method. This method is
+ * called automatically by the substitution process.
+ * <p>
+ * Writers of subclasses can override this method if they need to alter
+ * how each substitution occurs. The method is passed the variable's name
+ * and must return the corresponding value. This implementation uses the
+ * {@link #getVariableResolver()} with the variable's name as the key.
+ *
+ * @param variableName the name of the variable, not null
+ * @param buf the buffer where the substitution is occurring, not null
+ * @param startPos the start position of the variable including the prefix, valid
+ * @param endPos the end position of the variable including the suffix, valid
+ * @return The variable's value or <b>null</b> if the variable is unknown
+ */
+ protected String resolveVariable(final String variableName,
+ final StrBuilder buf,
+ final int startPos,
+ final int endPos) {
+ final StrLookup<?> resolver = getVariableResolver();
+ if (resolver == null) {
+ return null;
+ }
+ return resolver.lookup(variableName);
+ }
+
+ // Escape
+ //-----------------------------------------------------------------------
+ /**
+ * Returns the escape character.
+ *
+ * @return The character used for escaping variable references
+ */
+ public char getEscapeChar() {
+ return this.escapeChar;
+ }
+
+ /**
+ * Sets the escape character.
+ * If this character is placed before a variable reference in the source
+ * text, this variable will be ignored.
+ *
+ * @param escapeCharacter the escape character (0 for disabling escaping)
+ */
+ public void setEscapeChar(final char escapeCharacter) {
+ this.escapeChar = escapeCharacter;
+ }
+
+ // Prefix
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the variable prefix matcher currently in use.
+ * <p>
+ * The variable prefix is the character or characters that identify the
+ * start of a variable. This prefix is expressed in terms of a matcher
+ * allowing advanced prefix matches.
+ *
+ * @return The prefix matcher in use
+ */
+ public StrMatcher getVariablePrefixMatcher() {
+ return prefixMatcher;
+ }
+
+ /**
+ * Sets the variable prefix matcher currently in use.
+ * <p>
+ * The variable prefix is the character or characters that identify the
+ * start of a variable. This prefix is expressed in terms of a matcher
+ * allowing advanced prefix matches.
+ *
+ * @param prefixMatcher the prefix matcher to use, null ignored
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the prefix matcher is null
+ */
+ public StrSubstitutor setVariablePrefixMatcher(final StrMatcher prefixMatcher) {
+ Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
+ this.prefixMatcher = prefixMatcher;
+ return this;
+ }
+
+ /**
+ * Sets the variable prefix to use.
+ * <p>
+ * The variable prefix is the character or characters that identify the
+ * start of a variable. This method allows a single character prefix to
+ * be easily set.
+ *
+ * @param prefix the prefix character to use
+ * @return this, to enable chaining
+ */
+ public StrSubstitutor setVariablePrefix(final char prefix) {
+ return setVariablePrefixMatcher(StrMatcher.charMatcher(prefix));
+ }
+
+ /**
+ * Sets the variable prefix to use.
+ * <p>
+ * The variable prefix is the character or characters that identify the
+ * start of a variable. This method allows a string prefix to be easily set.
+ *
+ * @param prefix the prefix for variables, not null
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the prefix is null
+ */
+ public StrSubstitutor setVariablePrefix(final String prefix) {
+ Validate.isTrue(prefix != null, "Variable prefix must not be null!");
+ return setVariablePrefixMatcher(StrMatcher.stringMatcher(prefix));
+ }
+
+ // Suffix
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the variable suffix matcher currently in use.
+ * <p>
+ * The variable suffix is the character or characters that identify the
+ * end of a variable. This suffix is expressed in terms of a matcher
+ * allowing advanced suffix matches.
+ *
+ * @return The suffix matcher in use
+ */
+ public StrMatcher getVariableSuffixMatcher() {
+ return suffixMatcher;
+ }
+
+ /**
+ * Sets the variable suffix matcher currently in use.
+ * <p>
+ * The variable suffix is the character or characters that identify the
+ * end of a variable. This suffix is expressed in terms of a matcher
+ * allowing advanced suffix matches.
+ *
+ * @param suffixMatcher the suffix matcher to use, null ignored
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the suffix matcher is null
+ */
+ public StrSubstitutor setVariableSuffixMatcher(final StrMatcher suffixMatcher) {
+ Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
+ this.suffixMatcher = suffixMatcher;
+ return this;
+ }
+
+ /**
+ * Sets the variable suffix to use.
+ * <p>
+ * The variable suffix is the character or characters that identify the
+ * end of a variable. This method allows a single character suffix to
+ * be easily set.
+ *
+ * @param suffix the suffix character to use
+ * @return this, to enable chaining
+ */
+ public StrSubstitutor setVariableSuffix(final char suffix) {
+ return setVariableSuffixMatcher(StrMatcher.charMatcher(suffix));
+ }
+
+ /**
+ * Sets the variable suffix to use.
+ * <p>
+ * The variable suffix is the character or characters that identify the
+ * end of a variable. This method allows a string suffix to be easily set.
+ *
+ * @param suffix the suffix for variables, not null
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the suffix is null
+ */
+ public StrSubstitutor setVariableSuffix(final String suffix) {
+ Validate.isTrue(suffix != null, "Variable suffix must not be null!");
+ return setVariableSuffixMatcher(StrMatcher.stringMatcher(suffix));
+ }
+
+ // Variable Default Value Delimiter
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the variable default value delimiter matcher currently in use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the
+ * variable name and the variable default value. This delimiter is expressed in terms of a matcher
+ * allowing advanced variable default value delimiter matches.
+ * <p>
+ * If it returns null, then the variable default value resolution is disabled.
+ *
+ * @return The variable default value delimiter matcher in use, may be null
+ */
+ public StrMatcher getValueDelimiterMatcher() {
+ return valueDelimiterMatcher;
+ }
+
+ /**
+ * Sets the variable default value delimiter matcher to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the
+ * variable name and the variable default value. This delimiter is expressed in terms of a matcher
+ * allowing advanced variable default value delimiter matches.
+ * <p>
+ * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution
+ * becomes disabled.
+ *
+ * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
+ * @return this, to enable chaining
+ */
+ public StrSubstitutor setValueDelimiterMatcher(final StrMatcher valueDelimiterMatcher) {
+ this.valueDelimiterMatcher = valueDelimiterMatcher;
+ return this;
+ }
+
+ /**
+ * Sets the variable default value delimiter to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the
+ * variable name and the variable default value. This method allows a single character
+ * variable default value delimiter to be easily set.
+ *
+ * @param valueDelimiter the variable default value delimiter character to use
+ * @return this, to enable chaining
+ */
+ public StrSubstitutor setValueDelimiter(final char valueDelimiter) {
+ return setValueDelimiterMatcher(StrMatcher.charMatcher(valueDelimiter));
+ }
+
+ /**
+ * Sets the variable default value delimiter to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the
+ * variable name and the variable default value. This method allows a string
+ * variable default value delimiter to be easily set.
+ * <p>
+ * If the {@code valueDelimiter} is null or empty string, then the variable default
+ * value resolution becomes disabled.
+ *
+ * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
+ * @return this, to enable chaining
+ */
+ public StrSubstitutor setValueDelimiter(final String valueDelimiter) {
+ if (valueDelimiter == null || valueDelimiter.length() == 0) {
+ setValueDelimiterMatcher(null);
+ return this;
+ }
+ return setValueDelimiterMatcher(StrMatcher.stringMatcher(valueDelimiter));
+ }
+
+ // Resolver
+ //-----------------------------------------------------------------------
+ /**
+ * Gets the VariableResolver that is used to lookup variables.
+ *
+ * @return The VariableResolver
+ */
+ public StrLookup<?> getVariableResolver() {
+ return this.variableResolver;
+ }
+
+ /**
+ * Sets the VariableResolver that is used to lookup variables.
+ *
+ * @param variableResolver the VariableResolver
+ */
+ public void setVariableResolver(final StrLookup<?> variableResolver) {
+ this.variableResolver = variableResolver;
+ }
+
+ // Substitution support in variable names
+ //-----------------------------------------------------------------------
+ /**
+ * Returns a flag whether substitution is done in variable names.
+ *
+ * @return The substitution in variable names flag
+ */
+ public boolean isEnableSubstitutionInVariables() {
+ return enableSubstitutionInVariables;
+ }
+
+ /**
+ * Sets a flag whether substitution is done in variable names. If set to
+ * <b>true</b>, the names of variables can contain other variables which are
+ * processed first before the original variable is evaluated, e.g.
+ * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
+ *
+ * @param enableSubstitutionInVariables the new value of the flag
+ */
+ public void setEnableSubstitutionInVariables(
+ final boolean enableSubstitutionInVariables) {
+ this.enableSubstitutionInVariables = enableSubstitutionInVariables;
+ }
+
+ /**
+ * Returns a flag whether substitution is disabled in variable values.If set to
+ * <b>true</b>, the values of variables can contain other variables will not be
+ * processed and substituted original variable is evaluated, e.g.
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("name", "Douglas ${surname}");
+ * valuesMap.put("surname", "Crockford");
+ * String templateString = "Hi ${name}";
+ * StrSubstitutor sub = new StrSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ * yielding:
+ * <pre>
+ * Hi Douglas ${surname}
+ * </pre>
+ *
+ * @return The substitution in variable values flag
+ *
+ * @since 1.2
+ */
+ public boolean isDisableSubstitutionInValues() {
+ return disableSubstitutionInValues;
+ }
+
+ /**
+ * Sets a flag whether substitution is done in variable values (recursive).
+ *
+ * @param disableSubstitutionInValues true if substitution in variable value are disabled
+ *
+ * @since 1.2
+ */
+ public void setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
+ this.disableSubstitutionInValues = disableSubstitutionInValues;
+ }
+
+ /**
+ * Returns the flag controlling whether escapes are preserved during
+ * substitution.
+ *
+ * @return The preserve escape flag
+ */
+ public boolean isPreserveEscapes() {
+ return preserveEscapes;
+ }
+
+ /**
+ * Sets a flag controlling whether escapes are preserved during
+ * substitution. If set to <b>true</b>, the escape character is retained
+ * during substitution (e.g. {@code $${this-is-escaped}} remains
+ * {@code $${this-is-escaped}}). If set to <b>false</b>, the escape
+ * character is removed during substitution (e.g.
+ * {@code $${this-is-escaped}} becomes
+ * {@code ${this-is-escaped}}). The default value is <b>false</b>
+ *
+ * @param preserveEscapes true if escapes are to be preserved
+ */
+ public void setPreserveEscapes(final boolean preserveEscapes) {
+ this.preserveEscapes = preserveEscapes;
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/StringSubstitutor.java b/src/main/java/org/apache/commons/text/StringSubstitutor.java
index d465c45..1c925c4 100644
--- a/src/main/java/org/apache/commons/text/StringSubstitutor.java
+++ b/src/main/java/org/apache/commons/text/StringSubstitutor.java
@@ -1,1421 +1,1421 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text;
-
-import java.util.ArrayList;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Properties;
-
-import org.apache.commons.lang3.Validate;
-import org.apache.commons.text.lookup.StringLookup;
-import org.apache.commons.text.lookup.StringLookupFactory;
-import org.apache.commons.text.matcher.StringMatcher;
-import org.apache.commons.text.matcher.StringMatcherFactory;
-
-/**
- * Substitutes variables within a string by values.
- * <p>
- * This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is
- * {@code ${variableName}}. The prefix and suffix can be changed via constructors and set methods.
- * </p>
- * <p>
- * Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying
- * a custom variable resolver.
- * <p>
- * The simplest example is to use this class to replace Java System properties. For example:
- * </p>
- *
- * <pre>
- * StringSubstitutor
- * .replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}.");
- * </pre>
- *
- * <h2>Using a Custom Map</h2>
- * <p>
- * Typical usage of this class follows the following pattern: First an instance is created and initialized with the map
- * that contains the values for the available variables. If a prefix and/or suffix for variables should be used other
- * than the default ones, the appropriate settings can be performed. After that the {@code replace()} method can be
- * called passing in the source text for interpolation. In the returned text all variable references (as long as their
- * values are known) will be resolved. The following example demonstrates this:
- * </p>
- *
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("animal", "quick brown fox");
- * valuesMap.put("target", "lazy dog");
- * String templateString = "The ${animal} jumped over the ${target}.";
- * StringSubstitutor sub = new StringSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- *
- * <p>
- * yielding:
- * </p>
- *
- * <pre>
- * The quick brown fox jumped over the lazy dog.
- * </pre>
- *
- * <h2>Providing Default Values</h2>
- * <p>
- * This class lets you set a default value for unresolved variables. The default value for a variable can be appended to
- * the variable name after the variable default value delimiter. The default value of the variable default value
- * delimiter is ':-', as in bash and other *nix shells, as those are arguably where the default ${} delimiter set
- * originated. The variable default value delimiter can be manually set by calling
- * {@link #setValueDelimiterMatcher(StringMatcher)}, {@link #setValueDelimiter(char)} or
- * {@link #setValueDelimiter(String)}. The following shows an example with variable default value settings:
- * </p>
- *
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("animal", "quick brown fox");
- * valuesMap.put("target", "lazy dog");
- * String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
- * StringSubstitutor sub = new StringSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- *
- * <p>
- * yielding:
- * </p>
- *
- * <pre>
- * The quick brown fox jumped over the lazy dog. 1234567890.
- * </pre>
- *
- * <p>
- * {@code StringSubstitutor} supports throwing exceptions for unresolved variables, you enable this by setting calling
- * {@link #setEnableUndefinedVariableException(boolean)} with {@code true}.
- * </p>
- *
- * <h2>Reusing Instances</h2>
- * <p>
- * In addition to this usage pattern there are some static convenience methods that cover the most common use cases.
- * These methods can be used without the need of manually creating an instance. However if multiple replace operations
- * are to be performed, creating and reusing an instance of this class will be more efficient.
- * </p>
- * <p>
- * This class is <b>not</b> thread safe.
- * </p>
- *
- * <h2>Using Interpolation</h2>
- * <p>
- * The default interpolator let's you use string lookups like:
- * </p>
- *
- * <pre>
-final StringSubstitutor interpolator = StringSubstitutor.createInterpolator();
-interpolator.setEnableSubstitutionInVariables(true); // Allows for nested $'s.
-final String text = interpolator.replace(
- "Base64 Decoder: ${base64Decoder:SGVsbG9Xb3JsZCE=}\n" +
- "Base64 Encoder: ${base64Encoder:HelloWorld!}\n" +
- "Java Constant: ${const:java.awt.event.KeyEvent.VK_ESCAPE}\n" +
- "Date: ${date:yyyy-MM-dd}\n" +
- "DNS: ${dns:address|apache.org}\n" +
- "Environment Variable: ${env:USERNAME}\n" +
- "File Content: ${file:UTF-8:src/test/resources/document.properties}\n" +
- "Java: ${java:version}\n" +
- "Localhost: ${localhost:canonical-name}\n" +
- "Properties File: ${properties:src/test/resources/document.properties::mykey}\n" +
- "Resource Bundle: ${resourceBundle:org.example.testResourceBundleLookup:mykey}\n" +
- "Script: ${script:javascript:3 + 4}\n" +
- "System Property: ${sys:user.dir}\n" +
- "URL Decoder: ${urlDecoder:Hello%20World%21}\n" +
- "URL Encoder: ${urlEncoder:Hello World!}\n" +
- "URL Content (HTTP): ${url:UTF-8:http://www.apache.org}\n" +
- "URL Content (HTTPS): ${url:UTF-8:https://www.apache.org}\n" +
- "URL Content (File): ${url:UTF-8:file:///${sys:user.dir}/src/test/resources/document.properties}\n" +
- "XML XPath: ${xml:src/test/resources/document.xml:/root/path/to/node}\n"
-);
- * </pre>
- * <p>
- * For documentation of each lookup, see {@link StringLookupFactory}.
- * </p>
- *
- * <h2>Using Recursive Variable Replacement</h2>
- * <p>
- * Variable replacement works in a recursive way. Thus, if a variable value contains a variable then that variable will
- * also be replaced. Cyclic replacements are detected and will cause an exception to be thrown.
- * </p>
- * <p>
- * Sometimes the interpolation's result must contain a variable prefix. As an example take the following source text:
- * </p>
- *
- * <pre>
- * The variable ${${name}} must be used.
- * </pre>
- *
- * <p>
- * Here only the variable's name referred to in the text should be replaced resulting in the text (assuming that the
- * value of the {@code name} variable is {@code x}):
- * </p>
- *
- * <pre>
- * The variable ${x} must be used.
- * </pre>
- *
- * <p>
- * To achieve this effect there are two possibilities: Either set a different prefix and suffix for variables which do
- * not conflict with the result text you want to produce. The other possibility is to use the escape character, by
- * default '$'. If this character is placed before a variable reference, this reference is ignored and won't be
- * replaced. For example:
- * </p>
- *
- * <pre>
- * The variable $${${name}} must be used.
- * </pre>
- * <p>
- * In some complex scenarios you might even want to perform substitution in the names of variables, for instance
- * </p>
- *
- * <pre>
- * ${jre-${java.specification.version}}
- * </pre>
- *
- * <p>
- * {@code StringSubstitutor} supports this recursive substitution in variable names, but it has to be enabled explicitly
- * by calling {@link #setEnableSubstitutionInVariables(boolean)} with {@code true}.
- * </p>
- *
- * @since 1.3
- */
-public class StringSubstitutor {
-
- /**
- * The default variable default separator.
- *
- * @since 1.5.
- */
- public static final String DEFAULT_VAR_DEFAULT = ":-";
-
- /**
- * The default variable end separator.
- *
- * @since 1.5.
- */
- public static final String DEFAULT_VAR_END = "}";
-
- /**
- * The default variable start separator.
- *
- * @since 1.5.
- */
- public static final String DEFAULT_VAR_START = "${";
-
- /**
- * Constant for the default escape character.
- */
- public static final char DEFAULT_ESCAPE = '$';
-
- /**
- * Constant for the default variable prefix.
- */
- public static final StringMatcher DEFAULT_PREFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_START);
-
- /**
- * Constant for the default variable suffix.
- */
- public static final StringMatcher DEFAULT_SUFFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_END);
-
- /**
- * Constant for the default value delimiter of a variable.
- */
- public static final StringMatcher DEFAULT_VALUE_DELIMITER = StringMatcherFactory.INSTANCE
- .stringMatcher(DEFAULT_VAR_DEFAULT);
-
- /**
- * Creates a new instance using the interpolator string lookup
- * {@link StringLookupFactory#interpolatorStringLookup()}.
- * <p>
- * This StringSubstitutor lets you perform substituions like:
- * </p>
- *
- * <pre>
- * StringSubstitutor.createInterpolator()
- * .replace("OS name: ${sys:os.name}, " + "3 + 4 = ${script:javascript:3 + 4}");
- * </pre>
- *
- * @return a new instance using the interpolator string lookup.
- * @see StringLookupFactory#interpolatorStringLookup()
- * @since 1.8
- */
- public static StringSubstitutor createInterpolator() {
- return new StringSubstitutor(StringLookupFactory.INSTANCE.interpolatorStringLookup());
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with their matching values from the map.
- *
- * @param <V> the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
- */
- public static <V> String replace(final Object source, final Map<String, V> valueMap) {
- return new StringSubstitutor(valueMap).replace(source);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with their matching values from the map.
- * This method allows to specify a custom variable prefix and suffix
- *
- * @param <V> the type of the values in the map
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueMap the map with the values, may be null
- * @param prefix the prefix of variables, not null
- * @param suffix the suffix of variables, not null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if the prefix or suffix is null
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
- */
- public static <V> String replace(final Object source, final Map<String, V> valueMap, final String prefix,
- final String suffix) {
- return new StringSubstitutor(valueMap, prefix, suffix).replace(source);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with their matching values from the
- * properties.
- *
- * @param source the source text containing the variables to substitute, null returns null
- * @param valueProperties the properties with values, may be null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
- */
- public static String replace(final Object source, final Properties valueProperties) {
- if (valueProperties == null) {
- return source.toString();
- }
- final Map<String, String> valueMap = new HashMap<>();
- final Enumeration<?> propNames = valueProperties.propertyNames();
- while (propNames.hasMoreElements()) {
- final String propName = (String) propNames.nextElement();
- final String propValue = valueProperties.getProperty(propName);
- valueMap.put(propName, propValue);
- }
- return StringSubstitutor.replace(source, valueMap);
- }
-
- /**
- * Replaces all the occurrences of variables in the given source object with their matching values from the system
- * properties.
- *
- * @param source the source text containing the variables to substitute, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
- */
- public static String replaceSystemProperties(final Object source) {
- return new StringSubstitutor(StringLookupFactory.INSTANCE.systemPropertyStringLookup()).replace(source);
- }
-
- /**
- * Stores the escape character.
- */
- private char escapeChar;
-
- /**
- * Stores the variable prefix.
- */
- private StringMatcher prefixMatcher;
-
- /**
- * Stores the variable suffix.
- */
- private StringMatcher suffixMatcher;
-
- /**
- * Stores the default variable value delimiter.
- */
- private StringMatcher valueDelimiterMatcher;
-
- /**
- * Variable resolution is delegated to an implementor of {@link StringLookup}.
- */
- private StringLookup variableResolver;
-
- /**
- * The flag whether substitution in variable names is enabled.
- */
- private boolean enableSubstitutionInVariables;
-
- /**
- * Whether escapes should be preserved. Default is false;
- */
- private boolean preserveEscapes;
-
- /**
- * The flag whether substitution in variable values is disabled.
- */
- private boolean disableSubstitutionInValues;
-
- /**
- * The flag whether exception should be thrown on undefined variable.
- */
- private boolean enableUndefinedVariableException;
-
- // -----------------------------------------------------------------------
- /**
- * Creates a new instance with defaults for variable prefix and suffix and the escaping character.
- */
- public StringSubstitutor() {
- this((StringLookup) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it. Uses defaults for variable prefix and suffix and the escaping
- * character.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- */
- public <V> StringSubstitutor(final Map<String, V> valueMap) {
- this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it. Uses a default escaping character.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) {
- this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
- final char escape) {
- this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param <V> the type of the values in the map
- * @param valueMap the map with the variables' values, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
- final char escape, final String valueDelimiter) {
- this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape, valueDelimiter);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- */
- public StringSubstitutor(final StringLookup variableResolver) {
- this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
- final char escape) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefix(prefix);
- this.setVariableSuffix(suffix);
- this.setEscapeChar(escape);
- this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefix the prefix for variables, not null
- * @param suffix the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiter the variable default value delimiter string, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
- final char escape, final String valueDelimiter) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefix(prefix);
- this.setVariableSuffix(suffix);
- this.setEscapeChar(escape);
- this.setValueDelimiter(valueDelimiter);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher,
- final StringMatcher suffixMatcher, final char escape) {
- this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER);
- }
-
- /**
- * Creates a new instance and initializes it.
- *
- * @param variableResolver the variable resolver, may be null
- * @param prefixMatcher the prefix for variables, not null
- * @param suffixMatcher the suffix for variables, not null
- * @param escape the escape character
- * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
- * @throws IllegalArgumentException if the prefix or suffix is null
- */
- public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher,
- final StringMatcher suffixMatcher, final char escape, final StringMatcher valueDelimiterMatcher) {
- this.setVariableResolver(variableResolver);
- this.setVariablePrefixMatcher(prefixMatcher);
- this.setVariableSuffixMatcher(suffixMatcher);
- this.setEscapeChar(escape);
- this.setValueDelimiterMatcher(valueDelimiterMatcher);
- }
-
- /**
- * Checks if the specified variable is already in the stack (list) of variables.
- *
- * @param varName the variable name to check
- * @param priorVariables the list of prior variables
- */
- private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
- if (!priorVariables.contains(varName)) {
- return;
- }
- final TextStringBuilder buf = new TextStringBuilder(256);
- buf.append("Infinite loop in property interpolation of ");
- buf.append(priorVariables.remove(0));
- buf.append(": ");
- buf.appendWithSeparators(priorVariables, "->");
- throw new IllegalStateException(buf.toString());
- }
-
- // Escape
- // -----------------------------------------------------------------------
- /**
- * Returns the escape character.
- *
- * @return The character used for escaping variable references
- */
- public char getEscapeChar() {
- return this.escapeChar;
- }
-
- // Resolver
- // -----------------------------------------------------------------------
- /**
- * Gets the StringLookup that is used to lookup variables.
- *
- * @return The StringLookup
- */
- public StringLookup getStringLookup() {
- return this.variableResolver;
- }
-
- // Variable Default Value Delimiter
- // -----------------------------------------------------------------------
- /**
- * Gets the variable default value delimiter matcher currently in use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the variable name and the
- * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default
- * value delimiter matches.
- * </p>
- * <p>
- * If it returns null, then the variable default value resolution is disabled.
- *
- * @return The variable default value delimiter matcher in use, may be null
- */
- public StringMatcher getValueDelimiterMatcher() {
- return valueDelimiterMatcher;
- }
-
- // Prefix
- // -----------------------------------------------------------------------
- /**
- * Gets the variable prefix matcher currently in use.
- * <p>
- * The variable prefix is the character or characters that identify the start of a variable. This prefix is
- * expressed in terms of a matcher allowing advanced prefix matches.
- * </p>
- *
- * @return The prefix matcher in use
- */
- public StringMatcher getVariablePrefixMatcher() {
- return prefixMatcher;
- }
-
- // Suffix
- // -----------------------------------------------------------------------
- /**
- * Gets the variable suffix matcher currently in use.
- * <p>
- * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed
- * in terms of a matcher allowing advanced suffix matches.
- * </p>
- *
- * @return The suffix matcher in use
- */
- public StringMatcher getVariableSuffixMatcher() {
- return suffixMatcher;
- }
-
- /**
- * Returns a flag whether substitution is disabled in variable values.If set to <b>true</b>, the values of variables
- * can contain other variables will not be processed and substituted original variable is evaluated, e.g.
- *
- * <pre>
- * Map<String, String> valuesMap = new HashMap<>();
- * valuesMap.put("name", "Douglas ${surname}");
- * valuesMap.put("surname", "Crockford");
- * String templateString = "Hi ${name}";
- * StrSubstitutor sub = new StrSubstitutor(valuesMap);
- * String resolvedString = sub.replace(templateString);
- * </pre>
- *
- * yielding:
- *
- * <pre>
- * Hi Douglas ${surname}
- * </pre>
- *
- * @return The substitution in variable values flag
- */
- public boolean isDisableSubstitutionInValues() {
- return disableSubstitutionInValues;
- }
-
- // Substitution support in variable names
- // -----------------------------------------------------------------------
- /**
- * Returns a flag whether substitution is done in variable names.
- *
- * @return The substitution in variable names flag
- */
- public boolean isEnableSubstitutionInVariables() {
- return enableSubstitutionInVariables;
- }
-
- /**
- * Returns a flag whether exception can be thrown upon undefined variable.
- *
- * @return The fail on undefined variable flag
- */
- public boolean isEnableUndefinedVariableException() {
- return enableUndefinedVariableException;
- }
-
- /**
- * Returns the flag controlling whether escapes are preserved during substitution.
- *
- * @return The preserve escape flag
- */
- public boolean isPreserveEscapes() {
- return preserveEscapes;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * array as a template. The array is not altered by this method.
- *
- * @param source the character array to replace in, not altered, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final char[] source) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(source.length).append(source);
- substitute(buf, 0, source.length);
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * array as a template. The array is not altered by this method.
- * <p>
- * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not
- * returned.
- * </p>
- *
- * @param source the character array to replace in, not altered, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final char[] source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source as
- * a template. The source is not altered by this method.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final CharSequence source) {
- if (source == null) {
- return null;
- }
- return replace(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source as
- * a template. The source is not altered by this method.
- * <p>
- * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not
- * returned.
- * </p>
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the array, must be valid
- * @param length the length within the array to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final CharSequence source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source.toString(), offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables in the given source object with their matching values from the
- * resolver. The input source object is converted to a string using {@code toString} and is not altered.
- *
- * @param source the source to replace in, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
- */
- public String replace(final Object source) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder().append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * string as a template.
- *
- * @param source the string to replace in, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final String source) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(source);
- if (!substitute(buf, 0, source.length())) {
- return source;
- }
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * string as a template.
- * <p>
- * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not
- * returned.
- * </p>
- *
- * @param source the string to replace in, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final String source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return source.substring(offset, offset + length);
- }
- return buf.toString();
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * buffer as a template. The buffer is not altered by this method.
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final StringBuffer source) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(source.length()).append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * buffer as a template. The buffer is not altered by this method.
- * <p>
- * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not
- * returned.
- * </p>
- *
- * @param source the buffer to use as a template, not changed, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final StringBuffer source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * builder as a template. The builder is not altered by this method.
- *
- * @param source the builder to use as a template, not changed, null returns null
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final TextStringBuilder source) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(source.length()).append(source);
- substitute(buf, 0, buf.length());
- return buf.toString();
- }
-
- /**
- * Replaces all the occurrences of variables with their matching values from the resolver using the given source
- * builder as a template. The builder is not altered by this method.
- * <p>
- * Only the specified portion of the builder will be processed. The rest of the builder is not processed, and is not
- * returned.
- * </p>
- *
- * @param source the builder to use as a template, not changed, null returns null
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return The result of the replace operation
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public String replace(final TextStringBuilder source, final int offset, final int length) {
- if (source == null) {
- return null;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- substitute(buf, 0, length);
- return buf.toString();
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source buffer with their matching values from the
- * resolver. The buffer is updated with the result.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
- */
- public boolean replaceIn(final StringBuffer source) {
- if (source == null) {
- return false;
- }
- return replaceIn(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source buffer with their matching values from the
- * resolver. The buffer is updated with the result.
- * <p>
- * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is
- * not deleted.
- * </p>
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return false;
- }
- source.replace(offset, offset + length, buf.toString());
- return true;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source buffer with their matching values from the
- * resolver. The buffer is updated with the result.
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @return true if altered
- */
- public boolean replaceIn(final StringBuilder source) {
- if (source == null) {
- return false;
- }
- return replaceIn(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source builder with their matching values from the
- * resolver. The builder is updated with the result.
- * <p>
- * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is
- * not deleted.
- * </p>
- *
- * @param source the buffer to replace in, updated, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
- if (!substitute(buf, 0, length)) {
- return false;
- }
- source.replace(offset, offset + length, buf.toString());
- return true;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Replaces all the occurrences of variables within the given source builder with their matching values from the
- * resolver.
- *
- * @param source the builder to replace in, updated, null returns zero
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public boolean replaceIn(final TextStringBuilder source) {
- if (source == null) {
- return false;
- }
- return substitute(source, 0, source.length());
- }
-
- /**
- * Replaces all the occurrences of variables within the given source builder with their matching values from the
- * resolver.
- * <p>
- * Only the specified portion of the builder will be processed. The rest of the builder is not processed, but it is
- * not deleted.
- * </p>
- *
- * @param source the builder to replace in, null returns zero
- * @param offset the start offset within the source, must be valid
- * @param length the length within the source to be processed, must be valid
- * @return true if altered
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- public boolean replaceIn(final TextStringBuilder source, final int offset, final int length) {
- if (source == null) {
- return false;
- }
- return substitute(source, offset, length);
- }
-
- /**
- * Internal method that resolves the value of a variable.
- * <p>
- * Most users of this class do not need to call this method. This method is called automatically by the substitution
- * process.
- * </p>
- * <p>
- * Writers of subclasses can override this method if they need to alter how each substitution occurs. The method is
- * passed the variable's name and must return the corresponding value. This implementation uses the
- * {@link #getStringLookup()} with the variable's name as the key.
- * </p>
- *
- * @param variableName the name of the variable, not null
- * @param buf the buffer where the substitution is occurring, not null
- * @param startPos the start position of the variable including the prefix, valid
- * @param endPos the end position of the variable including the suffix, valid
- * @return The variable's value or <b>null</b> if the variable is unknown
- */
- protected String resolveVariable(final String variableName, final TextStringBuilder buf, final int startPos,
- final int endPos) {
- final StringLookup resolver = getStringLookup();
- if (resolver == null) {
- return null;
- }
- return resolver.lookup(variableName);
- }
-
- /**
- * Sets a flag whether substitution is done in variable values (recursive).
- *
- * @param disableSubstitutionInValues true if substitution in variable value are disabled
- * @return this, to enable chaining
- */
- public StringSubstitutor setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
- this.disableSubstitutionInValues = disableSubstitutionInValues;
- return this;
- }
-
- /**
- * Sets a flag whether substitution is done in variable names. If set to <b>true</b>, the names of variables can
- * contain other variables which are processed first before the original variable is evaluated, e.g.
- * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
- *
- * @param enableSubstitutionInVariables the new value of the flag
- * @return this, to enable chaining
- */
- public StringSubstitutor setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) {
- this.enableSubstitutionInVariables = enableSubstitutionInVariables;
- return this;
- }
-
- /**
- * Sets a flag whether exception should be thrown if any variable is undefined.
- *
- * @param failOnUndefinedVariable true if exception should be thrown on undefined variable
- * @return this, to enable chaining
- */
- public StringSubstitutor setEnableUndefinedVariableException(final boolean failOnUndefinedVariable) {
- this.enableUndefinedVariableException = failOnUndefinedVariable;
- return this;
- }
-
- /**
- * Sets the escape character. If this character is placed before a variable reference in the source text, this
- * variable will be ignored.
- *
- * @param escapeCharacter the escape character (0 for disabling escaping)
- * @return this, to enable chaining
- */
- public StringSubstitutor setEscapeChar(final char escapeCharacter) {
- this.escapeChar = escapeCharacter;
- return this;
- }
-
- /**
- * Sets a flag controlling whether escapes are preserved during substitution. If set to <b>true</b>, the escape
- * character is retained during substitution (e.g. {@code $${this-is-escaped}} remains
- * {@code $${this-is-escaped}}). If set to <b>false</b>, the escape character is removed during substitution
- * (e.g. {@code $${this-is-escaped}} becomes {@code ${this-is-escaped}}). The default value is
- * <b>false</b>
- *
- * @param preserveEscapes true if escapes are to be preserved
- * @return this, to enable chaining
- */
- public StringSubstitutor setPreserveEscapes(final boolean preserveEscapes) {
- this.preserveEscapes = preserveEscapes;
- return this;
- }
-
- /**
- * Sets the variable default value delimiter to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the variable name and the
- * variable default value. This method allows a single character variable default value delimiter to be easily set.
- * </p>
- *
- * @param valueDelimiter the variable default value delimiter character to use
- * @return this, to enable chaining
- */
- public StringSubstitutor setValueDelimiter(final char valueDelimiter) {
- return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(valueDelimiter));
- }
-
- /**
- * Sets the variable default value delimiter to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the variable name and the
- * variable default value. This method allows a string variable default value delimiter to be easily set.
- * </p>
- * <p>
- * If the {@code valueDelimiter} is null or empty string, then the variable default value resolution becomes
- * disabled.
- * </p>
- *
- * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
- * @return this, to enable chaining
- */
- public StringSubstitutor setValueDelimiter(final String valueDelimiter) {
- if (valueDelimiter == null || valueDelimiter.length() == 0) {
- setValueDelimiterMatcher(null);
- return this;
- }
- return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.stringMatcher(valueDelimiter));
- }
-
- /**
- * Sets the variable default value delimiter matcher to use.
- * <p>
- * The variable default value delimiter is the character or characters that delimite the variable name and the
- * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default
- * value delimiter matches.
- * </p>
- * <p>
- * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution becomes disabled.
- * </p>
- *
- * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
- * @return this, to enable chaining
- */
- public StringSubstitutor setValueDelimiterMatcher(final StringMatcher valueDelimiterMatcher) {
- this.valueDelimiterMatcher = valueDelimiterMatcher;
- return this;
- }
-
- /**
- * Sets the variable prefix to use.
- * <p>
- * The variable prefix is the character or characters that identify the start of a variable. This method allows a
- * single character prefix to be easily set.
- * </p>
- *
- * @param prefix the prefix character to use
- * @return this, to enable chaining
- */
- public StringSubstitutor setVariablePrefix(final char prefix) {
- return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.charMatcher(prefix));
- }
-
- /**
- * Sets the variable prefix to use.
- * <p>
- * The variable prefix is the character or characters that identify the start of a variable. This method allows a
- * string prefix to be easily set.
- * </p>
- *
- * @param prefix the prefix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix is null
- */
- public StringSubstitutor setVariablePrefix(final String prefix) {
- Validate.isTrue(prefix != null, "Variable prefix must not be null!");
- return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(prefix));
- }
-
- /**
- * Sets the variable prefix matcher currently in use.
- * <p>
- * The variable prefix is the character or characters that identify the start of a variable. This prefix is
- * expressed in terms of a matcher allowing advanced prefix matches.
- * </p>
- *
- * @param prefixMatcher the prefix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the prefix matcher is null
- */
- public StringSubstitutor setVariablePrefixMatcher(final StringMatcher prefixMatcher) {
- Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
- this.prefixMatcher = prefixMatcher;
- return this;
- }
-
- /**
- * Sets the VariableResolver that is used to lookup variables.
- *
- * @param variableResolver the VariableResolver
- * @return this, to enable chaining
- */
- public StringSubstitutor setVariableResolver(final StringLookup variableResolver) {
- this.variableResolver = variableResolver;
- return this;
- }
-
- /**
- * Sets the variable suffix to use.
- * <p>
- * The variable suffix is the character or characters that identify the end of a variable. This method allows a
- * single character suffix to be easily set.
- * </p>
- *
- * @param suffix the suffix character to use
- * @return this, to enable chaining
- */
- public StringSubstitutor setVariableSuffix(final char suffix) {
- return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.charMatcher(suffix));
- }
-
- /**
- * Sets the variable suffix to use.
- * <p>
- * The variable suffix is the character or characters that identify the end of a variable. This method allows a
- * string suffix to be easily set.
- * </p>
- *
- * @param suffix the suffix for variables, not null
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix is null
- */
- public StringSubstitutor setVariableSuffix(final String suffix) {
- Validate.isTrue(suffix != null, "Variable suffix must not be null!");
- return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(suffix));
- }
-
- /**
- * Sets the variable suffix matcher currently in use.
- * <p>
- * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed
- * in terms of a matcher allowing advanced suffix matches.
- * </p>
- *
- * @param suffixMatcher the suffix matcher to use, null ignored
- * @return this, to enable chaining
- * @throws IllegalArgumentException if the suffix matcher is null
- */
- public StringSubstitutor setVariableSuffixMatcher(final StringMatcher suffixMatcher) {
- Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
- this.suffixMatcher = suffixMatcher;
- return this;
- }
-
- // -----------------------------------------------------------------------
- /**
- * Internal method that substitutes the variables.
- * <p>
- * Most users of this class do not need to call this method. This method will be called automatically by another
- * (public) method.
- * </p>
- * <p>
- * Writers of subclasses can override this method if they need access to the substitution process at the start or
- * end.
- * </p>
- *
- * @param buf the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @return true if altered
- */
- protected boolean substitute(final TextStringBuilder buf, final int offset, final int length) {
- return substitute(buf, offset, length, null) > 0;
- }
-
- /**
- * Recursive handler for multiple levels of interpolation. This is the main interpolation method, which resolves the
- * values of all variable references contained in the passed in text.
- *
- * @param builder the string builder to substitute into, not null
- * @param offset the start offset within the builder, must be valid
- * @param length the length within the builder to be processed, must be valid
- * @param priorVariables the stack keeping track of the replaced variables, may be null
- * @return The length change that occurs, unless priorVariables is null when the int represents a boolean flag as to
- * whether any change occurred.
- * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
- */
- private int substitute(final TextStringBuilder builder, final int offset, final int length,
- List<String> priorVariables) {
- final StringMatcher prefixMatcher = getVariablePrefixMatcher();
- final StringMatcher suffixMatcher = getVariableSuffixMatcher();
- final char escapeCh = getEscapeChar();
- final StringMatcher valueDelimMatcher = getValueDelimiterMatcher();
- final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables();
- final boolean substitutionInValuesDisabled = isDisableSubstitutionInValues();
- final boolean undefinedVariableException = isEnableUndefinedVariableException();
-
- final boolean top = priorVariables == null;
- boolean altered = false;
- int lengthChange = 0;
- char[] chars = builder.buffer;
- int bufEnd = offset + length;
- int pos = offset;
- while (pos < bufEnd) {
- final int startMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd);
- if (startMatchLen == 0) {
- pos++;
- } else {
- // found variable start marker
- if (pos > offset && chars[pos - 1] == escapeCh) {
- // escaped
- if (preserveEscapes) {
- pos++;
- continue;
- }
- builder.deleteCharAt(pos - 1);
- chars = builder.buffer; // in case buffer was altered
- lengthChange--;
- altered = true;
- bufEnd--;
- } else {
- // find suffix
- final int startPos = pos;
- pos += startMatchLen;
- int endMatchLen = 0;
- int nestedVarCount = 0;
- while (pos < bufEnd) {
- if (substitutionInVariablesEnabled && prefixMatcher.isMatch(chars, pos, offset, bufEnd) != 0) {
- // found a nested variable start
- endMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd);
- nestedVarCount++;
- pos += endMatchLen;
- continue;
- }
-
- endMatchLen = suffixMatcher.isMatch(chars, pos, offset, bufEnd);
- if (endMatchLen == 0) {
- pos++;
- } else {
- // found variable end marker
- if (nestedVarCount == 0) {
- String varNameExpr = new String(chars, startPos + startMatchLen,
- pos - startPos - startMatchLen);
- if (substitutionInVariablesEnabled) {
- final TextStringBuilder bufName = new TextStringBuilder(varNameExpr);
- substitute(bufName, 0, bufName.length());
- varNameExpr = bufName.toString();
- }
- pos += endMatchLen;
- final int endPos = pos;
-
- String varName = varNameExpr;
- String varDefaultValue = null;
-
- if (valueDelimMatcher != null) {
- final char[] varNameExprChars = varNameExpr.toCharArray();
- int valueDelimiterMatchLen = 0;
- for (int i = 0; i < varNameExprChars.length; i++) {
- // if there's any nested variable when nested variable substitution disabled,
- // then stop resolving name and default value.
- if (!substitutionInVariablesEnabled && prefixMatcher.isMatch(varNameExprChars,
- i, i, varNameExprChars.length) != 0) {
- break;
- }
- if (valueDelimMatcher.isMatch(varNameExprChars, i, 0,
- varNameExprChars.length) != 0) {
- valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i, 0,
- varNameExprChars.length);
- varName = varNameExpr.substring(0, i);
- varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
- break;
- }
- }
- }
-
- // on the first call initialize priorVariables
- if (priorVariables == null) {
- priorVariables = new ArrayList<>();
- priorVariables.add(new String(chars, offset, length));
- }
-
- // handle cyclic substitution
- checkCyclicSubstitution(varName, priorVariables);
- priorVariables.add(varName);
-
- // resolve the variable
- String varValue = resolveVariable(varName, builder, startPos, endPos);
- if (varValue == null) {
- varValue = varDefaultValue;
- }
- if (varValue != null) {
- final int varLen = varValue.length();
- builder.replace(startPos, endPos, varValue);
- altered = true;
- int change = 0;
- if (!substitutionInValuesDisabled) { // recursive replace
- change = substitute(builder, startPos, varLen, priorVariables);
- }
- change = change + varLen - (endPos - startPos);
- pos += change;
- bufEnd += change;
- lengthChange += change;
- chars = builder.buffer; // in case buffer was altered
- } else if (undefinedVariableException) {
- throw new IllegalArgumentException(String.format(
- "Cannot resolve variable '%s' (enableSubstitutionInVariables=%s).", varName,
- enableSubstitutionInVariables));
- }
-
- // remove variable from the cyclic stack
- priorVariables.remove(priorVariables.size() - 1);
- break;
- }
- nestedVarCount--;
- pos += endMatchLen;
- }
- }
- }
- }
- }
- if (top) {
- return altered ? 1 : 0;
- }
- return lengthChange;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text;
+
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+import org.apache.commons.lang3.Validate;
+import org.apache.commons.text.lookup.StringLookup;
+import org.apache.commons.text.lookup.StringLookupFactory;
+import org.apache.commons.text.matcher.StringMatcher;
+import org.apache.commons.text.matcher.StringMatcherFactory;
+
+/**
+ * Substitutes variables within a string by values.
+ * <p>
+ * This class takes a piece of text and substitutes all the variables within it. The default definition of a variable is
+ * {@code ${variableName}}. The prefix and suffix can be changed via constructors and set methods.
+ * </p>
+ * <p>
+ * Variable values are typically resolved from a map, but could also be resolved from system properties, or by supplying
+ * a custom variable resolver.
+ * <p>
+ * The simplest example is to use this class to replace Java System properties. For example:
+ * </p>
+ *
+ * <pre>
+ * StringSubstitutor
+ * .replaceSystemProperties("You are running with java.version = ${java.version} and os.name = ${os.name}.");
+ * </pre>
+ *
+ * <h2>Using a Custom Map</h2>
+ * <p>
+ * Typical usage of this class follows the following pattern: First an instance is created and initialized with the map
+ * that contains the values for the available variables. If a prefix and/or suffix for variables should be used other
+ * than the default ones, the appropriate settings can be performed. After that the {@code replace()} method can be
+ * called passing in the source text for interpolation. In the returned text all variable references (as long as their
+ * values are known) will be resolved. The following example demonstrates this:
+ * </p>
+ *
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("animal", "quick brown fox");
+ * valuesMap.put("target", "lazy dog");
+ * String templateString = "The ${animal} jumped over the ${target}.";
+ * StringSubstitutor sub = new StringSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ *
+ * <p>
+ * yielding:
+ * </p>
+ *
+ * <pre>
+ * The quick brown fox jumped over the lazy dog.
+ * </pre>
+ *
+ * <h2>Providing Default Values</h2>
+ * <p>
+ * This class lets you set a default value for unresolved variables. The default value for a variable can be appended to
+ * the variable name after the variable default value delimiter. The default value of the variable default value
+ * delimiter is ':-', as in bash and other *nix shells, as those are arguably where the default ${} delimiter set
+ * originated. The variable default value delimiter can be manually set by calling
+ * {@link #setValueDelimiterMatcher(StringMatcher)}, {@link #setValueDelimiter(char)} or
+ * {@link #setValueDelimiter(String)}. The following shows an example with variable default value settings:
+ * </p>
+ *
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("animal", "quick brown fox");
+ * valuesMap.put("target", "lazy dog");
+ * String templateString = "The ${animal} jumped over the ${target}. ${undefined.number:-1234567890}.";
+ * StringSubstitutor sub = new StringSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ *
+ * <p>
+ * yielding:
+ * </p>
+ *
+ * <pre>
+ * The quick brown fox jumped over the lazy dog. 1234567890.
+ * </pre>
+ *
+ * <p>
+ * {@code StringSubstitutor} supports throwing exceptions for unresolved variables, you enable this by setting calling
+ * {@link #setEnableUndefinedVariableException(boolean)} with {@code true}.
+ * </p>
+ *
+ * <h2>Reusing Instances</h2>
+ * <p>
+ * In addition to this usage pattern there are some static convenience methods that cover the most common use cases.
+ * These methods can be used without the need of manually creating an instance. However if multiple replace operations
+ * are to be performed, creating and reusing an instance of this class will be more efficient.
+ * </p>
+ * <p>
+ * This class is <b>not</b> thread safe.
+ * </p>
+ *
+ * <h2>Using Interpolation</h2>
+ * <p>
+ * The default interpolator let's you use string lookups like:
+ * </p>
+ *
+ * <pre>
+final StringSubstitutor interpolator = StringSubstitutor.createInterpolator();
+interpolator.setEnableSubstitutionInVariables(true); // Allows for nested $'s.
+final String text = interpolator.replace(
+ "Base64 Decoder: ${base64Decoder:SGVsbG9Xb3JsZCE=}\n" +
+ "Base64 Encoder: ${base64Encoder:HelloWorld!}\n" +
+ "Java Constant: ${const:java.awt.event.KeyEvent.VK_ESCAPE}\n" +
+ "Date: ${date:yyyy-MM-dd}\n" +
+ "DNS: ${dns:address|apache.org}\n" +
+ "Environment Variable: ${env:USERNAME}\n" +
+ "File Content: ${file:UTF-8:src/test/resources/document.properties}\n" +
+ "Java: ${java:version}\n" +
+ "Localhost: ${localhost:canonical-name}\n" +
+ "Properties File: ${properties:src/test/resources/document.properties::mykey}\n" +
+ "Resource Bundle: ${resourceBundle:org.example.testResourceBundleLookup:mykey}\n" +
+ "Script: ${script:javascript:3 + 4}\n" +
+ "System Property: ${sys:user.dir}\n" +
+ "URL Decoder: ${urlDecoder:Hello%20World%21}\n" +
+ "URL Encoder: ${urlEncoder:Hello World!}\n" +
+ "URL Content (HTTP): ${url:UTF-8:http://www.apache.org}\n" +
+ "URL Content (HTTPS): ${url:UTF-8:https://www.apache.org}\n" +
+ "URL Content (File): ${url:UTF-8:file:///${sys:user.dir}/src/test/resources/document.properties}\n" +
+ "XML XPath: ${xml:src/test/resources/document.xml:/root/path/to/node}\n"
+);
+ * </pre>
+ * <p>
+ * For documentation of each lookup, see {@link StringLookupFactory}.
+ * </p>
+ *
+ * <h2>Using Recursive Variable Replacement</h2>
+ * <p>
+ * Variable replacement works in a recursive way. Thus, if a variable value contains a variable then that variable will
+ * also be replaced. Cyclic replacements are detected and will cause an exception to be thrown.
+ * </p>
+ * <p>
+ * Sometimes the interpolation's result must contain a variable prefix. As an example take the following source text:
+ * </p>
+ *
+ * <pre>
+ * The variable ${${name}} must be used.
+ * </pre>
+ *
+ * <p>
+ * Here only the variable's name referred to in the text should be replaced resulting in the text (assuming that the
+ * value of the {@code name} variable is {@code x}):
+ * </p>
+ *
+ * <pre>
+ * The variable ${x} must be used.
+ * </pre>
+ *
+ * <p>
+ * To achieve this effect there are two possibilities: Either set a different prefix and suffix for variables which do
+ * not conflict with the result text you want to produce. The other possibility is to use the escape character, by
+ * default '$'. If this character is placed before a variable reference, this reference is ignored and won't be
+ * replaced. For example:
+ * </p>
+ *
+ * <pre>
+ * The variable $${${name}} must be used.
+ * </pre>
+ * <p>
+ * In some complex scenarios you might even want to perform substitution in the names of variables, for instance
+ * </p>
+ *
+ * <pre>
+ * ${jre-${java.specification.version}}
+ * </pre>
+ *
+ * <p>
+ * {@code StringSubstitutor} supports this recursive substitution in variable names, but it has to be enabled explicitly
+ * by calling {@link #setEnableSubstitutionInVariables(boolean)} with {@code true}.
+ * </p>
+ *
+ * @since 1.3
+ */
+public class StringSubstitutor {
+
+ /**
+ * The default variable default separator.
+ *
+ * @since 1.5.
+ */
+ public static final String DEFAULT_VAR_DEFAULT = ":-";
+
+ /**
+ * The default variable end separator.
+ *
+ * @since 1.5.
+ */
+ public static final String DEFAULT_VAR_END = "}";
+
+ /**
+ * The default variable start separator.
+ *
+ * @since 1.5.
+ */
+ public static final String DEFAULT_VAR_START = "${";
+
+ /**
+ * Constant for the default escape character.
+ */
+ public static final char DEFAULT_ESCAPE = '$';
+
+ /**
+ * Constant for the default variable prefix.
+ */
+ public static final StringMatcher DEFAULT_PREFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_START);
+
+ /**
+ * Constant for the default variable suffix.
+ */
+ public static final StringMatcher DEFAULT_SUFFIX = StringMatcherFactory.INSTANCE.stringMatcher(DEFAULT_VAR_END);
+
+ /**
+ * Constant for the default value delimiter of a variable.
+ */
+ public static final StringMatcher DEFAULT_VALUE_DELIMITER = StringMatcherFactory.INSTANCE
+ .stringMatcher(DEFAULT_VAR_DEFAULT);
+
+ /**
+ * Creates a new instance using the interpolator string lookup
+ * {@link StringLookupFactory#interpolatorStringLookup()}.
+ * <p>
+ * This StringSubstitutor lets you perform substituions like:
+ * </p>
+ *
+ * <pre>
+ * StringSubstitutor.createInterpolator()
+ * .replace("OS name: ${sys:os.name}, " + "3 + 4 = ${script:javascript:3 + 4}");
+ * </pre>
+ *
+ * @return a new instance using the interpolator string lookup.
+ * @see StringLookupFactory#interpolatorStringLookup()
+ * @since 1.8
+ */
+ public static StringSubstitutor createInterpolator() {
+ return new StringSubstitutor(StringLookupFactory.INSTANCE.interpolatorStringLookup());
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching values from the map.
+ *
+ * @param <V> the type of the values in the map
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueMap the map with the values, may be null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ */
+ public static <V> String replace(final Object source, final Map<String, V> valueMap) {
+ return new StringSubstitutor(valueMap).replace(source);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching values from the map.
+ * This method allows to specify a custom variable prefix and suffix
+ *
+ * @param <V> the type of the values in the map
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueMap the map with the values, may be null
+ * @param prefix the prefix of variables, not null
+ * @param suffix the suffix of variables, not null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ */
+ public static <V> String replace(final Object source, final Map<String, V> valueMap, final String prefix,
+ final String suffix) {
+ return new StringSubstitutor(valueMap, prefix, suffix).replace(source);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching values from the
+ * properties.
+ *
+ * @param source the source text containing the variables to substitute, null returns null
+ * @param valueProperties the properties with values, may be null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ */
+ public static String replace(final Object source, final Properties valueProperties) {
+ if (valueProperties == null) {
+ return source.toString();
+ }
+ final Map<String, String> valueMap = new HashMap<>();
+ final Enumeration<?> propNames = valueProperties.propertyNames();
+ while (propNames.hasMoreElements()) {
+ final String propName = (String) propNames.nextElement();
+ final String propValue = valueProperties.getProperty(propName);
+ valueMap.put(propName, propValue);
+ }
+ return StringSubstitutor.replace(source, valueMap);
+ }
+
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching values from the system
+ * properties.
+ *
+ * @param source the source text containing the variables to substitute, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ */
+ public static String replaceSystemProperties(final Object source) {
+ return new StringSubstitutor(StringLookupFactory.INSTANCE.systemPropertyStringLookup()).replace(source);
+ }
+
+ /**
+ * Stores the escape character.
+ */
+ private char escapeChar;
+
+ /**
+ * Stores the variable prefix.
+ */
+ private StringMatcher prefixMatcher;
+
+ /**
+ * Stores the variable suffix.
+ */
+ private StringMatcher suffixMatcher;
+
+ /**
+ * Stores the default variable value delimiter.
+ */
+ private StringMatcher valueDelimiterMatcher;
+
+ /**
+ * Variable resolution is delegated to an implementor of {@link StringLookup}.
+ */
+ private StringLookup variableResolver;
+
+ /**
+ * The flag whether substitution in variable names is enabled.
+ */
+ private boolean enableSubstitutionInVariables;
+
+ /**
+ * Whether escapes should be preserved. Default is false;
+ */
+ private boolean preserveEscapes;
+
+ /**
+ * The flag whether substitution in variable values is disabled.
+ */
+ private boolean disableSubstitutionInValues;
+
+ /**
+ * The flag whether exception should be thrown on undefined variable.
+ */
+ private boolean enableUndefinedVariableException;
+
+ // -----------------------------------------------------------------------
+ /**
+ * Creates a new instance with defaults for variable prefix and suffix and the escaping character.
+ */
+ public StringSubstitutor() {
+ this((StringLookup) null, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it. Uses defaults for variable prefix and suffix and the escaping
+ * character.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ */
+ public <V> StringSubstitutor(final Map<String, V> valueMap) {
+ this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it. Uses a default escaping character.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix) {
+ this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
+ final char escape) {
+ this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param <V> the type of the values in the map
+ * @param valueMap the map with the variables' values, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiter the variable default value delimiter, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public <V> StringSubstitutor(final Map<String, V> valueMap, final String prefix, final String suffix,
+ final char escape, final String valueDelimiter) {
+ this(StringLookupFactory.INSTANCE.mapStringLookup(valueMap), prefix, suffix, escape, valueDelimiter);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ */
+ public StringSubstitutor(final StringLookup variableResolver) {
+ this(variableResolver, DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ESCAPE);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
+ final char escape) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefix(prefix);
+ this.setVariableSuffix(suffix);
+ this.setEscapeChar(escape);
+ this.setValueDelimiterMatcher(DEFAULT_VALUE_DELIMITER);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefix the prefix for variables, not null
+ * @param suffix the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiter the variable default value delimiter string, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StringSubstitutor(final StringLookup variableResolver, final String prefix, final String suffix,
+ final char escape, final String valueDelimiter) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefix(prefix);
+ this.setVariableSuffix(suffix);
+ this.setEscapeChar(escape);
+ this.setValueDelimiter(valueDelimiter);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefixMatcher the prefix for variables, not null
+ * @param suffixMatcher the suffix for variables, not null
+ * @param escape the escape character
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher,
+ final StringMatcher suffixMatcher, final char escape) {
+ this(variableResolver, prefixMatcher, suffixMatcher, escape, DEFAULT_VALUE_DELIMITER);
+ }
+
+ /**
+ * Creates a new instance and initializes it.
+ *
+ * @param variableResolver the variable resolver, may be null
+ * @param prefixMatcher the prefix for variables, not null
+ * @param suffixMatcher the suffix for variables, not null
+ * @param escape the escape character
+ * @param valueDelimiterMatcher the variable default value delimiter matcher, may be null
+ * @throws IllegalArgumentException if the prefix or suffix is null
+ */
+ public StringSubstitutor(final StringLookup variableResolver, final StringMatcher prefixMatcher,
+ final StringMatcher suffixMatcher, final char escape, final StringMatcher valueDelimiterMatcher) {
+ this.setVariableResolver(variableResolver);
+ this.setVariablePrefixMatcher(prefixMatcher);
+ this.setVariableSuffixMatcher(suffixMatcher);
+ this.setEscapeChar(escape);
+ this.setValueDelimiterMatcher(valueDelimiterMatcher);
+ }
+
+ /**
+ * Checks if the specified variable is already in the stack (list) of variables.
+ *
+ * @param varName the variable name to check
+ * @param priorVariables the list of prior variables
+ */
+ private void checkCyclicSubstitution(final String varName, final List<String> priorVariables) {
+ if (!priorVariables.contains(varName)) {
+ return;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(256);
+ buf.append("Infinite loop in property interpolation of ");
+ buf.append(priorVariables.remove(0));
+ buf.append(": ");
+ buf.appendWithSeparators(priorVariables, "->");
+ throw new IllegalStateException(buf.toString());
+ }
+
+ // Escape
+ // -----------------------------------------------------------------------
+ /**
+ * Returns the escape character.
+ *
+ * @return The character used for escaping variable references
+ */
+ public char getEscapeChar() {
+ return this.escapeChar;
+ }
+
+ // Resolver
+ // -----------------------------------------------------------------------
+ /**
+ * Gets the StringLookup that is used to lookup variables.
+ *
+ * @return The StringLookup
+ */
+ public StringLookup getStringLookup() {
+ return this.variableResolver;
+ }
+
+ // Variable Default Value Delimiter
+ // -----------------------------------------------------------------------
+ /**
+ * Gets the variable default value delimiter matcher currently in use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the variable name and the
+ * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default
+ * value delimiter matches.
+ * </p>
+ * <p>
+ * If it returns null, then the variable default value resolution is disabled.
+ *
+ * @return The variable default value delimiter matcher in use, may be null
+ */
+ public StringMatcher getValueDelimiterMatcher() {
+ return valueDelimiterMatcher;
+ }
+
+ // Prefix
+ // -----------------------------------------------------------------------
+ /**
+ * Gets the variable prefix matcher currently in use.
+ * <p>
+ * The variable prefix is the character or characters that identify the start of a variable. This prefix is
+ * expressed in terms of a matcher allowing advanced prefix matches.
+ * </p>
+ *
+ * @return The prefix matcher in use
+ */
+ public StringMatcher getVariablePrefixMatcher() {
+ return prefixMatcher;
+ }
+
+ // Suffix
+ // -----------------------------------------------------------------------
+ /**
+ * Gets the variable suffix matcher currently in use.
+ * <p>
+ * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed
+ * in terms of a matcher allowing advanced suffix matches.
+ * </p>
+ *
+ * @return The suffix matcher in use
+ */
+ public StringMatcher getVariableSuffixMatcher() {
+ return suffixMatcher;
+ }
+
+ /**
+ * Returns a flag whether substitution is disabled in variable values.If set to <b>true</b>, the values of variables
+ * can contain other variables will not be processed and substituted original variable is evaluated, e.g.
+ *
+ * <pre>
+ * Map<String, String> valuesMap = new HashMap<>();
+ * valuesMap.put("name", "Douglas ${surname}");
+ * valuesMap.put("surname", "Crockford");
+ * String templateString = "Hi ${name}";
+ * StrSubstitutor sub = new StrSubstitutor(valuesMap);
+ * String resolvedString = sub.replace(templateString);
+ * </pre>
+ *
+ * yielding:
+ *
+ * <pre>
+ * Hi Douglas ${surname}
+ * </pre>
+ *
+ * @return The substitution in variable values flag
+ */
+ public boolean isDisableSubstitutionInValues() {
+ return disableSubstitutionInValues;
+ }
+
+ // Substitution support in variable names
+ // -----------------------------------------------------------------------
+ /**
+ * Returns a flag whether substitution is done in variable names.
+ *
+ * @return The substitution in variable names flag
+ */
+ public boolean isEnableSubstitutionInVariables() {
+ return enableSubstitutionInVariables;
+ }
+
+ /**
+ * Returns a flag whether exception can be thrown upon undefined variable.
+ *
+ * @return The fail on undefined variable flag
+ */
+ public boolean isEnableUndefinedVariableException() {
+ return enableUndefinedVariableException;
+ }
+
+ /**
+ * Returns the flag controlling whether escapes are preserved during substitution.
+ *
+ * @return The preserve escape flag
+ */
+ public boolean isPreserveEscapes() {
+ return preserveEscapes;
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * array as a template. The array is not altered by this method.
+ *
+ * @param source the character array to replace in, not altered, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final char[] source) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(source.length).append(source);
+ substitute(buf, 0, source.length);
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * array as a template. The array is not altered by this method.
+ * <p>
+ * Only the specified portion of the array will be processed. The rest of the array is not processed, and is not
+ * returned.
+ * </p>
+ *
+ * @param source the character array to replace in, not altered, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final char[] source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source as
+ * a template. The source is not altered by this method.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final CharSequence source) {
+ if (source == null) {
+ return null;
+ }
+ return replace(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source as
+ * a template. The source is not altered by this method.
+ * <p>
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not
+ * returned.
+ * </p>
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @param offset the start offset within the array, must be valid
+ * @param length the length within the array to be processed, must be valid
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final CharSequence source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source.toString(), offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables in the given source object with their matching values from the
+ * resolver. The input source object is converted to a string using {@code toString} and is not altered.
+ *
+ * @param source the source to replace in, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if a variable is not found and enableUndefinedVariableException is true
+ */
+ public String replace(final Object source) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder().append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * string as a template.
+ *
+ * @param source the string to replace in, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final String source) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(source);
+ if (!substitute(buf, 0, source.length())) {
+ return source;
+ }
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * string as a template.
+ * <p>
+ * Only the specified portion of the string will be processed. The rest of the string is not processed, and is not
+ * returned.
+ * </p>
+ *
+ * @param source the string to replace in, null returns null
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final String source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return source.substring(offset, offset + length);
+ }
+ return buf.toString();
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * buffer as a template. The buffer is not altered by this method.
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final StringBuffer source) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(source.length()).append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * buffer as a template. The buffer is not altered by this method.
+ * <p>
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, and is not
+ * returned.
+ * </p>
+ *
+ * @param source the buffer to use as a template, not changed, null returns null
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final StringBuffer source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * builder as a template. The builder is not altered by this method.
+ *
+ * @param source the builder to use as a template, not changed, null returns null
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final TextStringBuilder source) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(source.length()).append(source);
+ substitute(buf, 0, buf.length());
+ return buf.toString();
+ }
+
+ /**
+ * Replaces all the occurrences of variables with their matching values from the resolver using the given source
+ * builder as a template. The builder is not altered by this method.
+ * <p>
+ * Only the specified portion of the builder will be processed. The rest of the builder is not processed, and is not
+ * returned.
+ * </p>
+ *
+ * @param source the builder to use as a template, not changed, null returns null
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return The result of the replace operation
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public String replace(final TextStringBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return null;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ substitute(buf, 0, length);
+ return buf.toString();
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the
+ * resolver. The buffer is updated with the result.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuffer source) {
+ if (source == null) {
+ return false;
+ }
+ return replaceIn(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the
+ * resolver. The buffer is updated with the result.
+ * <p>
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is
+ * not deleted.
+ * </p>
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return true if altered
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public boolean replaceIn(final StringBuffer source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return false;
+ }
+ source.replace(offset, offset + length, buf.toString());
+ return true;
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source buffer with their matching values from the
+ * resolver. The buffer is updated with the result.
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @return true if altered
+ */
+ public boolean replaceIn(final StringBuilder source) {
+ if (source == null) {
+ return false;
+ }
+ return replaceIn(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the
+ * resolver. The builder is updated with the result.
+ * <p>
+ * Only the specified portion of the buffer will be processed. The rest of the buffer is not processed, but it is
+ * not deleted.
+ * </p>
+ *
+ * @param source the buffer to replace in, updated, null returns zero
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return true if altered
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public boolean replaceIn(final StringBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ final TextStringBuilder buf = new TextStringBuilder(length).append(source, offset, length);
+ if (!substitute(buf, 0, length)) {
+ return false;
+ }
+ source.replace(offset, offset + length, buf.toString());
+ return true;
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the
+ * resolver.
+ *
+ * @param source the builder to replace in, updated, null returns zero
+ * @return true if altered
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public boolean replaceIn(final TextStringBuilder source) {
+ if (source == null) {
+ return false;
+ }
+ return substitute(source, 0, source.length());
+ }
+
+ /**
+ * Replaces all the occurrences of variables within the given source builder with their matching values from the
+ * resolver.
+ * <p>
+ * Only the specified portion of the builder will be processed. The rest of the builder is not processed, but it is
+ * not deleted.
+ * </p>
+ *
+ * @param source the builder to replace in, null returns zero
+ * @param offset the start offset within the source, must be valid
+ * @param length the length within the source to be processed, must be valid
+ * @return true if altered
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ public boolean replaceIn(final TextStringBuilder source, final int offset, final int length) {
+ if (source == null) {
+ return false;
+ }
+ return substitute(source, offset, length);
+ }
+
+ /**
+ * Internal method that resolves the value of a variable.
+ * <p>
+ * Most users of this class do not need to call this method. This method is called automatically by the substitution
+ * process.
+ * </p>
+ * <p>
+ * Writers of subclasses can override this method if they need to alter how each substitution occurs. The method is
+ * passed the variable's name and must return the corresponding value. This implementation uses the
+ * {@link #getStringLookup()} with the variable's name as the key.
+ * </p>
+ *
+ * @param variableName the name of the variable, not null
+ * @param buf the buffer where the substitution is occurring, not null
+ * @param startPos the start position of the variable including the prefix, valid
+ * @param endPos the end position of the variable including the suffix, valid
+ * @return The variable's value or <b>null</b> if the variable is unknown
+ */
+ protected String resolveVariable(final String variableName, final TextStringBuilder buf, final int startPos,
+ final int endPos) {
+ final StringLookup resolver = getStringLookup();
+ if (resolver == null) {
+ return null;
+ }
+ return resolver.lookup(variableName);
+ }
+
+ /**
+ * Sets a flag whether substitution is done in variable values (recursive).
+ *
+ * @param disableSubstitutionInValues true if substitution in variable value are disabled
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setDisableSubstitutionInValues(final boolean disableSubstitutionInValues) {
+ this.disableSubstitutionInValues = disableSubstitutionInValues;
+ return this;
+ }
+
+ /**
+ * Sets a flag whether substitution is done in variable names. If set to <b>true</b>, the names of variables can
+ * contain other variables which are processed first before the original variable is evaluated, e.g.
+ * {@code ${jre-${java.version}}}. The default value is <b>false</b>.
+ *
+ * @param enableSubstitutionInVariables the new value of the flag
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setEnableSubstitutionInVariables(final boolean enableSubstitutionInVariables) {
+ this.enableSubstitutionInVariables = enableSubstitutionInVariables;
+ return this;
+ }
+
+ /**
+ * Sets a flag whether exception should be thrown if any variable is undefined.
+ *
+ * @param failOnUndefinedVariable true if exception should be thrown on undefined variable
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setEnableUndefinedVariableException(final boolean failOnUndefinedVariable) {
+ this.enableUndefinedVariableException = failOnUndefinedVariable;
+ return this;
+ }
+
+ /**
+ * Sets the escape character. If this character is placed before a variable reference in the source text, this
+ * variable will be ignored.
+ *
+ * @param escapeCharacter the escape character (0 for disabling escaping)
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setEscapeChar(final char escapeCharacter) {
+ this.escapeChar = escapeCharacter;
+ return this;
+ }
+
+ /**
+ * Sets a flag controlling whether escapes are preserved during substitution. If set to <b>true</b>, the escape
+ * character is retained during substitution (e.g. {@code $${this-is-escaped}} remains
+ * {@code $${this-is-escaped}}). If set to <b>false</b>, the escape character is removed during substitution
+ * (e.g. {@code $${this-is-escaped}} becomes {@code ${this-is-escaped}}). The default value is
+ * <b>false</b>
+ *
+ * @param preserveEscapes true if escapes are to be preserved
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setPreserveEscapes(final boolean preserveEscapes) {
+ this.preserveEscapes = preserveEscapes;
+ return this;
+ }
+
+ /**
+ * Sets the variable default value delimiter to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the variable name and the
+ * variable default value. This method allows a single character variable default value delimiter to be easily set.
+ * </p>
+ *
+ * @param valueDelimiter the variable default value delimiter character to use
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setValueDelimiter(final char valueDelimiter) {
+ return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.charMatcher(valueDelimiter));
+ }
+
+ /**
+ * Sets the variable default value delimiter to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the variable name and the
+ * variable default value. This method allows a string variable default value delimiter to be easily set.
+ * </p>
+ * <p>
+ * If the {@code valueDelimiter} is null or empty string, then the variable default value resolution becomes
+ * disabled.
+ * </p>
+ *
+ * @param valueDelimiter the variable default value delimiter string to use, may be null or empty
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setValueDelimiter(final String valueDelimiter) {
+ if (valueDelimiter == null || valueDelimiter.length() == 0) {
+ setValueDelimiterMatcher(null);
+ return this;
+ }
+ return setValueDelimiterMatcher(StringMatcherFactory.INSTANCE.stringMatcher(valueDelimiter));
+ }
+
+ /**
+ * Sets the variable default value delimiter matcher to use.
+ * <p>
+ * The variable default value delimiter is the character or characters that delimite the variable name and the
+ * variable default value. This delimiter is expressed in terms of a matcher allowing advanced variable default
+ * value delimiter matches.
+ * </p>
+ * <p>
+ * If the {@code valueDelimiterMatcher} is null, then the variable default value resolution becomes disabled.
+ * </p>
+ *
+ * @param valueDelimiterMatcher variable default value delimiter matcher to use, may be null
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setValueDelimiterMatcher(final StringMatcher valueDelimiterMatcher) {
+ this.valueDelimiterMatcher = valueDelimiterMatcher;
+ return this;
+ }
+
+ /**
+ * Sets the variable prefix to use.
+ * <p>
+ * The variable prefix is the character or characters that identify the start of a variable. This method allows a
+ * single character prefix to be easily set.
+ * </p>
+ *
+ * @param prefix the prefix character to use
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setVariablePrefix(final char prefix) {
+ return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.charMatcher(prefix));
+ }
+
+ /**
+ * Sets the variable prefix to use.
+ * <p>
+ * The variable prefix is the character or characters that identify the start of a variable. This method allows a
+ * string prefix to be easily set.
+ * </p>
+ *
+ * @param prefix the prefix for variables, not null
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the prefix is null
+ */
+ public StringSubstitutor setVariablePrefix(final String prefix) {
+ Validate.isTrue(prefix != null, "Variable prefix must not be null!");
+ return setVariablePrefixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(prefix));
+ }
+
+ /**
+ * Sets the variable prefix matcher currently in use.
+ * <p>
+ * The variable prefix is the character or characters that identify the start of a variable. This prefix is
+ * expressed in terms of a matcher allowing advanced prefix matches.
+ * </p>
+ *
+ * @param prefixMatcher the prefix matcher to use, null ignored
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the prefix matcher is null
+ */
+ public StringSubstitutor setVariablePrefixMatcher(final StringMatcher prefixMatcher) {
+ Validate.isTrue(prefixMatcher != null, "Variable prefix matcher must not be null!");
+ this.prefixMatcher = prefixMatcher;
+ return this;
+ }
+
+ /**
+ * Sets the VariableResolver that is used to lookup variables.
+ *
+ * @param variableResolver the VariableResolver
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setVariableResolver(final StringLookup variableResolver) {
+ this.variableResolver = variableResolver;
+ return this;
+ }
+
+ /**
+ * Sets the variable suffix to use.
+ * <p>
+ * The variable suffix is the character or characters that identify the end of a variable. This method allows a
+ * single character suffix to be easily set.
+ * </p>
+ *
+ * @param suffix the suffix character to use
+ * @return this, to enable chaining
+ */
+ public StringSubstitutor setVariableSuffix(final char suffix) {
+ return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.charMatcher(suffix));
+ }
+
+ /**
+ * Sets the variable suffix to use.
+ * <p>
+ * The variable suffix is the character or characters that identify the end of a variable. This method allows a
+ * string suffix to be easily set.
+ * </p>
+ *
+ * @param suffix the suffix for variables, not null
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the suffix is null
+ */
+ public StringSubstitutor setVariableSuffix(final String suffix) {
+ Validate.isTrue(suffix != null, "Variable suffix must not be null!");
+ return setVariableSuffixMatcher(StringMatcherFactory.INSTANCE.stringMatcher(suffix));
+ }
+
+ /**
+ * Sets the variable suffix matcher currently in use.
+ * <p>
+ * The variable suffix is the character or characters that identify the end of a variable. This suffix is expressed
+ * in terms of a matcher allowing advanced suffix matches.
+ * </p>
+ *
+ * @param suffixMatcher the suffix matcher to use, null ignored
+ * @return this, to enable chaining
+ * @throws IllegalArgumentException if the suffix matcher is null
+ */
+ public StringSubstitutor setVariableSuffixMatcher(final StringMatcher suffixMatcher) {
+ Validate.isTrue(suffixMatcher != null, "Variable suffix matcher must not be null!");
+ this.suffixMatcher = suffixMatcher;
+ return this;
+ }
+
+ // -----------------------------------------------------------------------
+ /**
+ * Internal method that substitutes the variables.
+ * <p>
+ * Most users of this class do not need to call this method. This method will be called automatically by another
+ * (public) method.
+ * </p>
+ * <p>
+ * Writers of subclasses can override this method if they need access to the substitution process at the start or
+ * end.
+ * </p>
+ *
+ * @param buf the string builder to substitute into, not null
+ * @param offset the start offset within the builder, must be valid
+ * @param length the length within the builder to be processed, must be valid
+ * @return true if altered
+ */
+ protected boolean substitute(final TextStringBuilder buf, final int offset, final int length) {
+ return substitute(buf, offset, length, null) > 0;
+ }
+
+ /**
+ * Recursive handler for multiple levels of interpolation. This is the main interpolation method, which resolves the
+ * values of all variable references contained in the passed in text.
+ *
+ * @param builder the string builder to substitute into, not null
+ * @param offset the start offset within the builder, must be valid
+ * @param length the length within the builder to be processed, must be valid
+ * @param priorVariables the stack keeping track of the replaced variables, may be null
+ * @return The length change that occurs, unless priorVariables is null when the int represents a boolean flag as to
+ * whether any change occurred.
+ * @throws IllegalArgumentException if variable is not found when its allowed to throw exception
+ */
+ private int substitute(final TextStringBuilder builder, final int offset, final int length,
+ List<String> priorVariables) {
+ final StringMatcher prefixMatcher = getVariablePrefixMatcher();
+ final StringMatcher suffixMatcher = getVariableSuffixMatcher();
+ final char escapeCh = getEscapeChar();
+ final StringMatcher valueDelimMatcher = getValueDelimiterMatcher();
+ final boolean substitutionInVariablesEnabled = isEnableSubstitutionInVariables();
+ final boolean substitutionInValuesDisabled = isDisableSubstitutionInValues();
+ final boolean undefinedVariableException = isEnableUndefinedVariableException();
+
+ final boolean top = priorVariables == null;
+ boolean altered = false;
+ int lengthChange = 0;
+ char[] chars = builder.buffer;
+ int bufEnd = offset + length;
+ int pos = offset;
+ while (pos < bufEnd) {
+ final int startMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd);
+ if (startMatchLen == 0) {
+ pos++;
+ } else {
+ // found variable start marker
+ if (pos > offset && chars[pos - 1] == escapeCh) {
+ // escaped
+ if (preserveEscapes) {
+ pos++;
+ continue;
+ }
+ builder.deleteCharAt(pos - 1);
+ chars = builder.buffer; // in case buffer was altered
+ lengthChange--;
+ altered = true;
+ bufEnd--;
+ } else {
+ // find suffix
+ final int startPos = pos;
+ pos += startMatchLen;
+ int endMatchLen = 0;
+ int nestedVarCount = 0;
+ while (pos < bufEnd) {
+ if (substitutionInVariablesEnabled && prefixMatcher.isMatch(chars, pos, offset, bufEnd) != 0) {
+ // found a nested variable start
+ endMatchLen = prefixMatcher.isMatch(chars, pos, offset, bufEnd);
+ nestedVarCount++;
+ pos += endMatchLen;
+ continue;
+ }
+
+ endMatchLen = suffixMatcher.isMatch(chars, pos, offset, bufEnd);
+ if (endMatchLen == 0) {
+ pos++;
+ } else {
+ // found variable end marker
+ if (nestedVarCount == 0) {
+ String varNameExpr = new String(chars, startPos + startMatchLen,
+ pos - startPos - startMatchLen);
+ if (substitutionInVariablesEnabled) {
+ final TextStringBuilder bufName = new TextStringBuilder(varNameExpr);
+ substitute(bufName, 0, bufName.length());
+ varNameExpr = bufName.toString();
+ }
+ pos += endMatchLen;
+ final int endPos = pos;
+
+ String varName = varNameExpr;
+ String varDefaultValue = null;
+
+ if (valueDelimMatcher != null) {
+ final char[] varNameExprChars = varNameExpr.toCharArray();
+ int valueDelimiterMatchLen = 0;
+ for (int i = 0; i < varNameExprChars.length; i++) {
+ // if there's any nested variable when nested variable substitution disabled,
+ // then stop resolving name and default value.
+ if (!substitutionInVariablesEnabled && prefixMatcher.isMatch(varNameExprChars,
+ i, i, varNameExprChars.length) != 0) {
+ break;
+ }
+ if (valueDelimMatcher.isMatch(varNameExprChars, i, 0,
+ varNameExprChars.length) != 0) {
+ valueDelimiterMatchLen = valueDelimMatcher.isMatch(varNameExprChars, i, 0,
+ varNameExprChars.length);
+ varName = varNameExpr.substring(0, i);
+ varDefaultValue = varNameExpr.substring(i + valueDelimiterMatchLen);
+ break;
+ }
+ }
+ }
+
+ // on the first call initialize priorVariables
+ if (priorVariables == null) {
+ priorVariables = new ArrayList<>();
+ priorVariables.add(new String(chars, offset, length));
+ }
+
+ // handle cyclic substitution
+ checkCyclicSubstitution(varName, priorVariables);
+ priorVariables.add(varName);
+
+ // resolve the variable
+ String varValue = resolveVariable(varName, builder, startPos, endPos);
+ if (varValue == null) {
+ varValue = varDefaultValue;
+ }
+ if (varValue != null) {
+ final int varLen = varValue.length();
+ builder.replace(startPos, endPos, varValue);
+ altered = true;
+ int change = 0;
+ if (!substitutionInValuesDisabled) { // recursive replace
+ change = substitute(builder, startPos, varLen, priorVariables);
+ }
+ change = change + varLen - (endPos - startPos);
+ pos += change;
+ bufEnd += change;
+ lengthChange += change;
+ chars = builder.buffer; // in case buffer was altered
+ } else if (undefinedVariableException) {
+ throw new IllegalArgumentException(String.format(
+ "Cannot resolve variable '%s' (enableSubstitutionInVariables=%s).", varName,
+ enableSubstitutionInVariables));
+ }
+
+ // remove variable from the cyclic stack
+ priorVariables.remove(priorVariables.size() - 1);
+ break;
+ }
+ nestedVarCount--;
+ pos += endMatchLen;
+ }
+ }
+ }
+ }
+ }
+ if (top) {
+ return altered ? 1 : 0;
+ }
+ return lengthChange;
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
index 004e496..6beff3b 100644
--- a/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
+++ b/src/main/java/org/apache/commons/text/diff/ReplacementsFinder.java
@@ -1,126 +1,126 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.diff;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * This class handles sequences of replacements resulting from a comparison.
- * <p>
- * The comparison of two objects sequences leads to the identification of common
- * parts and parts which only belong to the first or to the second sequence. The
- * common parts appear in the edit script in the form of <em>keep</em> commands,
- * they can be considered as synchronization objects between the two sequences.
- * These synchronization objects split the two sequences in synchronized
- * sub-sequences. The first sequence can be transformed into the second one by
- * replacing each synchronized sub-sequence of the first sequence by the
- * corresponding sub-sequence of the second sequence. This is a synthetic way to
- * see an {@link EditScript edit script}, replacing individual
- * {@link DeleteCommand delete}, {@link KeepCommand keep} and
- * {@link InsertCommand insert} commands by fewer replacements acting on
- * complete sub-sequences.
- * </p>
- * <p>
- * This class is devoted to perform this interpretation. It visits an
- * {@link EditScript edit script} (because it implements the
- * {@link CommandVisitor CommandVisitor} interface) and calls a user-supplied
- * handler implementing the {@link ReplacementsHandler ReplacementsHandler}
- * interface to process the sub-sequences.
- * </p>
- *
- * @see ReplacementsHandler
- * @see EditScript
- * @see StringsComparator
- *
- * @param <T> object type
- * @since 1.0
- */
-public class ReplacementsFinder<T> implements CommandVisitor<T> {
-
- /**
- * List of pending insertions.
- */
- private final List<T> pendingInsertions;
-
- /**
- * List of pending deletions.
- */
- private final List<T> pendingDeletions;
-
- /**
- * Count of elements skipped.
- */
- private int skipped;
-
- /** Handler to call when synchronized sequences are found. */
- private final ReplacementsHandler<T> handler;
-
- /**
- * Simple constructor. Creates a new instance of {@link ReplacementsFinder}.
- *
- * @param handler handler to call when synchronized sequences are found
- */
- public ReplacementsFinder(final ReplacementsHandler<T> handler) {
- pendingInsertions = new ArrayList<>();
- pendingDeletions = new ArrayList<>();
- skipped = 0;
- this.handler = handler;
- }
-
- /**
- * Add an object to the pending insertions set.
- *
- * @param object object to insert
- */
- @Override
- public void visitInsertCommand(final T object) {
- pendingInsertions.add(object);
- }
-
- /**
- * Handle a synchronization object.
- * <p>
- * When a synchronization object is identified, the pending insertions and
- * pending deletions sets are provided to the user handler as subsequences.
- * </p>
- *
- * @param object synchronization object detected
- */
- @Override
- public void visitKeepCommand(final T object) {
- if (pendingDeletions.isEmpty() && pendingInsertions.isEmpty()) {
- ++skipped;
- } else {
- handler.handleReplacement(skipped, pendingDeletions, pendingInsertions);
- pendingDeletions.clear();
- pendingInsertions.clear();
- skipped = 1;
- }
- }
-
- /**
- * Add an object to the pending deletions set.
- *
- * @param object object to delete
- */
- @Override
- public void visitDeleteCommand(final T object) {
- pendingDeletions.add(object);
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.diff;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class handles sequences of replacements resulting from a comparison.
+ * <p>
+ * The comparison of two objects sequences leads to the identification of common
+ * parts and parts which only belong to the first or to the second sequence. The
+ * common parts appear in the edit script in the form of <em>keep</em> commands,
+ * they can be considered as synchronization objects between the two sequences.
+ * These synchronization objects split the two sequences in synchronized
+ * sub-sequences. The first sequence can be transformed into the second one by
+ * replacing each synchronized sub-sequence of the first sequence by the
+ * corresponding sub-sequence of the second sequence. This is a synthetic way to
+ * see an {@link EditScript edit script}, replacing individual
+ * {@link DeleteCommand delete}, {@link KeepCommand keep} and
+ * {@link InsertCommand insert} commands by fewer replacements acting on
+ * complete sub-sequences.
+ * </p>
+ * <p>
+ * This class is devoted to perform this interpretation. It visits an
+ * {@link EditScript edit script} (because it implements the
+ * {@link CommandVisitor CommandVisitor} interface) and calls a user-supplied
+ * handler implementing the {@link ReplacementsHandler ReplacementsHandler}
+ * interface to process the sub-sequences.
+ * </p>
+ *
+ * @see ReplacementsHandler
+ * @see EditScript
+ * @see StringsComparator
+ *
+ * @param <T> object type
+ * @since 1.0
+ */
+public class ReplacementsFinder<T> implements CommandVisitor<T> {
+
+ /**
+ * List of pending insertions.
+ */
+ private final List<T> pendingInsertions;
+
+ /**
+ * List of pending deletions.
+ */
+ private final List<T> pendingDeletions;
+
+ /**
+ * Count of elements skipped.
+ */
+ private int skipped;
+
+ /** Handler to call when synchronized sequences are found. */
+ private final ReplacementsHandler<T> handler;
+
+ /**
+ * Simple constructor. Creates a new instance of {@link ReplacementsFinder}.
+ *
+ * @param handler handler to call when synchronized sequences are found
+ */
+ public ReplacementsFinder(final ReplacementsHandler<T> handler) {
+ pendingInsertions = new ArrayList<>();
+ pendingDeletions = new ArrayList<>();
+ skipped = 0;
+ this.handler = handler;
+ }
+
+ /**
+ * Add an object to the pending insertions set.
+ *
+ * @param object object to insert
+ */
+ @Override
+ public void visitInsertCommand(final T object) {
+ pendingInsertions.add(object);
+ }
+
+ /**
+ * Handle a synchronization object.
+ * <p>
+ * When a synchronization object is identified, the pending insertions and
+ * pending deletions sets are provided to the user handler as subsequences.
+ * </p>
+ *
+ * @param object synchronization object detected
+ */
+ @Override
+ public void visitKeepCommand(final T object) {
+ if (pendingDeletions.isEmpty() && pendingInsertions.isEmpty()) {
+ ++skipped;
+ } else {
+ handler.handleReplacement(skipped, pendingDeletions, pendingInsertions);
+ pendingDeletions.clear();
+ pendingInsertions.clear();
+ skipped = 1;
+ }
+ }
+
+ /**
+ * Add an object to the pending deletions set.
+ *
+ * @param object object to delete
+ */
+ @Override
+ public void visitDeleteCommand(final T object) {
+ pendingDeletions.add(object);
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java b/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
index 8f7c0b6..676387d 100644
--- a/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/DateStringLookup.java
@@ -1,94 +1,94 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-package org.apache.commons.text.lookup;
-
-import java.text.DateFormat;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
-import org.apache.commons.lang3.time.FastDateFormat;
-import org.apache.commons.text.StringSubstitutor;
-
-/**
- * Formats the current date with the format given in the key in a format compatible with
- * {@link java.text.SimpleDateFormat}.
- * <p>
- * Using a {@link StringLookup} from the {@link StringLookupFactory}:
- * </p>
- *
- * <pre>
- * StringLookupFactory.INSTANCE.dateStringLookup().lookup("yyyy-MM-dd");
- * </pre>
- * <p>
- * Using a {@link StringSubstitutor}:
- * </p>
- *
- * <pre>
- * StringSubstitutor.createInterpolator().replace("... ${date:yyyy-MM-dd} ..."));
- * </pre>
- * <p>
- * The above examples convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}.
- * </p>
- */
-final class DateStringLookup extends AbstractStringLookup {
-
- /**
- * Defines the singleton for this class.
- */
- static final DateStringLookup INSTANCE = new DateStringLookup();
-
- /**
- * No need to build instances for now.
- */
- private DateStringLookup() {
- // empty
- }
-
- /**
- * Formats the given {@code date} long with the given {@code format}.
- *
- * @param date the date to format
- * @param format the format string for {@link SimpleDateFormat}.
- * @return The formatted date
- */
- private String formatDate(final long date, final String format) {
- FastDateFormat dateFormat = null;
- if (format != null) {
- try {
- dateFormat = FastDateFormat.getInstance(format);
- } catch (final Exception ex) {
- throw IllegalArgumentExceptions.format(ex, "Invalid date format: [%s]", format);
- }
- }
- if (dateFormat == null) {
- dateFormat = FastDateFormat.getInstance();
- }
- return dateFormat.format(new Date(date));
- }
-
- /**
- * Formats the current date with the format given in the key in a format compatible with
- * {@link java.text.SimpleDateFormat}.
- *
- * @param key the format to use. If null, the default {@link DateFormat} will be used.
- * @return The value of the environment variable.
- */
- @Override
- public String lookup(final String key) {
- return formatDate(System.currentTimeMillis(), key);
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.commons.text.lookup;
+
+import java.text.DateFormat;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+
+import org.apache.commons.lang3.time.FastDateFormat;
+import org.apache.commons.text.StringSubstitutor;
+
+/**
+ * Formats the current date with the format given in the key in a format compatible with
+ * {@link java.text.SimpleDateFormat}.
+ * <p>
+ * Using a {@link StringLookup} from the {@link StringLookupFactory}:
+ * </p>
+ *
+ * <pre>
+ * StringLookupFactory.INSTANCE.dateStringLookup().lookup("yyyy-MM-dd");
+ * </pre>
+ * <p>
+ * Using a {@link StringSubstitutor}:
+ * </p>
+ *
+ * <pre>
+ * StringSubstitutor.createInterpolator().replace("... ${date:yyyy-MM-dd} ..."));
+ * </pre>
+ * <p>
+ * The above examples convert {@code "yyyy-MM-dd"} to todays's date, for example, {@code "2019-08-04"}.
+ * </p>
+ */
+final class DateStringLookup extends AbstractStringLookup {
+
+ /**
+ * Defines the singleton for this class.
+ */
+ static final DateStringLookup INSTANCE = new DateStringLookup();
+
+ /**
+ * No need to build instances for now.
+ */
+ private DateStringLookup() {
+ // empty
+ }
+
+ /**
+ * Formats the given {@code date} long with the given {@code format}.
+ *
+ * @param date the date to format
+ * @param format the format string for {@link SimpleDateFormat}.
+ * @return The formatted date
+ */
+ private String formatDate(final long date, final String format) {
+ FastDateFormat dateFormat = null;
+ if (format != null) {
+ try {
+ dateFormat = FastDateFormat.getInstance(format);
+ } catch (final Exception ex) {
+ throw IllegalArgumentExceptions.format(ex, "Invalid date format: [%s]", format);
+ }
+ }
+ if (dateFormat == null) {
+ dateFormat = FastDateFormat.getInstance();
+ }
+ return dateFormat.format(new Date(date));
+ }
+
+ /**
+ * Formats the current date with the format given in the key in a format compatible with
+ * {@link java.text.SimpleDateFormat}.
+ *
+ * @param key the format to use. If null, the default {@link DateFormat} will be used.
+ * @return The value of the environment variable.
+ */
+ @Override
+ public String lookup(final String key) {
+ return formatDate(System.currentTimeMillis(), key);
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookup.java b/src/main/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookup.java
index 1ad1a8d..78758ef 100644
--- a/src/main/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/EnvironmentVariableStringLookup.java
@@ -1,70 +1,70 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-package org.apache.commons.text.lookup;
-
-import org.apache.commons.text.StringSubstitutor;
-
-/**
- * Looks up keys from environment variables.
- * <p>
- * Using a {@link StringLookup} from the {@link StringLookupFactory}:
- * </p>
- *
- * <pre>
- * StringLookupFactory.INSTANCE.dateStringLookup().lookup("USER");
- * </pre>
- * <p>
- * Using a {@link StringSubstitutor}:
- * </p>
- *
- * <pre>
- * StringSubstitutor.createInterpolator().replace("... ${env:USER} ..."));
- * </pre>
- * <p>
- * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use
- * {@code "USERNAME"} to the same effect.
- * </p>
- *
- * @since 1.3
- */
-final class EnvironmentVariableStringLookup extends AbstractStringLookup {
-
- /**
- * Defines the singleton for this class.
- */
- static final EnvironmentVariableStringLookup INSTANCE = new EnvironmentVariableStringLookup();
-
- /**
- * No need to build instances for now.
- */
- private EnvironmentVariableStringLookup() {
- // empty
- }
-
- /**
- * Looks up the value of the given environment variable.
- *
- * @param key the key to be looked up, may be null
- * @return The value of the environment variable.
- * @see System#getenv(String)
- */
- @Override
- public String lookup(final String key) {
- // getenv throws NullPointerException if {@code name} is {@code null}
- return key != null ? System.getenv(key) : null;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.commons.text.lookup;
+
+import org.apache.commons.text.StringSubstitutor;
+
+/**
+ * Looks up keys from environment variables.
+ * <p>
+ * Using a {@link StringLookup} from the {@link StringLookupFactory}:
+ * </p>
+ *
+ * <pre>
+ * StringLookupFactory.INSTANCE.dateStringLookup().lookup("USER");
+ * </pre>
+ * <p>
+ * Using a {@link StringSubstitutor}:
+ * </p>
+ *
+ * <pre>
+ * StringSubstitutor.createInterpolator().replace("... ${env:USER} ..."));
+ * </pre>
+ * <p>
+ * The above examples convert (on Linux) {@code "USER"} to the current user name. On Windows 10, you would use
+ * {@code "USERNAME"} to the same effect.
+ * </p>
+ *
+ * @since 1.3
+ */
+final class EnvironmentVariableStringLookup extends AbstractStringLookup {
+
+ /**
+ * Defines the singleton for this class.
+ */
+ static final EnvironmentVariableStringLookup INSTANCE = new EnvironmentVariableStringLookup();
+
+ /**
+ * No need to build instances for now.
+ */
+ private EnvironmentVariableStringLookup() {
+ // empty
+ }
+
+ /**
+ * Looks up the value of the given environment variable.
+ *
+ * @param key the key to be looked up, may be null
+ * @return The value of the environment variable.
+ * @see System#getenv(String)
+ */
+ @Override
+ public String lookup(final String key) {
+ // getenv throws NullPointerException if {@code name} is {@code null}
+ return key != null ? System.getenv(key) : null;
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java b/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
index 585fe56..e5e2445 100644
--- a/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
+++ b/src/main/java/org/apache/commons/text/lookup/IllegalArgumentExceptions.java
@@ -1,61 +1,61 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-/**
- * Shorthands creating {@link IllegalArgumentException} instances using formatted strings.
- *
- * @since 1.3
- */
-final class IllegalArgumentExceptions {
-
- /**
- * Creates an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}.
- *
- * @param format
- * See {@link String#format(String,Object...)}
- * @param args
- * See {@link String#format(String,Object...)}
- * @return an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}
- */
- static IllegalArgumentException format(final String format, final Object... args) {
- return new IllegalArgumentException(String.format(format, args));
- }
-
- /**
- * Creates an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}.
- *
- * @param t
- * the throwable cause
- * @param format
- * See {@link String#format(String,Object...)}
- * @param args
- * See {@link String#format(String,Object...)}
- * @return an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}
- */
- static IllegalArgumentException format(final Throwable t, final String format, final Object... args) {
- return new IllegalArgumentException(String.format(format, args), t);
- }
-
- /**
- * No need to build instances.
- */
- private IllegalArgumentExceptions() {
- // empty
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+/**
+ * Shorthands creating {@link IllegalArgumentException} instances using formatted strings.
+ *
+ * @since 1.3
+ */
+final class IllegalArgumentExceptions {
+
+ /**
+ * Creates an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}.
+ *
+ * @param format
+ * See {@link String#format(String,Object...)}
+ * @param args
+ * See {@link String#format(String,Object...)}
+ * @return an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}
+ */
+ static IllegalArgumentException format(final String format, final Object... args) {
+ return new IllegalArgumentException(String.format(format, args));
+ }
+
+ /**
+ * Creates an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}.
+ *
+ * @param t
+ * the throwable cause
+ * @param format
+ * See {@link String#format(String,Object...)}
+ * @param args
+ * See {@link String#format(String,Object...)}
+ * @return an {@link IllegalArgumentException} with a message formated with {@link String#format(String,Object...)}
+ */
+ static IllegalArgumentException format(final Throwable t, final String format, final Object... args) {
+ return new IllegalArgumentException(String.format(format, args), t);
+ }
+
+ /**
+ * No need to build instances.
+ */
+ private IllegalArgumentExceptions() {
+ // empty
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/MapStringLookup.java b/src/main/java/org/apache/commons/text/lookup/MapStringLookup.java
index 37d2c78..c70a611 100644
--- a/src/main/java/org/apache/commons/text/lookup/MapStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/MapStringLookup.java
@@ -1,98 +1,98 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-package org.apache.commons.text.lookup;
-
-import java.util.Map;
-
-/**
- * A map-based lookup where the request for a lookup is answered with the value for that key.
- *
- * @param <V>
- * A map's value type
- *
- * @since 1.3
- */
-final class MapStringLookup<V> implements StringLookup {
-
- /**
- * Creates a new instance backed by a Map. Used by the default lookup.
- *
- * @param <T>
- * the map's value type.
- * @param map
- * the map of keys to values, may be null.
- * @return a new instance backed by the given map.
- */
- static <T> MapStringLookup<T> on(final Map<String, T> map) {
- return new MapStringLookup<>(map);
- }
-
- /**
- * Map keys are variable names and value.
- */
- private final Map<String, V> map;
-
- /**
- * Creates a new instance backed by a Map. Used by the default lookup.
- *
- * @param map
- * the map of keys to values, may be null.
- */
- private MapStringLookup(final Map<String, V> map) {
- this.map = map;
- }
-
- /**
- * Gets the map used in lookups.
- *
- * @return The map used in lookups.
- */
- Map<String, V> getMap() {
- return map;
- }
-
- /**
- * Looks up a String key to a String value using the map.
- * <p>
- * If the map is null, then null is returned. The map result object is converted to a string using toString().
- * </p>
- *
- * @param key
- * the key to be looked up, may be null.
- * @return The matching value, null if no match
- */
- @Override
- public String lookup(final String key) {
- if (map == null) {
- return null;
- }
- final V obj;
- try {
- obj = map.get(key);
- } catch (final NullPointerException e) {
- // Could be a ConcurrentHashMap and a null key request
- return null;
- }
- return obj != null ? obj.toString() : null;
- }
-
- @Override
- public String toString() {
- return super.toString() + " [map=" + map + "]";
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.commons.text.lookup;
+
+import java.util.Map;
+
+/**
+ * A map-based lookup where the request for a lookup is answered with the value for that key.
+ *
+ * @param <V>
+ * A map's value type
+ *
+ * @since 1.3
+ */
+final class MapStringLookup<V> implements StringLookup {
+
+ /**
+ * Creates a new instance backed by a Map. Used by the default lookup.
+ *
+ * @param <T>
+ * the map's value type.
+ * @param map
+ * the map of keys to values, may be null.
+ * @return a new instance backed by the given map.
+ */
+ static <T> MapStringLookup<T> on(final Map<String, T> map) {
+ return new MapStringLookup<>(map);
+ }
+
+ /**
+ * Map keys are variable names and value.
+ */
+ private final Map<String, V> map;
+
+ /**
+ * Creates a new instance backed by a Map. Used by the default lookup.
+ *
+ * @param map
+ * the map of keys to values, may be null.
+ */
+ private MapStringLookup(final Map<String, V> map) {
+ this.map = map;
+ }
+
+ /**
+ * Gets the map used in lookups.
+ *
+ * @return The map used in lookups.
+ */
+ Map<String, V> getMap() {
+ return map;
+ }
+
+ /**
+ * Looks up a String key to a String value using the map.
+ * <p>
+ * If the map is null, then null is returned. The map result object is converted to a string using toString().
+ * </p>
+ *
+ * @param key
+ * the key to be looked up, may be null.
+ * @return The matching value, null if no match
+ */
+ @Override
+ public String lookup(final String key) {
+ if (map == null) {
+ return null;
+ }
+ final V obj;
+ try {
+ obj = map.get(key);
+ } catch (final NullPointerException e) {
+ // Could be a ConcurrentHashMap and a null key request
+ return null;
+ }
+ return obj != null ? obj.toString() : null;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + " [map=" + map + "]";
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/NullStringLookup.java b/src/main/java/org/apache/commons/text/lookup/NullStringLookup.java
index 8190139..f873e55 100644
--- a/src/main/java/org/apache/commons/text/lookup/NullStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/NullStringLookup.java
@@ -1,47 +1,47 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-
-package org.apache.commons.text.lookup;
-
-/**
- * Always returns null.
- *
- * @since 1.3
- */
-final class NullStringLookup extends AbstractStringLookup {
-
- /**
- * Defines the singleton for this class.
- */
- static final NullStringLookup INSTANCE = new NullStringLookup();
-
- /**
- * No need to build instances for now.
- */
- private NullStringLookup() {
- // empty
- }
-
- /**
- * Always returns null.
- */
- @Override
- public String lookup(final String key) {
- return null;
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+
+package org.apache.commons.text.lookup;
+
+/**
+ * Always returns null.
+ *
+ * @since 1.3
+ */
+final class NullStringLookup extends AbstractStringLookup {
+
+ /**
+ * Defines the singleton for this class.
+ */
+ static final NullStringLookup INSTANCE = new NullStringLookup();
+
+ /**
+ * No need to build instances for now.
+ */
+ private NullStringLookup() {
+ // empty
+ }
+
+ /**
+ * Always returns null.
+ */
+ @Override
+ public String lookup(final String key) {
+ return null;
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/lookup/SystemPropertyStringLookup.java b/src/main/java/org/apache/commons/text/lookup/SystemPropertyStringLookup.java
index 9d84da6..5261c93 100644
--- a/src/main/java/org/apache/commons/text/lookup/SystemPropertyStringLookup.java
+++ b/src/main/java/org/apache/commons/text/lookup/SystemPropertyStringLookup.java
@@ -1,55 +1,55 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache license, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the license for the specific language governing permissions and
- * limitations under the license.
- */
-package org.apache.commons.text.lookup;
-
-/**
- * Looks up keys from system properties where the key is a system property name.
- *
- * @since 1.3
- */
-final class SystemPropertyStringLookup extends AbstractStringLookup {
-
- /**
- * Defines the singleton for this class.
- */
- static final SystemPropertyStringLookup INSTANCE = new SystemPropertyStringLookup();
-
- /**
- * No need to build instances for now.
- */
- private SystemPropertyStringLookup() {
- // empty
- }
-
- /**
- * Looks up the value for the key from system properties where the key is a system property name.
- *
- * @param key
- * the key to be looked up where the key is a system property name, may be null
- * @return The value associated with the key.
- * @see System#getProperty(String)
- */
- @Override
- public String lookup(final String key) {
- try {
- return System.getProperty(key);
- } catch (final SecurityException | NullPointerException | IllegalArgumentException e) {
- // Squelched. All lookup(String) will return null.
- return null;
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache license, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the license for the specific language governing permissions and
+ * limitations under the license.
+ */
+package org.apache.commons.text.lookup;
+
+/**
+ * Looks up keys from system properties where the key is a system property name.
+ *
+ * @since 1.3
+ */
+final class SystemPropertyStringLookup extends AbstractStringLookup {
+
+ /**
+ * Defines the singleton for this class.
+ */
+ static final SystemPropertyStringLookup INSTANCE = new SystemPropertyStringLookup();
+
+ /**
+ * No need to build instances for now.
+ */
+ private SystemPropertyStringLookup() {
+ // empty
+ }
+
+ /**
+ * Looks up the value for the key from system properties where the key is a system property name.
+ *
+ * @param key
+ * the key to be looked up where the key is a system property name, may be null
+ * @return The value associated with the key.
+ * @see System#getProperty(String)
+ */
+ @Override
+ public String lookup(final String key) {
+ try {
+ return System.getProperty(key);
+ } catch (final SecurityException | NullPointerException | IllegalArgumentException e) {
+ // Squelched. All lookup(String) will return null.
+ return null;
+ }
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java b/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
index abe6d65..e2431c1 100644
--- a/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
+++ b/src/main/java/org/apache/commons/text/matcher/AbstractStringMatcher.java
@@ -1,259 +1,259 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.text.matcher;
-
-import java.util.Arrays;
-
-/**
- * A matcher class that can be queried to determine if a character array portion matches.
- * <p>
- * This class comes complete with various factory methods. If these do not suffice, you can subclass and implement your
- * own matcher.
- *
- * @since 1.3
- */
-abstract class AbstractStringMatcher implements StringMatcher {
-
- /**
- * Class used to define a character for matching purposes.
- */
- static final class CharMatcher extends AbstractStringMatcher {
-
- /** The character to match. */
- private final char ch;
-
- /**
- * Constructor that creates a matcher that matches a single character.
- *
- * @param ch
- * the character to match
- */
- CharMatcher(final char ch) {
- super();
- this.ch = ch;
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- @Override
- public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
- return ch == buffer[start] ? 1 : 0;
- }
- }
-
- /**
- * Class used to define a set of characters for matching purposes.
- */
- static final class CharSetMatcher extends AbstractStringMatcher {
-
- /** The set of characters to match. */
- private final char[] chars;
-
- /**
- * Constructor that creates a matcher from a character array.
- *
- * @param chars
- * the characters to match, must not be null
- */
- CharSetMatcher(final char[] chars) {
- super();
- this.chars = chars.clone();
- Arrays.sort(this.chars);
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- @Override
- public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
- return Arrays.binarySearch(chars, buffer[start]) >= 0 ? 1 : 0;
- }
- }
-
- /**
- * Class used to match no characters.
- */
- static final class NoMatcher extends AbstractStringMatcher {
-
- /**
- * Constructs a new instance of {@code NoMatcher}.
- */
- NoMatcher() {
- super();
- }
-
- /**
- * Always returns {@code false}.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- @Override
- public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
- return 0;
- }
- }
-
- /**
- * Class used to define a set of characters for matching purposes.
- */
- static final class StringMatcher extends AbstractStringMatcher {
-
- /** The string to match, as a character array. */
- private final char[] chars;
-
- /**
- * Constructor that creates a matcher from a String.
- *
- * @param str
- * the string to match, must not be null
- */
- StringMatcher(final String str) {
- super();
- chars = str.toCharArray();
- }
-
- /**
- * Returns whether or not the given text matches the stored string.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- @Override
- public int isMatch(final char[] buffer, int start, final int bufferStart, final int bufferEnd) {
- final int len = chars.length;
- if (start + len > bufferEnd) {
- return 0;
- }
- for (int i = 0; i < chars.length; i++, start++) {
- if (chars[i] != buffer[start]) {
- return 0;
- }
- }
- return len;
- }
-
- @Override
- public String toString() {
- return super.toString() + ' ' + Arrays.toString(chars);
- }
-
- }
-
- /**
- * Class used to match whitespace as per trim().
- */
- static final class TrimMatcher extends AbstractStringMatcher {
-
- /**
- * The space character.
- */
- private static final int SPACE_INT = 32;
-
- /**
- * Constructs a new instance of {@code TrimMatcher}.
- */
- TrimMatcher() {
- super();
- }
-
- /**
- * Returns whether or not the given character matches.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index of the active buffer, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- @Override
- public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
- return buffer[start] <= SPACE_INT ? 1 : 0;
- }
- }
-
- /**
- * Constructor.
- */
- protected AbstractStringMatcher() {
- super();
- }
-
- /**
- * Returns the number of matching characters, zero for no match.
- * <p>
- * This method is called to check for a match. The parameter {@code pos} represents the current position to be
- * checked in the string {@code buffer} (a character array which must not be changed). The API guarantees that
- * {@code pos} is a valid index for {@code buffer}.
- * <p>
- * The matching code may check one character or many. It may check characters preceding {@code pos} as well as
- * those after.
- * <p>
- * It must return zero for no match, or a positive number if a match was found. The number indicates the number of
- * characters that matched.
- *
- * @param buffer
- * the text content to match against, do not change
- * @param pos
- * the starting position for the match, valid for buffer
- * @return The number of matching characters, zero for no match
- */
- public int isMatch(final char[] buffer, final int pos) {
- return isMatch(buffer, pos, 0, buffer.length);
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.text.matcher;
+
+import java.util.Arrays;
+
+/**
+ * A matcher class that can be queried to determine if a character array portion matches.
+ * <p>
+ * This class comes complete with various factory methods. If these do not suffice, you can subclass and implement your
+ * own matcher.
+ *
+ * @since 1.3
+ */
+abstract class AbstractStringMatcher implements StringMatcher {
+
+ /**
+ * Class used to define a character for matching purposes.
+ */
+ static final class CharMatcher extends AbstractStringMatcher {
+
+ /** The character to match. */
+ private final char ch;
+
+ /**
+ * Constructor that creates a matcher that matches a single character.
+ *
+ * @param ch
+ * the character to match
+ */
+ CharMatcher(final char ch) {
+ super();
+ this.ch = ch;
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
+ return ch == buffer[start] ? 1 : 0;
+ }
+ }
+
+ /**
+ * Class used to define a set of characters for matching purposes.
+ */
+ static final class CharSetMatcher extends AbstractStringMatcher {
+
+ /** The set of characters to match. */
+ private final char[] chars;
+
+ /**
+ * Constructor that creates a matcher from a character array.
+ *
+ * @param chars
+ * the characters to match, must not be null
+ */
+ CharSetMatcher(final char[] chars) {
+ super();
+ this.chars = chars.clone();
+ Arrays.sort(this.chars);
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
+ return Arrays.binarySearch(chars, buffer[start]) >= 0 ? 1 : 0;
+ }
+ }
+
+ /**
+ * Class used to match no characters.
+ */
+ static final class NoMatcher extends AbstractStringMatcher {
+
+ /**
+ * Constructs a new instance of {@code NoMatcher}.
+ */
+ NoMatcher() {
+ super();
+ }
+
+ /**
+ * Always returns {@code false}.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
+ return 0;
+ }
+ }
+
+ /**
+ * Class used to define a set of characters for matching purposes.
+ */
+ static final class StringMatcher extends AbstractStringMatcher {
+
+ /** The string to match, as a character array. */
+ private final char[] chars;
+
+ /**
+ * Constructor that creates a matcher from a String.
+ *
+ * @param str
+ * the string to match, must not be null
+ */
+ StringMatcher(final String str) {
+ super();
+ chars = str.toCharArray();
+ }
+
+ /**
+ * Returns whether or not the given text matches the stored string.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, int start, final int bufferStart, final int bufferEnd) {
+ final int len = chars.length;
+ if (start + len > bufferEnd) {
+ return 0;
+ }
+ for (int i = 0; i < chars.length; i++, start++) {
+ if (chars[i] != buffer[start]) {
+ return 0;
+ }
+ }
+ return len;
+ }
+
+ @Override
+ public String toString() {
+ return super.toString() + ' ' + Arrays.toString(chars);
+ }
+
+ }
+
+ /**
+ * Class used to match whitespace as per trim().
+ */
+ static final class TrimMatcher extends AbstractStringMatcher {
+
+ /**
+ * The space character.
+ */
+ private static final int SPACE_INT = 32;
+
+ /**
+ * Constructs a new instance of {@code TrimMatcher}.
+ */
+ TrimMatcher() {
+ super();
+ }
+
+ /**
+ * Returns whether or not the given character matches.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index of the active buffer, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ @Override
+ public int isMatch(final char[] buffer, final int start, final int bufferStart, final int bufferEnd) {
+ return buffer[start] <= SPACE_INT ? 1 : 0;
+ }
+ }
+
+ /**
+ * Constructor.
+ */
+ protected AbstractStringMatcher() {
+ super();
+ }
+
+ /**
+ * Returns the number of matching characters, zero for no match.
+ * <p>
+ * This method is called to check for a match. The parameter {@code pos} represents the current position to be
+ * checked in the string {@code buffer} (a character array which must not be changed). The API guarantees that
+ * {@code pos} is a valid index for {@code buffer}.
+ * <p>
+ * The matching code may check one character or many. It may check characters preceding {@code pos} as well as
+ * those after.
+ * <p>
+ * It must return zero for no match, or a positive number if a match was found. The number indicates the number of
+ * characters that matched.
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param pos
+ * the starting position for the match, valid for buffer
+ * @return The number of matching characters, zero for no match
+ */
+ public int isMatch(final char[] buffer, final int pos) {
+ return isMatch(buffer, pos, 0, buffer.length);
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/matcher/StringMatcher.java b/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
index 292c47c..1a69e2c 100644
--- a/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
+++ b/src/main/java/org/apache/commons/text/matcher/StringMatcher.java
@@ -1,59 +1,59 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.text.matcher;
-
-/**
- * Determines if a character array portion matches.
- *
- * @since 1.3
- */
-public interface StringMatcher {
-
- /**
- * Returns the number of matching characters, zero for no match.
- * <p>
- * This method is called to check for a match. The parameter {@code start} represents the start position to be
- * checked in the string {@code buffer} (a character array which must not be changed). The API guarantees that
- * {@code start} is a valid index for {@code buffer}.
- * </p>
- * <p>
- * The character array may be larger than the active area to be matched. Only values in the buffer between the
- * specified indices may be accessed.
- * </p>
- * <p>
- * The matching code may check one character or many. It may check characters preceding {@code start} as well as
- * those after, so long as no checks exceed the bounds specified.
- * </p>
- * <p>
- * It must return zero for no match, or a positive number if a match was found. The number indicates the number of
- * characters that matched.
- * </p>
- *
- * @param buffer
- * the text content to match against, do not change
- * @param start
- * the starting position for the match, valid for buffer
- * @param bufferStart
- * the first active index in the buffer, valid for buffer
- * @param bufferEnd
- * the end index (exclusive) of the active buffer, valid for buffer
- * @return The number of matching characters, or zero if there is no match
- */
- int isMatch(char[] buffer, int start, int bufferStart, int bufferEnd);
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.text.matcher;
+
+/**
+ * Determines if a character array portion matches.
+ *
+ * @since 1.3
+ */
+public interface StringMatcher {
+
+ /**
+ * Returns the number of matching characters, zero for no match.
+ * <p>
+ * This method is called to check for a match. The parameter {@code start} represents the start position to be
+ * checked in the string {@code buffer} (a character array which must not be changed). The API guarantees that
+ * {@code start} is a valid index for {@code buffer}.
+ * </p>
+ * <p>
+ * The character array may be larger than the active area to be matched. Only values in the buffer between the
+ * specified indices may be accessed.
+ * </p>
+ * <p>
+ * The matching code may check one character or many. It may check characters preceding {@code start} as well as
+ * those after, so long as no checks exceed the bounds specified.
+ * </p>
+ * <p>
+ * It must return zero for no match, or a positive number if a match was found. The number indicates the number of
+ * characters that matched.
+ * </p>
+ *
+ * @param buffer
+ * the text content to match against, do not change
+ * @param start
+ * the starting position for the match, valid for buffer
+ * @param bufferStart
+ * the first active index in the buffer, valid for buffer
+ * @param bufferEnd
+ * the end index (exclusive) of the active buffer, valid for buffer
+ * @return The number of matching characters, or zero if there is no match
+ */
+ int isMatch(char[] buffer, int start, int bufferStart, int bufferEnd);
+
+}
diff --git a/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java b/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
index 1dc5b15..b112a92 100644
--- a/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
+++ b/src/main/java/org/apache/commons/text/matcher/StringMatcherFactory.java
@@ -1,228 +1,228 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.commons.text.matcher;
-
-/**
- * Provides access to matchers defined in this package.
- *
- * @since 1.3
- */
-public final class StringMatcherFactory {
-
- /**
- * Matches the comma character.
- */
- private static final AbstractStringMatcher.CharMatcher COMMA_MATCHER = new AbstractStringMatcher.CharMatcher(',');
-
- /**
- * Matches the double quote character.
- */
- private static final AbstractStringMatcher.CharMatcher DOUBLE_QUOTE_MATCHER = new AbstractStringMatcher.CharMatcher(
- '"');
-
- /**
- * Defines the singleton for this class.
- */
- public static final StringMatcherFactory INSTANCE = new StringMatcherFactory();
-
- /**
- * Matches no characters.
- */
- private static final AbstractStringMatcher.NoMatcher NONE_MATCHER = new AbstractStringMatcher.NoMatcher();
-
- /**
- * Matches the single or double quote character.
- */
- private static final AbstractStringMatcher.CharSetMatcher QUOTE_MATCHER = new AbstractStringMatcher.CharSetMatcher(
- "'\"".toCharArray());
-
- /**
- * Matches the double quote character.
- */
- private static final AbstractStringMatcher.CharMatcher SINGLE_QUOTE_MATCHER = new AbstractStringMatcher.CharMatcher(
- '\'');
-
- /**
- * Matches the space character.
- */
- private static final AbstractStringMatcher.CharMatcher SPACE_MATCHER = new AbstractStringMatcher.CharMatcher(' ');
-
- /**
- * Matches the same characters as StringTokenizer, namely space, tab, newline, form feed.
- */
- private static final AbstractStringMatcher.CharSetMatcher SPLIT_MATCHER = new AbstractStringMatcher.CharSetMatcher(
- " \t\n\r\f".toCharArray());
-
- /**
- * Matches the tab character.
- */
- private static final AbstractStringMatcher.CharMatcher TAB_MATCHER = new AbstractStringMatcher.CharMatcher('\t');
-
- /**
- * Matches the String trim() whitespace characters.
- */
- private static final AbstractStringMatcher.TrimMatcher TRIM_MATCHER = new AbstractStringMatcher.TrimMatcher();
-
- /**
- * No need to build instances for now.
- */
- private StringMatcherFactory() {
- // empty
- }
-
- /**
- * Constructor that creates a matcher from a character.
- *
- * @param ch
- * the character to match, must not be null
- * @return a new Matcher for the given char
- */
- public StringMatcher charMatcher(final char ch) {
- return new AbstractStringMatcher.CharMatcher(ch);
- }
-
- /**
- * Constructor that creates a matcher from a set of characters.
- *
- * @param chars
- * the characters to match, null or empty matches nothing
- * @return a new matcher for the given char[]
- */
- public StringMatcher charSetMatcher(final char... chars) {
- if (chars == null || chars.length == 0) {
- return NONE_MATCHER;
- }
- if (chars.length == 1) {
- return new AbstractStringMatcher.CharMatcher(chars[0]);
- }
- return new AbstractStringMatcher.CharSetMatcher(chars);
- }
-
- /**
- * Creates a matcher from a string representing a set of characters.
- *
- * @param chars
- * the characters to match, null or empty matches nothing
- * @return a new Matcher for the given characters
- */
- public StringMatcher charSetMatcher(final String chars) {
- if (chars == null || chars.length() == 0) {
- return NONE_MATCHER;
- }
- if (chars.length() == 1) {
- return new AbstractStringMatcher.CharMatcher(chars.charAt(0));
- }
- return new AbstractStringMatcher.CharSetMatcher(chars.toCharArray());
- }
-
- /**
- * Returns a matcher which matches the comma character.
- *
- * @return a matcher for a comma
- */
- public StringMatcher commaMatcher() {
- return COMMA_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the double quote character.
- *
- * @return a matcher for a double quote
- */
- public StringMatcher doubleQuoteMatcher() {
- return DOUBLE_QUOTE_MATCHER;
- }
-
- /**
- * Matches no characters.
- *
- * @return a matcher that matches nothing
- */
- public StringMatcher noneMatcher() {
- return NONE_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the single or double quote character.
- *
- * @return a matcher for a single or double quote
- */
- public StringMatcher quoteMatcher() {
- return QUOTE_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the single quote character.
- *
- * @return a matcher for a single quote
- */
- public StringMatcher singleQuoteMatcher() {
- return SINGLE_QUOTE_MATCHER;
- }
-
- /**
- * Returns a matcher which matches the space character.
- *
- * @return a matcher for a space
- */
- public StringMatcher spaceMatcher() {
- return SPACE_MATCHER;
- }
-
- /**
- * Matches the same characters as StringTokenizer, namely space, tab, newline and form feed.
- *
- * @return The split matcher
- */
- public StringMatcher splitMatcher() {
- return SPLIT_MATCHER;
- }
-
- /**
- * Creates a matcher from a string.
- *
- * @param str
- * the string to match, null or empty matches nothing
- * @return a new Matcher for the given String
- */
- public StringMatcher stringMatcher(final String str) {
- if (str == null || str.length() == 0) {
- return NONE_MATCHER;
- }
- return new AbstractStringMatcher.StringMatcher(str);
- }
-
- /**
- * Returns a matcher which matches the tab character.
- *
- * @return a matcher for a tab
- */
- public StringMatcher tabMatcher() {
- return TAB_MATCHER;
- }
-
- /**
- * Matches the String trim() whitespace characters.
- *
- * @return The trim matcher
- */
- public StringMatcher trimMatcher() {
- return TRIM_MATCHER;
- }
-
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.text.matcher;
+
+/**
+ * Provides access to matchers defined in this package.
+ *
+ * @since 1.3
+ */
+public final class StringMatcherFactory {
+
+ /**
+ * Matches the comma character.
+ */
+ private static final AbstractStringMatcher.CharMatcher COMMA_MATCHER = new AbstractStringMatcher.CharMatcher(',');
+
+ /**
+ * Matches the double quote character.
+ */
+ private static final AbstractStringMatcher.CharMatcher DOUBLE_QUOTE_MATCHER = new AbstractStringMatcher.CharMatcher(
+ '"');
+
+ /**
+ * Defines the singleton for this class.
+ */
+ public static final StringMatcherFactory INSTANCE = new StringMatcherFactory();
+
+ /**
+ * Matches no characters.
+ */
+ private static final AbstractStringMatcher.NoMatcher NONE_MATCHER = new AbstractStringMatcher.NoMatcher();
+
+ /**
+ * Matches the single or double quote character.
+ */
+ private static final AbstractStringMatcher.CharSetMatcher QUOTE_MATCHER = new AbstractStringMatcher.CharSetMatcher(
+ "'\"".toCharArray());
+
+ /**
+ * Matches the double quote character.
+ */
+ private static final AbstractStringMatcher.CharMatcher SINGLE_QUOTE_MATCHER = new AbstractStringMatcher.CharMatcher(
+ '\'');
+
+ /**
+ * Matches the space character.
+ */
+ private static final AbstractStringMatcher.CharMatcher SPACE_MATCHER = new AbstractStringMatcher.CharMatcher(' ');
+
+ /**
+ * Matches the same characters as StringTokenizer, namely space, tab, newline, form feed.
+ */
+ private static final AbstractStringMatcher.CharSetMatcher SPLIT_MATCHER = new AbstractStringMatcher.CharSetMatcher(
+ " \t\n\r\f".toCharArray());
+
+ /**
+ * Matches the tab character.
+ */
+ private static final AbstractStringMatcher.CharMatcher TAB_MATCHER = new AbstractStringMatcher.CharMatcher('\t');
+
+ /**
+ * Matches the String trim() whitespace characters.
+ */
+ private static final AbstractStringMatcher.TrimMatcher TRIM_MATCHER = new AbstractStringMatcher.TrimMatcher();
+
+ /**
+ * No need to build instances for now.
+ */
+ private StringMatcherFactory() {
+ // empty
+ }
+
+ /**
+ * Constructor that creates a matcher from a character.
+ *
+ * @param ch
+ * the character to match, must not be null
+ * @return a new Matcher for the given char
+ */
+ public StringMatcher charMatcher(final char ch) {
+ return new AbstractStringMatcher.CharMatcher(ch);
+ }
+
+ /**
+ * Constructor that creates a matcher from a set of characters.
+ *
+ * @param chars
+ * the characters to match, null or empty matches nothing
+ * @return a new matcher for the given char[]
+ */
+ public StringMatcher charSetMatcher(final char... chars) {
+ if (chars == null || chars.length == 0) {
+ return NONE_MATCHER;
+ }
+ if (chars.length == 1) {
+ return new AbstractStringMatcher.CharMatcher(chars[0]);
+ }
+ return new AbstractStringMatcher.CharSetMatcher(chars);
+ }
+
+ /**
+ * Creates a matcher from a string representing a set of characters.
+ *
+ * @param chars
+ * the characters to match, null or empty matches nothing
+ * @return a new Matcher for the given characters
+ */
+ public StringMatcher charSetMatcher(final String chars) {
+ if (chars == null || chars.length() == 0) {
+ return NONE_MATCHER;
+ }
+ if (chars.length() == 1) {
+ return new AbstractStringMatcher.CharMatcher(chars.charAt(0));
+ }
+ return new AbstractStringMatcher.CharSetMatcher(chars.toCharArray());
+ }
+
+ /**
+ * Returns a matcher which matches the comma character.
+ *
+ * @return a matcher for a comma
+ */
+ public StringMatcher commaMatcher() {
+ return COMMA_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the double quote character.
+ *
+ * @return a matcher for a double quote
+ */
+ public StringMatcher doubleQuoteMatcher() {
+ return DOUBLE_QUOTE_MATCHER;
+ }
+
+ /**
+ * Matches no characters.
+ *
+ * @return a matcher that matches nothing
+ */
+ public StringMatcher noneMatcher() {
+ return NONE_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the single or double quote character.
+ *
+ * @return a matcher for a single or double quote
+ */
+ public StringMatcher quoteMatcher() {
+ return QUOTE_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the single quote character.
+ *
+ * @return a matcher for a single quote
+ */
+ public StringMatcher singleQuoteMatcher() {
+ return SINGLE_QUOTE_MATCHER;
+ }
+
+ /**
+ * Returns a matcher which matches the space character.
+ *
+ * @return a matcher for a space
+ */
+ public StringMatcher spaceMatcher() {
+ return SPACE_MATCHER;
+ }
+
+ /**
+ * Matches the same characters as StringTokenizer, namely space, tab, newline and form feed.
+ *
+ * @return The split matcher
+ */
+ public StringMatcher splitMatcher() {
+ return SPLIT_MATCHER;
+ }
+
+ /**
+ * Creates a matcher from a string.
+ *
+ * @param str
+ * the string to match, null or empty matches nothing
+ * @return a new Matcher for the given String
+ */
+ public StringMatcher stringMatcher(final String str) {
+ if (str == null || str.length() == 0) {
+ return NONE_MATCHER;
+ }
+ return new AbstractStringMatcher.StringMatcher(str);
+ }
+
+ /**
+ * Returns a matcher which matches the tab character.
+ *
+ * @return a matcher for a tab
+ */
+ public StringMatcher tabMatcher() {
+ return TAB_MATCHER;
+ }
+
+ /**
+ * Matches the String trim() whitespace characters.
+ *
+ * @return The trim matcher
+ */
+ public StringMatcher trimMatcher() {
+ return TRIM_MATCHER;
+ }
+
+}
diff --git a/src/main/java/org/apache/commons/text/matcher/package-info.java b/src/main/java/org/apache/commons/text/matcher/package-info.java
index a7a3aae..1ba8f5c 100644
--- a/src/main/java/org/apache/commons/text/matcher/package-info.java
+++ b/src/main/java/org/apache/commons/text/matcher/package-info.java
@@ -1,25 +1,25 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/**
- * <p>
- * Provides algorithms for matching up strings for use with a {@link org.apache.commons.text.StringSubstitutor}. The
- * main class here is {@link org.apache.commons.text.matcher.StringMatcherFactory}
- * </p>
- *
- * @since 1.3
- */
-package org.apache.commons.text.matcher;
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+/**
+ * <p>
+ * Provides algorithms for matching up strings for use with a {@link org.apache.commons.text.StringSubstitutor}. The
+ * main class here is {@link org.apache.commons.text.matcher.StringMatcherFactory}
+ * </p>
+ *
+ * @since 1.3
+ */
+package org.apache.commons.text.matcher;
diff --git a/src/main/java/org/apache/commons/text/translate/CsvTranslators.java b/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
index 69301d6..df95486 100644
--- a/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
+++ b/src/main/java/org/apache/commons/text/translate/CsvTranslators.java
@@ -1,94 +1,94 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-
-import org.apache.commons.lang3.CharUtils;
-import org.apache.commons.lang3.StringUtils;
-
-/**
- * This class holds inner classes for escaping/unescaping Comma Separated Values.
- * <p>
- * In general the use a high level API like <a href="https://commons.apache.org/proper/commons-csv/">Apache Commons
- * CSV</a> should be preferred over these low level classes.
- * </p>
- *
- * @see <a href="https://commons.apache.org/proper/commons-csv/apidocs/index.html">Apache Commons CSV</a>
- */
-public final class CsvTranslators {
-
- /** Comma character. */
- private static final char CSV_DELIMITER = ',';
- /** Quote character. */
- private static final char CSV_QUOTE = '"';
- /** Quote character converted to string. */
- private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
- /** Escaped quote string. */
- private static final String CSV_ESCAPED_QUOTE_STR = CSV_QUOTE_STR + CSV_QUOTE_STR;
- /** CSV key characters in an array. */
- private static final char[] CSV_SEARCH_CHARS =
- new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
-
- /** Hidden constructor. */
- private CsvTranslators() { }
-
- /**
- * Translator for escaping Comma Separated Values.
- */
- public static class CsvEscaper extends SinglePassTranslator {
-
- @Override
- void translateWhole(final CharSequence input, final Writer out) throws IOException {
- final String inputSting = input.toString();
- if (StringUtils.containsNone(inputSting, CSV_SEARCH_CHARS)) {
- out.write(inputSting);
- } else {
- // input needs quoting
- out.write(CSV_QUOTE);
- out.write(StringUtils.replace(inputSting, CSV_QUOTE_STR, CSV_ESCAPED_QUOTE_STR));
- out.write(CSV_QUOTE);
- }
- }
- }
-
- /**
- * Translator for unescaping escaped Comma Separated Value entries.
- */
- public static class CsvUnescaper extends SinglePassTranslator {
-
- @Override
- void translateWhole(final CharSequence input, final Writer out) throws IOException {
- // is input not quoted?
- if (input.charAt(0) != CSV_QUOTE || input.charAt(input.length() - 1) != CSV_QUOTE) {
- out.write(input.toString());
- return;
- }
-
- // strip quotes
- final String quoteless = input.subSequence(1, input.length() - 1).toString();
-
- if (StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS)) {
- // deal with escaped quotes; ie) ""
- out.write(StringUtils.replace(quoteless, CSV_ESCAPED_QUOTE_STR, CSV_QUOTE_STR));
- } else {
- out.write(quoteless);
- }
- }
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.translate;
+
+import java.io.IOException;
+import java.io.Writer;
+
+import org.apache.commons.lang3.CharUtils;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * This class holds inner classes for escaping/unescaping Comma Separated Values.
+ * <p>
+ * In general the use a high level API like <a href="https://commons.apache.org/proper/commons-csv/">Apache Commons
+ * CSV</a> should be preferred over these low level classes.
+ * </p>
+ *
+ * @see <a href="https://commons.apache.org/proper/commons-csv/apidocs/index.html">Apache Commons CSV</a>
+ */
+public final class CsvTranslators {
+
+ /** Comma character. */
+ private static final char CSV_DELIMITER = ',';
+ /** Quote character. */
+ private static final char CSV_QUOTE = '"';
+ /** Quote character converted to string. */
+ private static final String CSV_QUOTE_STR = String.valueOf(CSV_QUOTE);
+ /** Escaped quote string. */
+ private static final String CSV_ESCAPED_QUOTE_STR = CSV_QUOTE_STR + CSV_QUOTE_STR;
+ /** CSV key characters in an array. */
+ private static final char[] CSV_SEARCH_CHARS =
+ new char[] {CSV_DELIMITER, CSV_QUOTE, CharUtils.CR, CharUtils.LF};
+
+ /** Hidden constructor. */
+ private CsvTranslators() { }
+
+ /**
+ * Translator for escaping Comma Separated Values.
+ */
+ public static class CsvEscaper extends SinglePassTranslator {
+
+ @Override
+ void translateWhole(final CharSequence input, final Writer out) throws IOException {
+ final String inputSting = input.toString();
+ if (StringUtils.containsNone(inputSting, CSV_SEARCH_CHARS)) {
+ out.write(inputSting);
+ } else {
+ // input needs quoting
+ out.write(CSV_QUOTE);
+ out.write(StringUtils.replace(inputSting, CSV_QUOTE_STR, CSV_ESCAPED_QUOTE_STR));
+ out.write(CSV_QUOTE);
+ }
+ }
+ }
+
+ /**
+ * Translator for unescaping escaped Comma Separated Value entries.
+ */
+ public static class CsvUnescaper extends SinglePassTranslator {
+
+ @Override
+ void translateWhole(final CharSequence input, final Writer out) throws IOException {
+ // is input not quoted?
+ if (input.charAt(0) != CSV_QUOTE || input.charAt(input.length() - 1) != CSV_QUOTE) {
+ out.write(input.toString());
+ return;
+ }
+
+ // strip quotes
+ final String quoteless = input.subSequence(1, input.length() - 1).toString();
+
+ if (StringUtils.containsAny(quoteless, CSV_SEARCH_CHARS)) {
+ // deal with escaped quotes; ie) ""
+ out.write(StringUtils.replace(quoteless, CSV_ESCAPED_QUOTE_STR, CSV_QUOTE_STR));
+ } else {
+ out.write(quoteless);
+ }
+ }
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java b/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
index 3a1c45b..1b8a7ee 100644
--- a/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
+++ b/src/main/java/org/apache/commons/text/translate/NumericEntityUnescaper.java
@@ -1,138 +1,138 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-import java.util.Arrays;
-import java.util.EnumSet;
-
-/**
- * Translate XML numeric entities of the form &#[xX]?\d+;? to
- * the specific codepoint.
- *
- * Note that the semi-colon is optional.
- *
- * @since 1.0
- */
-public class NumericEntityUnescaper extends CharSequenceTranslator {
-
- /** NumericEntityUnescaper option enum. */
- public enum OPTION { semiColonRequired, semiColonOptional, errorIfNoSemiColon }
-
- /** EnumSet of OPTIONS, given from the constructor. */
- private final EnumSet<OPTION> options;
-
- /**
- * Create a UnicodeUnescaper.
- *
- * The constructor takes a list of options, only one type of which is currently
- * available (whether to allow, error or ignore the semi-colon on the end of a
- * numeric entity to being missing).
- *
- * For example, to support numeric entities without a ';':
- * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
- * and to throw an IllegalArgumentException when they're missing:
- * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
- *
- * Note that the default behavior is to ignore them.
- *
- * @param options to apply to this unescaper
- */
- public NumericEntityUnescaper(final OPTION... options) {
- if (options.length > 0) {
- this.options = EnumSet.copyOf(Arrays.asList(options));
- } else {
- this.options = EnumSet.copyOf(Arrays.asList(OPTION.semiColonRequired));
- }
- }
-
- /**
- * Whether the passed in option is currently set.
- *
- * @param option to check state of
- * @return whether the option is set
- */
- public boolean isSet(final OPTION option) {
- return options != null && options.contains(option);
- }
-
- /**
- * {@inheritDoc}
- */
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- final int seqEnd = input.length();
- // Uses -2 to ensure there is something after the &#
- if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
- int start = index + 2;
- boolean isHex = false;
-
- final char firstChar = input.charAt(start);
- if (firstChar == 'x' || firstChar == 'X') {
- start++;
- isHex = true;
-
- // Check there's more than just an x after the &#
- if (start == seqEnd) {
- return 0;
- }
- }
-
- int end = start;
- // Note that this supports character codes without a ; on the end
- while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9'
- || input.charAt(end) >= 'a' && input.charAt(end) <= 'f'
- || input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
- end++;
- }
-
- final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
-
- if (!semiNext) {
- if (isSet(OPTION.semiColonRequired)) {
- return 0;
- }
- if (isSet(OPTION.errorIfNoSemiColon)) {
- throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
- }
- }
-
- int entityValue;
- try {
- if (isHex) {
- entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
- } else {
- entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
- }
- } catch (final NumberFormatException nfe) {
- return 0;
- }
-
- if (entityValue > 0xFFFF) {
- final char[] chrs = Character.toChars(entityValue);
- out.write(chrs[0]);
- out.write(chrs[1]);
- } else {
- out.write(entityValue);
- }
-
- return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
- }
- return 0;
- }
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.translate;
+
+import java.io.IOException;
+import java.io.Writer;
+import java.util.Arrays;
+import java.util.EnumSet;
+
+/**
+ * Translate XML numeric entities of the form &#[xX]?\d+;? to
+ * the specific codepoint.
+ *
+ * Note that the semi-colon is optional.
+ *
+ * @since 1.0
+ */
+public class NumericEntityUnescaper extends CharSequenceTranslator {
+
+ /** NumericEntityUnescaper option enum. */
+ public enum OPTION { semiColonRequired, semiColonOptional, errorIfNoSemiColon }
+
+ /** EnumSet of OPTIONS, given from the constructor. */
+ private final EnumSet<OPTION> options;
+
+ /**
+ * Create a UnicodeUnescaper.
+ *
+ * The constructor takes a list of options, only one type of which is currently
+ * available (whether to allow, error or ignore the semi-colon on the end of a
+ * numeric entity to being missing).
+ *
+ * For example, to support numeric entities without a ';':
+ * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.semiColonOptional)
+ * and to throw an IllegalArgumentException when they're missing:
+ * new NumericEntityUnescaper(NumericEntityUnescaper.OPTION.errorIfNoSemiColon)
+ *
+ * Note that the default behavior is to ignore them.
+ *
+ * @param options to apply to this unescaper
+ */
+ public NumericEntityUnescaper(final OPTION... options) {
+ if (options.length > 0) {
+ this.options = EnumSet.copyOf(Arrays.asList(options));
+ } else {
+ this.options = EnumSet.copyOf(Arrays.asList(OPTION.semiColonRequired));
+ }
+ }
+
+ /**
+ * Whether the passed in option is currently set.
+ *
+ * @param option to check state of
+ * @return whether the option is set
+ */
+ public boolean isSet(final OPTION option) {
+ return options != null && options.contains(option);
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
+ final int seqEnd = input.length();
+ // Uses -2 to ensure there is something after the &#
+ if (input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
+ int start = index + 2;
+ boolean isHex = false;
+
+ final char firstChar = input.charAt(start);
+ if (firstChar == 'x' || firstChar == 'X') {
+ start++;
+ isHex = true;
+
+ // Check there's more than just an x after the &#
+ if (start == seqEnd) {
+ return 0;
+ }
+ }
+
+ int end = start;
+ // Note that this supports character codes without a ; on the end
+ while (end < seqEnd && (input.charAt(end) >= '0' && input.charAt(end) <= '9'
+ || input.charAt(end) >= 'a' && input.charAt(end) <= 'f'
+ || input.charAt(end) >= 'A' && input.charAt(end) <= 'F')) {
+ end++;
+ }
+
+ final boolean semiNext = end != seqEnd && input.charAt(end) == ';';
+
+ if (!semiNext) {
+ if (isSet(OPTION.semiColonRequired)) {
+ return 0;
+ }
+ if (isSet(OPTION.errorIfNoSemiColon)) {
+ throw new IllegalArgumentException("Semi-colon required at end of numeric entity");
+ }
+ }
+
+ int entityValue;
+ try {
+ if (isHex) {
+ entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
+ } else {
+ entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
+ }
+ } catch (final NumberFormatException nfe) {
+ return 0;
+ }
+
+ if (entityValue > 0xFFFF) {
+ final char[] chrs = Character.toChars(entityValue);
+ out.write(chrs[0]);
+ out.write(chrs[1]);
+ } else {
+ out.write(entityValue);
+ }
+
+ return 2 + end - start + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
+ }
+ return 0;
+ }
+}
diff --git a/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java b/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
index cfd12c9..d61b584 100644
--- a/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
+++ b/src/main/java/org/apache/commons/text/translate/SinglePassTranslator.java
@@ -1,58 +1,58 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.commons.text.translate;
-
-import java.io.IOException;
-import java.io.Writer;
-
-/**
- * Abstract translator for processing whole input in single pass.
- * Handles initial index checking and counting of returned code points.
- */
-abstract class SinglePassTranslator extends CharSequenceTranslator {
-
- @Override
- public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
- if (index != 0) {
- throw new IllegalArgumentException(getClassName() + ".translate(final CharSequence input, final int "
- + "index, final Writer out) can not handle a non-zero index.");
- }
-
- translateWhole(input, out);
-
- return Character.codePointCount(input, index, input.length());
- }
-
- /**
- * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method.
- *
- * @return The name of this or the extending class.
- */
- private String getClassName() {
- final Class<? extends SinglePassTranslator> clazz = this.getClass();
- return clazz.isAnonymousClass() ? clazz.getName() : clazz.getSimpleName();
- }
-
- /**
- * Translate whole set of code points passed in input.
- *
- * @param input CharSequence that is being translated
- * @param out Writer to translate the text to
- * @throws IOException if and only if the Writer produces an IOException
- */
- abstract void translateWhole(CharSequence input, Writer out) throws IOException;
-}
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.text.translate;
+
+import java.io.IOException;
+import java.io.Writer;
+
+/**
+ * Abstract translator for processing whole input in single pass.
+ * Handles initial index checking and counting of returned code points.
+ */
+abstract class SinglePassTranslator extends CharSequenceTranslator {
+
+ @Override
+ public int translate(final CharSequence input, final int index, final Writer out) throws IOException {
+ if (index != 0) {
+ throw new IllegalArgumentException(getClassName() + ".translate(final CharSequence input, final int "
+ + "index, final Writer out) can not handle a non-zero index.");
+ }
+
+ translateWhole(input, out);
+
+ return Character.codePointCount(input, index, input.length());
+ }
+
+ /**
+ * A utility method to be used in the {@link #translate(CharSequence, int, Writer)} method.
+ *
+ * @return The name of this or the extending class.
+ */
+ private String getClassName() {
+ final Class<? extends SinglePassTranslator> clazz = this.getClass();
+ return clazz.isAnonymousClass() ? clazz.getName() : clazz.getSimpleName();
+ }
+
+ /**
+ * Translate whole set of code points passed in input.
+ *
+ * @param input CharSequence that is being translated
+ * @param out Writer to translate the text to
+ * @throws IOException if and only if the Writer produces an IOException
+ */
+ abstract void translateWhole(CharSequence input, Writer out) throws IOException;
+}