Class StringHelper


  • public final class StringHelper
    extends java.lang.Object
    Some handy methods for strings.
    Author:
    harald
    • Field Summary

      Fields 
      Modifier and Type Field Description
      static java.util.function.Function<java.lang.String,​java.lang.String> stringNormalizer
      The default normalizer used within the application.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void blank​(char[] buf)
      Null-safe char array filler.
      Fills with blanks.
      static int countOccurrences​(java.lang.String str, char c)
      Counts the number of occurrences of a given character in a string.
      static java.lang.String digitToString​(java.lang.Character digit)
      Gets the word-string for a digit.
      Example:
      static boolean equalsIgnoreCase​(java.lang.String a, java.lang.String b)
      Null safe String.equalsIgnoreCase(String).
      static void fill​(char[] buf, char val)
      Null-safe char array filler.
      static java.lang.String fillLeft​(java.lang.String str, int length, char filler)
      Fills up a string from the left with a filler character to match a given length.
      If the string is already longer, nothing happens.
      static java.lang.String fillRight​(java.lang.String str, int length, char filler)
      Fills up a string to the right with a filler character to match a given length.
      If the string is already longer, nothing happens.
      static java.lang.String firstBefore​(java.lang.String str, char delimiter)
      Gets the part of a string before a given delimiter.
      static java.lang.String firstLine​(java.lang.String str)
      Gets the first line from a multi-line string.
      static java.lang.String firstToLower​(java.lang.String str)
      Converts the first character of string to uppercase.
      static java.lang.String firstToUpper​(java.lang.String str)
      Converts the first character of string to uppercase.
      static java.lang.String getArchitecture()
      Gets the name of the architecture from the system properties.
      static java.lang.String getContinuedLine​(java.lang.String line)
      Checks whether given string introduces a continuation line.
      static int getMaxLogCollectionSize()
      Gets the size limit of collections to be logged.
      static java.lang.String getPlainClassName​(java.lang.String className)
      Gets a classname without any optional generics.
      static java.lang.String getPlatform()
      Gets the name of the operating system from the system properties.
      static java.lang.String hash​(java.lang.String algorithm, char[] salt, char[] input)
      Builds a hash from an array of chars.
      Note that this method converts the characters to bytes via toBytes(char[]) before applying the hash.
      static int indexAnyOf​(java.lang.String str, java.lang.String anyOf)
      Returns the first index of any of the given characters.
      static boolean isAllDigits​(java.lang.String str)
      checks if a string contains only digits, i.e.
      static boolean isAllDigits​(java.lang.String str, boolean whitespaceAllowed)
      Checks if a string contains only digits or whitespaces, i.e.
      static boolean isAllWhitespace​(java.lang.String str)
      Checks if string contains only whitespaces.
      static boolean isFQCN​(java.lang.String className)
      Checks whether given string is a fully qualified classname (FQCN).
      The class must belong to a package!
      static boolean isReservedWord​(java.lang.String word)
      Returns whether given string is a reserved java keyword.
      static boolean isValidJavaClassName​(java.lang.String className)
      Checks that given string is a valid Java classname.
      Both classnames with a full classpath or without are validated.
      static boolean isValidJavaIdentifier​(java.lang.String str)
      Returns whether the given string is a valid java identifier.
      static boolean isValidJavaPackageName​(java.lang.String packageName)
      Checks that given string is a valid Java packagename.
      This is very restrictive verification.
      static java.lang.String lastAfter​(java.lang.String str, char delimiter)
      Gets the part of a string after a given delimiter.
      static java.lang.String normalize​(java.lang.String str)
      Normalizes a string (phonetically) for use as PDO.normText using stringNormalizer.
      static java.lang.String normalize​(java.lang.String str, java.util.function.Function<java.lang.String,​java.lang.String> normalizer)
      Normalizes a string (phonetically) for use as PDO.normText.
      static java.lang.String objectArrayToString​(java.lang.Object[] objArray, java.lang.String separator)
      Creates a string from an object array.
      static java.lang.String objectToLoggableString​(java.lang.Object object)
      Converts a value to a loggable string.
      static java.lang.String parseString​(java.lang.String str)
      Parses a string.
      The string may be enclosed in double- or single quotes which will be removed.
      static java.lang.String readTextFromResource​(java.lang.Class<?> caller, java.lang.String resourceName)
      Reads a textfile from a resource.
      static java.lang.String removeTrailingText​(java.lang.String str, java.lang.String trail)
      Removes a trailing text from a string.
      static void setMaxLogCollectionSize​(int maxLogCollectionSize)
      Sets the size limit of collections to be logged.
      If an object is logged and it is a collection and the size exceeds maxLogCollectionSize, only the number of items is logged in objectToLoggableString(java.lang.Object) instead of each item.
      static java.util.List<java.lang.String> split​(java.lang.String str, java.lang.String delimiters)
      Splits a string keeping strings together.
      The strings may be enclosed in double- or single quotes which will not be removed.
      static java.lang.String stripEnclosingDoubleQuotes​(java.lang.String str)
      Strips enclosing double quotes.
      static java.lang.String toAsciiLetterOrDigit​(java.lang.String str)
      Converts to string containing only the letters A-z or digits.
      All other characters will be converted to an underscore.
      static byte[] toBytes​(char c)
      Converts a single (unicode) char to a byte-array.
      static byte[] toBytes​(char[] chars)
      Converts a char-array to a byte-array.
      static java.lang.String toCamelCase​(java.lang.String str)
      Converts a dotted path to camelCase.
      Example:
      "alpha.beta.gamma" is converted to "alphaBetaGamma".
      static char[] toCharArray​(java.lang.String str)
      Null-safe string to a char-array conversion.
      static java.lang.String toDoubleQuotes​(java.lang.String str)
      Takes a string, surrounds it with double-quotes and escapes all double-quotes already in the string according to Unix rules.
      static java.lang.String toDTA​(java.lang.String str)
      Filters illegal chars for DTA-Files (German "DATENAUSTAUSCH" banking format).
      static java.lang.String toFixedLength​(java.lang.String str, int length)
      Takes a string and returns one with a given length, cutting or filling up with spaces, whatever appropriate.
      static java.lang.String toFixedLength​(java.lang.String str, int length, char filler)
      Takes a string and returns one with a given length, cutting or filling up with fillchars, whatever appropriate.
      static java.lang.String toFixedLengthLeftFill​(java.lang.String str, int length)
      Takes a string and returns one with a given length, cutting or filling up with spaces from the left, whatever appropriate.
      static java.lang.String toFixedLengthLeftFill​(java.lang.String str, int length, char filler)
      Takes a string and returns one with a given length, cutting or filling up with fillchars from the left, whatever appropriate.
      static java.lang.String toHexString​(byte[] binaryData)
      Creates a human-readable hex-String out of a byte-array (e.g.
      static java.lang.String toHTML​(java.lang.String text)
      Converts a multiline string to an HTML-string that can be displayed in a label.
      static java.lang.String toLower​(java.lang.String str)
      Converts a string to lowercase allowing null values.
      static java.lang.String toParsableString​(java.lang.String str)
      Converts a string to a string parsable by parseString(java.lang.String).
      static java.lang.String toUpper​(java.lang.String str)
      Converts a string to uppercase allowing null values.
      static java.lang.String toVarName​(java.lang.String str)
      Filters illegal chars for Java variable names.
      static java.lang.String trim​(java.lang.String s)
      Trims a string.
      static java.lang.String trim​(java.lang.String s, int max)
      Trims a string.
      static java.lang.String trimLeft​(java.lang.String str, char filler)
      Cuts leading characters.
      static java.lang.String trimRight​(java.lang.String str, char filler)
      Cuts trailing characters.
      static java.lang.String unDiacrit​(java.lang.String str, boolean keepLength)
      Converts special unicode characters (so-called diacrits) to standard ascii.
      Supports also special german and northern european "umlauts".
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • stringNormalizer

        public static java.util.function.Function<java.lang.String,​java.lang.String> stringNormalizer
        The default normalizer used within the application. Defaults to DefaultStringNormalizer.
    • Method Detail

      • setMaxLogCollectionSize

        public static void setMaxLogCollectionSize​(int maxLogCollectionSize)
        Sets the size limit of collections to be logged.
        If an object is logged and it is a collection and the size exceeds maxLogCollectionSize, only the number of items is logged in objectToLoggableString(java.lang.Object) instead of each item.
        Parameters:
        maxLogCollectionSize - the limit
      • getMaxLogCollectionSize

        public static int getMaxLogCollectionSize()
        Gets the size limit of collections to be logged.
        Returns:
        the limit (default is 10)
      • equalsIgnoreCase

        public static boolean equalsIgnoreCase​(java.lang.String a,
                                               java.lang.String b)
        Null safe String.equalsIgnoreCase(String).
        Parameters:
        a - first string, may be null
        b - second string, may be null
        Returns:
        true if equal ignoring the case or both are null
      • toUpper

        public static java.lang.String toUpper​(java.lang.String str)
        Converts a string to uppercase allowing null values.
        Parameters:
        str - the string
        Returns:
        the uppercase string or null
      • toLower

        public static java.lang.String toLower​(java.lang.String str)
        Converts a string to lowercase allowing null values.
        Parameters:
        str - the string
        Returns:
        the lowercase string or null
      • firstToUpper

        public static java.lang.String firstToUpper​(java.lang.String str)
        Converts the first character of string to uppercase.
        Parameters:
        str - the string
        Returns:
        the converted string
      • firstToLower

        public static java.lang.String firstToLower​(java.lang.String str)
        Converts the first character of string to uppercase.
        Parameters:
        str - the string
        Returns:
        the converted string
      • getPlainClassName

        public static java.lang.String getPlainClassName​(java.lang.String className)
        Gets a classname without any optional generics.
        Parameters:
        className - the original classname
        Returns:
        classname without generics
      • getContinuedLine

        public static java.lang.String getContinuedLine​(java.lang.String line)
        Checks whether given string introduces a continuation line.

        This is the case if the last character is an unquoted backslash.

        Parameters:
        line - the source line
        Returns:
        null if line does not introduce a continuation line
      • indexAnyOf

        public static int indexAnyOf​(java.lang.String str,
                                     java.lang.String anyOf)
        Returns the first index of any of the given characters.
        Parameters:
        str - the string
        anyOf - the characters
        Returns:
        the index to the first character found, -1 if no such character
      • toDoubleQuotes

        public static java.lang.String toDoubleQuotes​(java.lang.String str)
        Takes a string, surrounds it with double-quotes and escapes all double-quotes already in the string according to Unix rules. Example:
         Length 5" --> "Length 5\""
         
        Parameters:
        str - the string
        Returns:
        the string in double quotes
      • parseString

        public static java.lang.String parseString​(java.lang.String str)
        Parses a string.
        The string may be enclosed in double- or single quotes which will be removed. Those special characters may be escaped by a backslash. The backslash itself can be written as a double backslash. Special escapes are:

        \n = new line \r = carriage return \t = tab \f = form feed

        Parameters:
        str - the source string
        Returns:
        a string, never null
      • toParsableString

        public static java.lang.String toParsableString​(java.lang.String str)
        Converts a string to a string parsable by parseString(java.lang.String).
        Parameters:
        str - the string
        Returns:
        the parsable string
      • split

        public static java.util.List<java.lang.String> split​(java.lang.String str,
                                                             java.lang.String delimiters)
        Splits a string keeping strings together.
        The strings may be enclosed in double- or single quotes which will not be removed. Those special characters may be escaped by a backslash. The backslash itself can be written as a double backslash. Special escapes are:

        \n = new line \r = carriage return \t = tab \f = form feed

        Parameters:
        str - the string
        delimiters - the delimiter characters
        Returns:
        the strings, never null
      • isFQCN

        public static boolean isFQCN​(java.lang.String className)
        Checks whether given string is a fully qualified classname (FQCN).
        The class must belong to a package!
        Parameters:
        className - the classname
        Returns:
        true if FQCN
      • isValidJavaClassName

        public static boolean isValidJavaClassName​(java.lang.String className)
        Checks that given string is a valid Java classname.
        Both classnames with a full classpath or without are validated.
        Parameters:
        className - the classname
        Returns:
        true if valid
      • isValidJavaPackageName

        public static boolean isValidJavaPackageName​(java.lang.String packageName)
        Checks that given string is a valid Java packagename.
        This is very restrictive verification. Packagenames must be all lowercase alphabetic or digits and must contain only dots and underscores.
        Parameters:
        packageName - the packagename
        Returns:
        true if valid
      • isValidJavaIdentifier

        public static boolean isValidJavaIdentifier​(java.lang.String str)
        Returns whether the given string is a valid java identifier.
        Parameters:
        str - the string
        Returns:
        true if valid, false if not
      • readTextFromResource

        public static java.lang.String readTextFromResource​(java.lang.Class<?> caller,
                                                            java.lang.String resourceName)
                                                     throws java.io.IOException
        Reads a textfile from a resource.

        Example:

           String model = StringHelper.readTextFromResource("/org/tentackle/model/TestModel.txt");
         
        Parameters:
        caller - the caller class, null to determine via Stackwalker
        resourceName - the name of the resource
        Returns:
        the loaded text
        Throws:
        java.io.IOException - if loading failed
        java.io.FileNotFoundException - if no such resource found
      • isAllWhitespace

        public static boolean isAllWhitespace​(java.lang.String str)
        Checks if string contains only whitespaces.
        Parameters:
        str - the string to check
        Returns:
        true if null, empty or all whitespace, false if at least one non-whitespace-character found
      • isReservedWord

        public static boolean isReservedWord​(java.lang.String word)
        Returns whether given string is a reserved java keyword.
        Parameters:
        word - the string to test
        Returns:
        true if java reserved word
      • digitToString

        public static java.lang.String digitToString​(java.lang.Character digit)
        Gets the word-string for a digit.
        Example:
         '0' --> "zero"
         
        Parameters:
        digit - the digit character
        Returns:
        the word-string
      • unDiacrit

        public static java.lang.String unDiacrit​(java.lang.String str,
                                                 boolean keepLength)
        Converts special unicode characters (so-called diacrits) to standard ascii.
        Supports also special german and northern european "umlauts".
        Parameters:
        str - the string to be converted
        keepLength - true if the length should be kept, i.e. no Ä to AE, but to A
        Returns:
        the converted string
      • normalize

        public static java.lang.String normalize​(java.lang.String str,
                                                 java.util.function.Function<java.lang.String,​java.lang.String> normalizer)
        Normalizes a string (phonetically) for use as PDO.normText.
        Parameters:
        str - the string to be normalized
        normalizer - the normalizer to use, null = global default
        Returns:
        the normalized string
      • normalize

        public static java.lang.String normalize​(java.lang.String str)
        Normalizes a string (phonetically) for use as PDO.normText using stringNormalizer.
        Parameters:
        str - the string to be normalized
        Returns:
        the normalized string
      • stripEnclosingDoubleQuotes

        public static java.lang.String stripEnclosingDoubleQuotes​(java.lang.String str)
        Strips enclosing double quotes.
        Parameters:
        str - the original string
        Returns:
        the string with its double quotes removed
      • toFixedLength

        public static java.lang.String toFixedLength​(java.lang.String str,
                                                     int length,
                                                     char filler)
        Takes a string and returns one with a given length, cutting or filling up with fillchars, whatever appropriate.
        Parameters:
        str - the string
        length - the length of the returned string
        filler - the character to fill up if str is too short
        Returns:
        the string with the desired length
      • toFixedLength

        public static java.lang.String toFixedLength​(java.lang.String str,
                                                     int length)
        Takes a string and returns one with a given length, cutting or filling up with spaces, whatever appropriate.
        Parameters:
        str - the string
        length - the length of the returned string
        Returns:
        the string with the desired length
      • toFixedLengthLeftFill

        public static java.lang.String toFixedLengthLeftFill​(java.lang.String str,
                                                             int length,
                                                             char filler)
        Takes a string and returns one with a given length, cutting or filling up with fillchars from the left, whatever appropriate.
        Parameters:
        str - the string
        length - the length of the returned string
        filler - the character to fill up if str is too short
        Returns:
        the string with the desired length
      • toFixedLengthLeftFill

        public static java.lang.String toFixedLengthLeftFill​(java.lang.String str,
                                                             int length)
        Takes a string and returns one with a given length, cutting or filling up with spaces from the left, whatever appropriate.
        Parameters:
        str - the string
        length - the length of the returned string
        Returns:
        the string with the desired length
      • toDTA

        public static java.lang.String toDTA​(java.lang.String str)
        Filters illegal chars for DTA-Files (German "DATENAUSTAUSCH" banking format).
        Parameters:
        str - the string
        Returns:
        the DTA conform string
      • toVarName

        public static java.lang.String toVarName​(java.lang.String str)
        Filters illegal chars for Java variable names.
        Parameters:
        str - the string
        Returns:
        the java conform string
      • toCamelCase

        public static java.lang.String toCamelCase​(java.lang.String str)
        Converts a dotted path to camelCase.
        Example:
        "alpha.beta.gamma" is converted to "alphaBetaGamma".
        Parameters:
        str - the dotted path
        Returns:
        the camel case path
      • isAllDigits

        public static boolean isAllDigits​(java.lang.String str,
                                          boolean whitespaceAllowed)
        Checks if a string contains only digits or whitespaces, i.e. no illegal char in a number string.
        Parameters:
        str - the string to check
        whitespaceAllowed - true if whitespaces are allowed
        Returns:
        true if no illegal char detected, false otherwise
      • isAllDigits

        public static boolean isAllDigits​(java.lang.String str)
        checks if a string contains only digits, i.e. no non-number char in string, even no whitespace.
        Parameters:
        str - the string to check
        Returns:
        true if no illegal char detected, false otherwise
      • trim

        public static java.lang.String trim​(java.lang.String s,
                                            int max)
        Trims a string. The method is nullpointer safe.
        Parameters:
        s - the string, may be null
        max - the maximum number of characters, 0 = minimum length
        Returns:
        the trimmed string, null if s == null
      • trim

        public static java.lang.String trim​(java.lang.String s)
        Trims a string. The method is nullpointer safe.
        Parameters:
        s - the string, may be null
        Returns:
        the trimmed string, null if s == null
        See Also:
        trim(java.lang.String, int)
      • trimRight

        public static java.lang.String trimRight​(java.lang.String str,
                                                 char filler)
        Cuts trailing characters.

        Removes all trailing characters of given value from the string. If the string consists of those characters only, the returned string will empty.

        Parameters:
        str - the string
        filler - the filler to remove
        Returns:
        the trimmed string, never null
      • trimLeft

        public static java.lang.String trimLeft​(java.lang.String str,
                                                char filler)
        Cuts leading characters.

        Removes all leading characters of given value from the string. If the string consists of those characters only, the returned string will be empty.

        Parameters:
        str - the string
        filler - the filler to remove
        Returns:
        the trimmed string, never null
      • fillLeft

        public static java.lang.String fillLeft​(java.lang.String str,
                                                int length,
                                                char filler)
        Fills up a string from the left with a filler character to match a given length.
        If the string is already longer, nothing happens.
        Parameters:
        str - the string
        length - the desired length
        filler - the filler character
        Returns:
        the filled string, never null
      • fillRight

        public static java.lang.String fillRight​(java.lang.String str,
                                                 int length,
                                                 char filler)
        Fills up a string to the right with a filler character to match a given length.
        If the string is already longer, nothing happens.
        Parameters:
        str - the string
        length - the desired length
        filler - the filler character
        Returns:
        the filled string, never null
      • firstBefore

        public static java.lang.String firstBefore​(java.lang.String str,
                                                   char delimiter)
        Gets the part of a string before a given delimiter.
        Parameters:
        str - the string
        delimiter - the delimiter
        Returns:
        the first part up to but excluding delimiter or the string if no delimiter at all
      • lastAfter

        public static java.lang.String lastAfter​(java.lang.String str,
                                                 char delimiter)
        Gets the part of a string after a given delimiter.
        Parameters:
        str - the string
        delimiter - the delimiter
        Returns:
        the last part following delimiter or the string if no delimiter at all
      • firstLine

        public static java.lang.String firstLine​(java.lang.String str)
        Gets the first line from a multi-line string. Nice in tables.
        Parameters:
        str - the multiline string
        Returns:
        the first line, null if str == null
      • toHexString

        public static java.lang.String toHexString​(byte[] binaryData)
        Creates a human-readable hex-String out of a byte-array (e.g. from MessageDigest MD5sum).
        Parameters:
        binaryData - the data, may be null
        Returns:
        the formatted hex string , null if data was null
      • toBytes

        public static byte[] toBytes​(char c)
        Converts a single (unicode) char to a byte-array.
        Parameters:
        c - the character
        Returns:
        the byte[2] array
      • toBytes

        public static byte[] toBytes​(char[] chars)
        Converts a char-array to a byte-array.
        Parameters:
        chars - the character array
        Returns:
        the byte array, empty if chars is null
      • hash

        public static java.lang.String hash​(java.lang.String algorithm,
                                            char[] salt,
                                            char[] input)
        Builds a hash from an array of chars.
        Note that this method converts the characters to bytes via toBytes(char[]) before applying the hash.
        Parameters:
        algorithm - the hashing algorithm (MD5, SHA-1, SHA-256 are supported by all java runtimes, at least)
        salt - the "salt", null if plain hash
        input - is the input array of chars
        Returns:
        the hash as a string, null if input == null
      • objectToLoggableString

        public static java.lang.String objectToLoggableString​(java.lang.Object object)
        Converts a value to a loggable string.
        Parameters:
        object - the object
        Returns:
        the string
      • countOccurrences

        public static int countOccurrences​(java.lang.String str,
                                           char c)
        Counts the number of occurrences of a given character in a string.
        Parameters:
        str - the string to test
        c - the character to check for
        Returns:
        the number of times c is part of str
      • objectArrayToString

        public static java.lang.String objectArrayToString​(java.lang.Object[] objArray,
                                                           java.lang.String separator)
        Creates a string from an object array.
        Parameters:
        objArray - the array of objects
        separator - the string between two objects
        Returns:
        the string
      • toCharArray

        public static char[] toCharArray​(java.lang.String str)
        Null-safe string to a char-array conversion.
        Parameters:
        str - the string, may be null
        Returns:
        the character array, null if str was null
        See Also:
        String.toCharArray()
      • fill

        public static void fill​(char[] buf,
                                char val)
        Null-safe char array filler.
        Parameters:
        buf - the char buffer, may be null
        val - the value to fill
        See Also:
        Arrays.fill(char[], char)
      • blank

        public static void blank​(char[] buf)
        Null-safe char array filler.
        Fills with blanks.
        Parameters:
        buf - the char buff, may be null
        See Also:
        fill(char[], char)
      • toHTML

        public static java.lang.String toHTML​(java.lang.String text)
        Converts a multiline string to an HTML-string that can be displayed in a label. Useful to print multiline labels.
        Parameters:
        text - the input string
        Returns:
        the HTML string
      • removeTrailingText

        public static java.lang.String removeTrailingText​(java.lang.String str,
                                                          java.lang.String trail)
        Removes a trailing text from a string.
        Parameters:
        str - the original string
        trail - the trailing string to remove, if found
        Returns:
        the shortened text
      • toAsciiLetterOrDigit

        public static java.lang.String toAsciiLetterOrDigit​(java.lang.String str)
        Converts to string containing only the letters A-z or digits.
        All other characters will be converted to an underscore. All diacrits will be converted first (see unDiacrit(java.lang.String, boolean). The resulting string will not contain more than one underscore in a row.

        Nice to create filenames.

        Parameters:
        str - the string
        Returns:
        the filename
      • getPlatform

        public static java.lang.String getPlatform()
        Gets the name of the operating system from the system properties.
        Returns:
        the normalized platform name
      • getArchitecture

        public static java.lang.String getArchitecture()
        Gets the name of the architecture from the system properties.
        Returns:
        the normalized architecture name