Class Strings


  • @ThreadSafe
    public final class Strings
    extends Object
    String-related utility methods.
    Author:
    Randall Hauch, Horia Chiorean
    • Constructor Detail

      • Strings

        private Strings()
    • 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 string
        splitter - the function that splits the input into multiple items; may not be null
        factory - 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 string
        splitter - the function that splits the input into multiple items; may not be null
        factory - 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 string
        delimiter - the character used to delimit the items in the input
        factory - 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 string
        factory - 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 expression Patterns 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 expression Patterns 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 expression Patterns 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 for compiling regular expressions
        Returns:
        the list of regular expression Patterns included in the list; never null
        Throws:
        PatternSyntaxException - if the input includes an invalid regular expression
        IllegalArgumentException - if bit values other than those corresponding to the defined match flags are set in regexFlags
      • 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 two CharSequence instances.
        Parameters:
        str1 - the first character sequence; may be null
        str2 - 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 two String instances are equal ignoring case.
        Parameters:
        str1 - the first character sequence; may be null
        str2 - the second character sequence; may be null
        Returns:
        true if both are null or if the two strings are equal to each other ignoring case, or false otherwise
      • 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 specified delimiter.
        Parameters:
        delimiter - the delimiter that separates each element
        values - the values to join together.
        Returns:
        a new String that is composed of the elements separated by the delimiter
        Throws:
        NullPointerException - If delimiter or elements is null
        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 specified delimiter. All null values are simply ignored.
        Parameters:
        delimiter - the delimiter that separates each element
        values - the values to join together.
        Returns:
        a new String that is composed of the elements separated by the delimiter
        Throws:
        NullPointerException - If delimiter or elements is null
        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 specified delimiter.
        Parameters:
        delimiter - the delimiter that separates each element
        values - the values to join together.
        conversion - the function that converts the supplied values into strings, or returns null if the value is to be excluded
        Returns:
        a new String that is composed of the elements separated by the delimiter
        Throws:
        NullPointerException - If delimiter or elements is null
        See Also:
        String.join(java.lang.CharSequence, java.lang.CharSequence...)
      • 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 null
        predicate - 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 repeat
        numberOfRepeats - 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 null
        length - the minimum desired length; must be positive
        padChar - 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. Unlike justifyLeft(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 null
        length - the desired length; must be positive
        padChar - 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 justified
        str - the string to be right justified; if null, an empty string is used
        width - the desired width of the string; must be positive
        padWithChar - 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 used
        width - the desired width of the string; must be positive
        padWithChar - 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 used
        width - the desired width of the string; must be positive
        padWithChar - 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 used
        width - the desired width of the string; must be positive
        padWithChar - 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 null if 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 value
        defaultValueProvider - 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 null if 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 value
        defaultValue - 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 value
        defaultValue - 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 value
        defaultValue - 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 value
        defaultValue - 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 a Duration.
        Returns:
        the given value as Duration or null if null was passed.
      • duration

        public static String duration​(long durationInMillis)
        For the given duration in milliseconds, obtain a readable representation of the form HHH: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 null
        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
      • 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 string
        splitter - 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 valid UUID.
        Parameters:
        str - the string to evaluate
        Returns:
        true if the string is a valid representation of a UUID, or false otherwise
      • isNullOrEmpty

        public static boolean isNullOrEmpty​(String str)
        Check if the string is empty or null.
        Parameters:
        str - the string to check
        Returns:
        true if 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:
        true if 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 first length characters of the given string.
        Parameters:
        str - The string to get the begin from
        length - The length of the string to return
        Returns:
        null, if the given string is null, the first first length characters of that string otherwise. If the string is shorter than the given number of characters, the string itself will be returned.
      • deriveQuotingChar

        private static Character deriveQuotingChar​(String identifierPart)