Class StringHelper

java.lang.Object
org.tentackle.common.StringHelper

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

    • stringNormalizer

      public static Function<String,String> stringNormalizer
      The default normalizer used within the application. Defaults to DefaultStringNormalizer.
  • Method Details

    • 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(String a, String b)
      Parameters:
      a - first string, may be null
      b - second string, may be null
      Returns:
      true if equal ignoring the case or both are null
    • compare

      public static int compare(String a, String b)
      Parameters:
      a - first string, may be null
      b - second string, may be null
      Returns:
      the comparison result
    • compareIgnoreCase

      public static int compareIgnoreCase(String a, String b)
      Parameters:
      a - first string, may be null
      b - second string, may be null
      Returns:
      the comparison result
    • toUpper

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

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

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

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

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

      public static String getContinuedLine(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(String str, String anyOf)
      Returns the first index 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 String toDoubleQuotes(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
    • charToEscaped

      public static char charToEscaped(char c)
      Converts a character that followed a backslash to an escaped character.
      The special escapes are:

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

      Parameters:
      c - the character following a backslash in a string
      Returns:
      the converted escape character
    • escapedToString

      public static String escapedToString(char c)
      Converts an escape character to a parsable string.
      The special escapes are:

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

      Parameters:
      c - the escape character
      Returns:
      the parsable string
    • parseString

      public static String parseString(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 String toParsableString(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 List<String> split(String str, 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(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(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(String packageName)
      Checks that given string is a valid Java package name.
      This is very restrictive verification. Package names must be all lowercase alphabetic or digits and must contain only dots and underscores.
      Parameters:
      packageName - the package name
      Returns:
      true if valid
    • isValidJavaIdentifier

      public static boolean isValidJavaIdentifier(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 String readTextFromResource(Class<?> caller, String resourceName) throws 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:
      IOException - if loading failed
      FileNotFoundException - if no such resource found
    • isAllWhitespace

      public static boolean isAllWhitespace(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(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 String digitToString(Character digit)
      Gets the word-string for a digit.
      Example:
       '0' --> "zero"
       
      Parameters:
      digit - the digit character
      Returns:
      the word-string
    • unDiacrit

      public static String unDiacrit(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 String normalize(String str, Function<String,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 String normalize(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 String stripEnclosingDoubleQuotes(String str)
      Strips enclosing double quotes.
      Parameters:
      str - the original string
      Returns:
      the string with its double quotes removed
    • toFixedLength

      public static String toFixedLength(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 String toFixedLength(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 String toFixedLengthLeftFill(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 String toFixedLengthLeftFill(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
    • toVarName

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

      public static String toCamelCase(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
    • camelCaseToDelimited

      public static String camelCaseToDelimited(String str, String delimiter)
      Converts a camelCase string to a string with delimiters.

      Example:
      "alphaBetaGamma" is converted to "alpha.beta.gamma", with delimiter ".".

      Parameters:
      str - the camelcase string
      delimiter - the delimiter to insert between parts, null or empty if none
      Returns:
      the converted string
    • isAllDigits

      public static boolean isAllDigits(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(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 String trim(String s, int max)
      Trims a string.
      The method is null-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 String trim(String s)
      Trims a string.
      The method is null-safe.
      Parameters:
      s - the string, may be null
      Returns:
      the trimmed string, null if s == null
      See Also:
    • trimRight

      public static String trimRight(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 String trimLeft(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 String fillLeft(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 String fillRight(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 String firstBefore(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 String lastAfter(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 String firstLine(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 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 String hash(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 String objectToLoggableString(Object object)
      Converts a value to a loggable string.
      Parameters:
      object - the object
      Returns:
      the string
    • countOccurrences

      public static int countOccurrences(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 String objectArrayToString(Object[] objArray, 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(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:
    • 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:
    • 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:
    • toHTML

      public static String toHTML(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 String removeTrailingText(String str, String... trail)
      Removes a trailing text from a string.
      Stops when the first trailing string is found.
      Parameters:
      str - the original string
      trail - the trailing string(s) to remove
      Returns:
      the shortened text, str if nothing removed
    • toAsciiLetterOrDigit

      public static String toAsciiLetterOrDigit(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 String getPlatform()
      Gets the name of the operating system from the system properties.
      Returns:
      the normalized platform name
    • getArchitecture

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

      public static String filterUpperCase(String str)
      Gets the uppercase letters only.
      Useful to get the camel case letters of a string.
      Parameters:
      str - the string
      Returns:
      the upper case letters
    • evaluate

      public static String evaluate(String str, Function<String,String> variableProvider)
      Evaluates a string replacing variables.
      The semantics are very much the same as known from the maven resources plugin, but with the extension of optional default values and that @ turns off nested variable processing.

      Syntax: $|@{name[?|!default]}, where name is the variable name and default is the default value to be used if there is no such variable (!) or variable is empty (@{link isAllWhitespace(String)}) or doesn't exist (?).

      Characters can be quoted with a backslash. A double backslash is treated as a single backslash.

      Examples:

          @{user.home}/somedir
          @{user.home?/tmp}/somedir
          @{user.home!/tmp}/somedir
       
      Notice that ${...} may lead to unexpected results, if the variable's value contains backslashes, as with windows path names, for example.
      Parameters:
      str - the string
      variableProvider - the variables as properties
      Returns:
      the processed string
    • levenshteinDistance

      public static int levenshteinDistance(String s1, String s2)
      Determines the Levenshtein distance of two strings.
      Notice that for s1 and s2 null values are treated as empty strings.
      Parameters:
      s1 - the first string
      s2 - the second string
      Returns:
      the distance
    • startsWithAnyOf

      public static String startsWithAnyOf(String str, int offset, String... prefixes)
      Same as String.startsWith(String, int), but for more multiple prefixes.
      Parameters:
      str - the string to check
      offset - where to begin looking in str
      prefixes - the prefixes
      Returns:
      the prefix, null if no match
    • startsWithAnyOf

      public static String startsWithAnyOf(String str, String... prefixes)
      Same as String.startsWith(String), but for more multiple prefixes.
      Parameters:
      str - the string to check
      prefixes - the prefixes
      Returns:
      the prefix, null if no match
    • endsWithAnyOf

      public static String endsWithAnyOf(String str, String... suffixes)
      Same as String.endsWith(String), but for more multiple suffixes.
      Parameters:
      str - the string to check
      suffixes - the suffixes
      Returns:
      the suffix, null if no match