Package io.debezium.util
Class Strings
- java.lang.Object
-
- io.debezium.util.Strings
-
@ThreadSafe public final class Strings extends Object
String-related utility methods.- Author:
- Randall Hauch, Horia Chiorean
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static interfaceStrings.CharacterPredicateRepresents a predicate (boolean-valued function) of one character argument.static classStrings.Justifyprivate static classStrings.RegExSplitterA tokenization class used to split a comma-separated list of regular expressions.
-
Field Summary
Fields Modifier and Type Field Description private static StringCURLY_PREFIXprivate static StringCURLY_SUFFIXprivate static StringDEFAULT_DELIMprivate static PatternTIME_PATTERNprivate static StringVAR_DELIM
-
Constructor Summary
Constructors Modifier Constructor Description privateStrings()
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static booleanasBoolean(String value, boolean defaultValue)Parse the supplied string as a boolean value.static doubleasDouble(String value, double defaultValue)Parse the supplied string as a double value.static DurationasDuration(String timeString)Converts the given string (in the format 00:00:00(.0*)) into aDuration.static intasInt(String value, int defaultValue)Parse the supplied string as a integer value.static longasLong(String value, long defaultValue)Parse the supplied string as a long value.static NumberasNumber(String value)Parse the supplied string as a number.static NumberasNumber(String value, Supplier<Number> defaultValueProvider)Parse the supplied string as a number.static intcompareTo(CharSequence str1, CharSequence str2)Compare twoCharSequenceinstances.static StringcreateString(char charToRepeat, int numberOfRepeats)Create a new string containing the specified character repeated a specific number of times.private static CharacterderiveQuotingChar(String identifierPart)static Stringduration(long durationInMillis)For the given duration in milliseconds, obtain a readable representation of the formHHH:MM:SS.mmm, where HHH is the number of hours written in at least 2 digits (e.g., "03") MM is the number of hours written in at least 2 digits (e.g., "05") SS is the number of hours written in at least 2 digits (e.g., "09") mmm is the fractional part of seconds, written with 1-3 digits (any trailing zeros are dropped)static booleanequalsIgnoreCase(String str1, String str2)Check whether the twoStringinstances are equal ignoring case.static StringgetBegin(String str, int length)Returns the firstlengthcharacters of the given string.static StringgetStackTrace(Throwable throwable)Get the stack trace of the supplied exception.static byte[]hexStringToByteArray(String hexString)Restores a byte array that is encoded as a hex string.static booleanisNullOrEmpty(String str)Check if the string is empty or null.static booleanisNumeric(String str)Check if the string contains only digits.static booleanisUuid(String str)Determine if the supplied string is a validUUID.static Stringjoin(CharSequence delimiter, int[] values)Returns a new String composed of the supplied integer values joined together with a copy of the specifieddelimiter.static <T> Stringjoin(CharSequence delimiter, Iterable<T> values)Returns a new String composed of the supplied values joined together with a copy of the specifieddelimiter.static <T> Stringjoin(CharSequence delimiter, Iterable<T> values, Function<T,String> conversion)Returns a new String composed of the supplied values joined together with a copy of the specifieddelimiter.static Stringjustify(Strings.Justify justify, String str, int width, char padWithChar)Justify the contents of the string.static StringjustifyCenter(String str, int width, char padWithChar)Center the contents of the string.static StringjustifyLeft(String str, int width, char padWithChar)Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the resulting string is of the desired length.protected static StringjustifyLeft(String str, int width, char padWithChar, boolean trimWhitespace)static StringjustifyRight(String str, int width, char padWithChar)Right justify the contents of the string, ensuring that the string ends at the last character.static <T> List<T>listOf(String input, Function<String,String[]> splitter, Function<String,T> factory)Generate the list of values that are included in the list.static List<Pattern>listOfRegex(String input, int regexFlags)Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.static Stringpad(String original, int length, char padChar)Pad the string with the specific character to ensure the string is at least the specified length.static StringreplaceVariables(String value, Function<String,String> replacementsByVariableName)Look in the supplied value for variables and replace them with values from the supplied lookup function.static Function<String,String>replaceVariablesWith(Function<String,String> replacementsByVariableName)Obtain a function that will replace variables in the supplied value with values from the supplied lookup function.static StringsetLength(String original, int length, char padChar)Set the length of the string, padding with the supplied character if the supplied string is shorter than desired, or truncating the string if it is longer than desired.static <T> Set<T>setOf(String input, char delimiter, Function<String,T> factory)Generate the set of values that are included in the list delimited by the given delimiter.static <T> Set<T>setOf(String input, Function<String,String[]> splitter, Function<String,T> factory)Generate the set of values that are included in the list.static <T> Set<T>setOf(String input, Function<String,T> factory)Generate the set of values that are included in the list separated by commas.static Set<Pattern>setOfRegex(String input)Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.static Set<Pattern>setOfRegex(String input, int regexFlags)Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.private static List<String>split(String str, String splitter)Split a string into pieces based on delimiters.static List<String>splitLines(String content)Split the supplied content into lines, returning each line as an element in the returned list.static booleanstartsWithIgnoreCase(String str, String prefix)Whether the given string begins with the given prefix, ignoring casing.static Stringtrim(String str)Trim away any leading or trailing whitespace characters.static Stringtrim(String str, Strings.CharacterPredicate predicate)Trim away any leading or trailing characters that satisfy the supplied predicatestatic StringunquoteIdentifierPart(String identifierPart)Unquotes the given identifier part (e.g.
-
-
-
Field Detail
-
TIME_PATTERN
private static final Pattern TIME_PATTERN
-
CURLY_PREFIX
private static final String CURLY_PREFIX
- See Also:
- Constant Field Values
-
CURLY_SUFFIX
private static final String CURLY_SUFFIX
- See Also:
- Constant Field Values
-
VAR_DELIM
private static final String VAR_DELIM
- See Also:
- Constant Field Values
-
DEFAULT_DELIM
private static final String DEFAULT_DELIM
- See Also:
- Constant Field Values
-
-
Method Detail
-
setOf
public static <T> Set<T> setOf(String input, Function<String,String[]> splitter, Function<String,T> factory)
Generate the set of values that are included in the list.- Parameters:
input- the input stringsplitter- the function that splits the input into multiple items; may not be nullfactory- the factory for creating string items into filter matches; may not be null- Returns:
- the set of objects included in the list; never null
-
listOf
public static <T> List<T> listOf(String input, Function<String,String[]> splitter, Function<String,T> factory)
Generate the list of values that are included in the list.- Parameters:
input- the input stringsplitter- the function that splits the input into multiple items; may not be nullfactory- the factory for creating string items into filter matches; may not be null- Returns:
- the list of objects included in the list; never null
-
setOf
public static <T> Set<T> setOf(String input, char delimiter, Function<String,T> factory)
Generate the set of values that are included in the list delimited by the given delimiter.- Parameters:
input- the input stringdelimiter- the character used to delimit the items in the inputfactory- the factory for creating string items into filter matches; may not be null- Returns:
- the set of objects included in the list; never null
-
setOf
public static <T> Set<T> setOf(String input, Function<String,T> factory)
Generate the set of values that are included in the list separated by commas.- Parameters:
input- the input stringfactory- the factory for creating string items into filter matches; may not be null- Returns:
- the set of objects included in the list; never null
-
setOfRegex
public static Set<Pattern> setOfRegex(String input, int regexFlags)
Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.- Parameters:
input- the input string with comma-separated regular expressions. Comma can be escaped with backslash.- Returns:
- the set of regular expression
Patterns included within the given string; never null - Throws:
PatternSyntaxException- if the input includes an invalid regular expression
-
setOfRegex
public static Set<Pattern> setOfRegex(String input)
Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.- Parameters:
input- the input string with comma-separated regular expressions. Comma can be escaped with backslash.- Returns:
- the set of regular expression
Patterns included within the given string; never null - Throws:
PatternSyntaxException- if the input includes an invalid regular expression
-
listOfRegex
public static List<Pattern> listOfRegex(String input, int regexFlags)
Generate the set of regular expressionPatterns that are specified in the string containing comma-separated regular expressions.- Parameters:
input- the input string with comma-separated regular expressions. Comma can be escaped with backslash.regexFlags- the flags forcompiling regular expressions- Returns:
- the list of regular expression
Patterns included in the list; never null - Throws:
PatternSyntaxException- if the input includes an invalid regular expressionIllegalArgumentException- if bit values other than those corresponding to the defined match flags are set inregexFlags
-
splitLines
public static List<String> splitLines(String content)
Split the supplied content into lines, returning each line as an element in the returned list.- Parameters:
content- the string content that is to be split- Returns:
- the list of lines; never null but may be an empty (unmodifiable) list if the supplied content is null or empty
-
compareTo
public static int compareTo(CharSequence str1, CharSequence str2)
Compare twoCharSequenceinstances.- Parameters:
str1- the first character sequence; may be nullstr2- the second character sequence; may be null- Returns:
- a negative integer if the first sequence is less than the second, zero if the sequence are equivalent (including if both are null), or a positive integer if the first sequence is greater than the second
-
equalsIgnoreCase
public static boolean equalsIgnoreCase(String str1, String str2)
Check whether the twoStringinstances are equal ignoring case.- Parameters:
str1- the first character sequence; may be nullstr2- the second character sequence; may be null- Returns:
trueif both are null or if the two strings are equal to each other ignoring case, orfalseotherwise
-
join
public static String join(CharSequence delimiter, int[] values)
Returns a new String composed of the supplied integer values joined together with a copy of the specifieddelimiter.- Parameters:
delimiter- the delimiter that separates each elementvalues- the values to join together.- Returns:
- a new
Stringthat is composed of theelementsseparated by thedelimiter - Throws:
NullPointerException- Ifdelimiterorelementsisnull- See Also:
String.join(java.lang.CharSequence, java.lang.CharSequence...)
-
join
public static <T> String join(CharSequence delimiter, Iterable<T> values)
Returns a new String composed of the supplied values joined together with a copy of the specifieddelimiter. Allnullvalues are simply ignored.- Parameters:
delimiter- the delimiter that separates each elementvalues- the values to join together.- Returns:
- a new
Stringthat is composed of theelementsseparated by thedelimiter - Throws:
NullPointerException- Ifdelimiterorelementsisnull- See Also:
String.join(java.lang.CharSequence, java.lang.CharSequence...)
-
join
public static <T> String join(CharSequence delimiter, Iterable<T> values, Function<T,String> conversion)
Returns a new String composed of the supplied values joined together with a copy of the specifieddelimiter.- Parameters:
delimiter- the delimiter that separates each elementvalues- the values to join together.conversion- the function that converts the supplied values into strings, or returnsnullif the value is to be excluded- Returns:
- a new
Stringthat is composed of theelementsseparated by thedelimiter - Throws:
NullPointerException- Ifdelimiterorelementsisnull- See Also:
String.join(java.lang.CharSequence, java.lang.CharSequence...)
-
trim
public static String trim(String str)
Trim away any leading or trailing whitespace characters.This is semantically equivalent to
String.trim()but instead usestrim(String, CharacterPredicate).- Parameters:
str- the string to be trimmed; may not be null- Returns:
- the trimmed string; never null
- See Also:
trim(String,CharacterPredicate)
-
trim
public static String trim(String str, Strings.CharacterPredicate predicate)
Trim away any leading or trailing characters that satisfy the supplied predicate- Parameters:
str- the string to be trimmed; may not be nullpredicate- the predicate function; may not be null- Returns:
- the trimmed string; never null
- See Also:
trim(String)
-
createString
public static String createString(char charToRepeat, int numberOfRepeats)
Create a new string containing the specified character repeated a specific number of times.- Parameters:
charToRepeat- the character to repeatnumberOfRepeats- the number of times the character is to repeat in the result; must be greater than 0- Returns:
- the resulting string
-
pad
public static String pad(String original, int length, char padChar)
Pad the string with the specific character to ensure the string is at least the specified length.- Parameters:
original- the string to be padded; may not be nulllength- the minimum desired length; must be positivepadChar- the character to use for padding, if the supplied string is not long enough- Returns:
- the padded string of the desired length
- See Also:
justifyLeft(String, int, char)
-
setLength
public static String setLength(String original, int length, char padChar)
Set the length of the string, padding with the supplied character if the supplied string is shorter than desired, or truncating the string if it is longer than desired. UnlikejustifyLeft(String, int, char), this method does not remove leading and trailing whitespace.- Parameters:
original- the string for which the length is to be set; may not be nulllength- the desired length; must be positivepadChar- the character to use for padding, if the supplied string is not long enough- Returns:
- the string of the desired length
- See Also:
justifyLeft(String, int, char)
-
justify
public static String justify(Strings.Justify justify, String str, int width, char padWithChar)
Justify the contents of the string.- Parameters:
justify- the way in which the string is to be justifiedstr- the string to be right justified; if null, an empty string is usedwidth- the desired width of the string; must be positivepadWithChar- the character to use for padding, if needed- Returns:
- the right justified string
-
justifyRight
public static String justifyRight(String str, int width, char padWithChar)
Right justify the contents of the string, ensuring that the string ends at the last character. If the supplied string is longer than the desired width, the leading characters are removed so that the last character in the supplied string at the last position. If the supplied string is shorter than the desired width, the padding character is inserted one or more times such that the last character in the supplied string appears as the last character in the resulting string and that the length matches that specified.- Parameters:
str- the string to be right justified; if null, an empty string is usedwidth- the desired width of the string; must be positivepadWithChar- the character to use for padding, if needed- Returns:
- the right justified string
-
justifyLeft
public static String justifyLeft(String str, int width, char padWithChar)
Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the resulting string is of the desired length. If the supplied string is longer than the desired width, it is truncated to the specified length. If the supplied string is shorter than the desired width, the padding character is added to the end of the string one or more times such that the length is that specified. All leading and trailing whitespace is removed.- Parameters:
str- the string to be left justified; if null, an empty string is usedwidth- the desired width of the string; must be positivepadWithChar- the character to use for padding, if needed- Returns:
- the left justified string
- See Also:
setLength(String, int, char)
-
justifyLeft
protected static String justifyLeft(String str, int width, char padWithChar, boolean trimWhitespace)
-
justifyCenter
public static String justifyCenter(String str, int width, char padWithChar)
Center the contents of the string. If the supplied string is longer than the desired width, it is truncated to the specified length. If the supplied string is shorter than the desired width, padding characters are added to the beginning and end of the string such that the length is that specified; one additional padding character is prepended if required. All leading and trailing whitespace is removed before centering.- Parameters:
str- the string to be left justified; if null, an empty string is usedwidth- the desired width of the string; must be positivepadWithChar- the character to use for padding, if needed- Returns:
- the left justified string
- See Also:
setLength(String, int, char)
-
getStackTrace
public static String getStackTrace(Throwable throwable)
Get the stack trace of the supplied exception.- Parameters:
throwable- the exception for which the stack trace is to be returned- Returns:
- the stack trace, or null if the supplied exception is null
-
asNumber
public static Number asNumber(String value)
Parse the supplied string as a number.- Parameters:
value- the string representation of a integer value- Returns:
- the number, or
nullif the value is not a number
-
asNumber
public static Number asNumber(String value, Supplier<Number> defaultValueProvider)
Parse the supplied string as a number.- Parameters:
value- the string representation of a integer valuedefaultValueProvider- the function that returns a value to be used when the string value is null or cannot be parsed as a number; may be null if no default value is to be used- Returns:
- the number, or
nullif the value is not a number and no default value is supplied
-
asInt
public static int asInt(String value, int defaultValue)
Parse the supplied string as a integer value.- Parameters:
value- the string representation of a integer valuedefaultValue- the value to return if the string value is null or cannot be parsed as an int- Returns:
- the int value
-
asLong
public static long asLong(String value, long defaultValue)
Parse the supplied string as a long value.- Parameters:
value- the string representation of a long valuedefaultValue- the value to return if the string value is null or cannot be parsed as a long- Returns:
- the long value
-
asDouble
public static double asDouble(String value, double defaultValue)
Parse the supplied string as a double value.- Parameters:
value- the string representation of a double valuedefaultValue- the value to return if the string value is null or cannot be parsed as a double- Returns:
- the double value
-
asBoolean
public static boolean asBoolean(String value, boolean defaultValue)
Parse the supplied string as a boolean value.- Parameters:
value- the string representation of a boolean valuedefaultValue- the value to return if the string value is null or cannot be parsed as a boolean- Returns:
- the boolean value
-
asDuration
public static Duration asDuration(String timeString)
Converts the given string (in the format 00:00:00(.0*)) into aDuration.- Returns:
- the given value as
Durationornullifnullwas passed.
-
duration
public static String duration(long durationInMillis)
For the given duration in milliseconds, obtain a readable representation of the formHHH:MM:SS.mmm, where- HHH
- is the number of hours written in at least 2 digits (e.g., "03")
- MM
- is the number of hours written in at least 2 digits (e.g., "05")
- SS
- is the number of hours written in at least 2 digits (e.g., "09")
- mmm
- is the fractional part of seconds, written with 1-3 digits (any trailing zeros are dropped)
- Parameters:
durationInMillis- the duration in milliseconds- Returns:
- the readable duration.
-
replaceVariablesWith
public static Function<String,String> replaceVariablesWith(Function<String,String> replacementsByVariableName)
Obtain a function that will replace variables in the supplied value with values from the supplied lookup function.Variables may appear anywhere within a string value, and multiple variables can be used within the same value. Variables take the form:
variable := '${' variableNames [ ':' defaultValue ] '}' variableNames := variableName [ ',' variableNames ] variableName := // any characters except ',' and ':' and '}' defaultValue := // any characters except '}'Note that variableName is the name used to look up a the property. Notice that the syntax supports multiple variables. The logic will process the variables from let to right, until an existing property is found. And at that point, it will stop and will not attempt to find values for the other variables.- Parameters:
replacementsByVariableName- the function used to find the replacements for variable names; may not be null- Returns:
- the function that will replace variables in supplied strings; never null
-
replaceVariables
public static String replaceVariables(String value, Function<String,String> replacementsByVariableName)
Look in the supplied value for variables and replace them with values from the supplied lookup function.Variables may appear anywhere within a string value, and multiple variables can be used within the same value. Variables take the form:
variable := '${' variableNames [ ':' defaultValue ] '}' variableNames := variableName [ ',' variableNames ] variableName := // any characters except ',' and ':' and '}' defaultValue := // any characters except '}'Note that variableName is the name used to look up a the property. Notice that the syntax supports multiple variables. The logic will process the variables from let to right, until an existing property is found. And at that point, it will stop and will not attempt to find values for the other variables.- Parameters:
value- the content in which the variables are to be found and replaced; may not be nullreplacementsByVariableName- the function used to find the replacements for variable names; may not be null- Returns:
- the function that will replace variables in supplied strings; never null
-
split
private static List<String> split(String str, String splitter)
Split a string into pieces based on delimiters. Similar to the Perl function of the same name. The delimiters are not included in the returned strings.- Parameters:
str- Full stringsplitter- Characters to split on- Returns:
- List of String pieces from full string
-
isUuid
public static boolean isUuid(String str)
Determine if the supplied string is a validUUID.- Parameters:
str- the string to evaluate- Returns:
trueif the string is a valid representation of a UUID, orfalseotherwise
-
isNullOrEmpty
public static boolean isNullOrEmpty(String str)
Check if the string is empty or null.- Parameters:
str- the string to check- Returns:
trueif the string is empty or null
-
isNumeric
public static boolean isNumeric(String str)
Check if the string contains only digits.- Parameters:
str- the string to check- Returns:
trueif only contains digits
-
unquoteIdentifierPart
public static String unquoteIdentifierPart(String identifierPart)
Unquotes the given identifier part (e.g. an unqualified table name), if the first character is one of the supported quoting characters (single quote, double quote and back-tick) and the last character equals to the first character. Otherwise, the original string will be returned.
-
hexStringToByteArray
public static byte[] hexStringToByteArray(String hexString)
Restores a byte array that is encoded as a hex string.
-
startsWithIgnoreCase
public static boolean startsWithIgnoreCase(String str, String prefix)
Whether the given string begins with the given prefix, ignoring casing. Copied from https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/StringUtils.java.
-
getBegin
public static String getBegin(String str, int length)
Returns the firstlengthcharacters of the given string.- Parameters:
str- The string to get the begin fromlength- The length of the string to return- Returns:
null, if the given string isnull, the first firstlengthcharacters of that string otherwise. If the string is shorter than the given number of characters, the string itself will be returned.
-
-