Class StringUtil

java.lang.Object
org.silverpeas.kernel.util.StringUtil

public class StringUtil extends Object
Utility class providing useful operations on Strings.
  • Field Details

  • Method Details

    • emptyString

      public static String emptyString()
      Gets an empty string as a constant (reusable empty string).
      Returns:
      an empty string.
    • startsWithIgnoreCase

      public static boolean startsWithIgnoreCase(String str, String prefix)

      Case insensitive check if a CharSequence starts with a specified prefix.

      nulls are handled without exceptions. Two null references are considered to be equal. The comparison is case insensitive.

       StringUtils.startsWithIgnoreCase(null, null)      = true
       StringUtils.startsWithIgnoreCase(null, "abc")     = false
       StringUtils.startsWithIgnoreCase("abcdef", null)  = false
       StringUtils.startsWithIgnoreCase("abcdef", "abc") = true
       StringUtils.startsWithIgnoreCase("ABCDEF", "abc") = true
       
      Parameters:
      str - the text to check, may be null
      prefix - the text to find, may be null
      Returns:
      true if the CharSequence starts with the prefix, case-insensitive, or both null
      See Also:
    • abbreviate

      public static String abbreviate(String str, int offset, int maxWidth)

      Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "...is the time for..."

      Works like abbreviate(String, int), but allows you to specify a "left edge" offset. Note that this left edge is not necessarily going to be the leftmost character in the result, or the first character following the ellipses, but it will appear somewhere in the result.

      In no case will it return a String of length greater than maxWidth.

       StringUtils.abbreviate(null, *, *)                = null
       StringUtils.abbreviate("", 0, 4)                  = ""
       StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..."
       StringUtils.abbreviate("abcdefghijklmno", 0, 10)  = "abcdefg..."
       StringUtils.abbreviate("abcdefghijklmno", 1, 10)  = "abcdefg..."
       StringUtils.abbreviate("abcdefghijklmno", 4, 10)  = "abcdefg..."
       StringUtils.abbreviate("abcdefghijklmno", 5, 10)  = "...fghi..."
       StringUtils.abbreviate("abcdefghijklmno", 6, 10)  = "...ghij..."
       StringUtils.abbreviate("abcdefghijklmno", 8, 10)  = "...ijklmno"
       StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno"
       StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno"
       StringUtils.abbreviate("abcdefghij", 0, 3)        = IllegalArgumentException
       StringUtils.abbreviate("abcdefghij", 5, 6)        = IllegalArgumentException
       
      Parameters:
      str - the String to check, may be null
      offset - left edge of source String
      maxWidth - maximum length of result String, must be at least 4
      Returns:
      abbreviated String, null if null String input
      Throws:
      IllegalArgumentException - if the width is too small
    • abbreviate

      public static String abbreviate(String str, int maxWidth)

      Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."

      Specifically:

      • If the number of characters in str is less than or equal to maxWidth, return str.
      • Else abbreviate it to (substring(str, 0, max-3) + "...").
      • If maxWidth is less than 4, throw an IllegalArgumentException.
      • In no case will it return a String of length greater than maxWidth.
       StringUtils.abbreviate(null, *)      = null
       StringUtils.abbreviate("", 4)        = ""
       StringUtils.abbreviate("abcdefg", 6) = "abc..."
       StringUtils.abbreviate("abcdefg", 7) = "abcdefg"
       StringUtils.abbreviate("abcdefg", 8) = "abcdefg"
       StringUtils.abbreviate("abcdefg", 4) = "a..."
       StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
       
      Parameters:
      str - the String to check, may be null
      maxWidth - maximum length of result String, must be at least 4
      Returns:
      abbreviated String, null if null String input
      Throws:
      IllegalArgumentException - if the width is too small
    • leftPad

      public static String leftPad(String str, int size, String padStr)

      Left pad a String with a specified String.

      Pad to a size of size.

       StringUtils.leftPad(null, *, *)      = null
       StringUtils.leftPad("", 3, "z")      = "zzz"
       StringUtils.leftPad("bat", 3, "yz")  = "bat"
       StringUtils.leftPad("bat", 5, "yz")  = "yzbat"
       StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat"
       StringUtils.leftPad("bat", 1, "yz")  = "bat"
       StringUtils.leftPad("bat", -1, "yz") = "bat"
       StringUtils.leftPad("bat", 5, null)  = "  bat"
       StringUtils.leftPad("bat", 5, "")    = "  bat"
       
      Parameters:
      str - the String to pad out, may be null
      size - the size to pad to
      padStr - the String to pad with, null or empty treated as single space
      Returns:
      left padded String or original String if no padding is necessary, null if null String input
    • defaultIfBlank

      public static <T extends CharSequence> T defaultIfBlank(T str, T defaultStr)

      Returns either the passed in CharSequence, or if the CharSequence is whitespace, empty ("") or null, the value of defaultStr.

      Whitespace is defined by Character.isWhitespace(char).

       StringUtils.defaultIfBlank(null, "NULL")  = "NULL"
       StringUtils.defaultIfBlank("", "NULL")    = "NULL"
       StringUtils.defaultIfBlank(" ", "NULL")   = "NULL"
       StringUtils.defaultIfBlank("bat", "NULL") = "bat"
       StringUtils.defaultIfBlank("", null)      = null
       
      Type Parameters:
      T - the specific kind of CharSequence
      Parameters:
      str - the CharSequence to check, may be null
      defaultStr - the default CharSequence to return if the input is whitespace, empty ("") or null, may be null
      Returns:
      the passed in CharSequence, or the default
      See Also:
      • StringUtils.defaultIfBlank(CharSequence, CharSequence)
    • isDefined

      public static boolean isDefined(String str)
      Is the specified string is well-defined?
      Parameters:
      str - a string to check.
      Returns:
      true if the given string isn't null, nor empty and doesn't contain any space characters. False otherwise. The "null" string is considered as a non-defined string.
    • isNotDefined

      public static boolean isNotDefined(String str)
      Is the specified string is not defined?
      Parameters:
      str - the string to check.
      Returns:
      true if the string is either null, an empty string, or a string containing only space characters. False otherwise. The "null" string is considered as a non-defined string.
      See Also:
      Implementation Note:
      it is the reverse of the isDefined(String) method.
    • requireDefined

      public static void requireDefined(String str)
      Requires the specified string to be defined, otherwise an AssertionError is thrown.
      Parameters:
      str - the string to check.
    • requireDefined

      public static void requireDefined(String str, String message)
      Requires the specified string to be defined, otherwise an AssertionError is thrown with the given message.
      Parameters:
      str - the string to check.
      message - the message to pass if the string doesn't satisfy the requirement.
    • requireDefined

      public static <T extends SilverpeasException> void requireDefined(String str, Supplier<T> exceptionSupplier) throws T
      Requires the specified string to be defined, otherwise throws the supplied exception.
      Parameters:
      str - the string to check.
      exceptionSupplier - a supplier of the Silverpeas exception to throw if the string isn't defined.
      Throws:
      T
    • startsWith

      public static boolean startsWith(CharSequence str, CharSequence prefix)

      Check if a CharSequence starts with a specified prefix.

      nulls are handled without exceptions. Two null references are considered to be equal. The comparison is case sensitive.

       StringUtils.startsWith(null, null)      = true
       StringUtils.startsWith(null, "abc")     = false
       StringUtils.startsWith("abcdef", null)  = false
       StringUtils.startsWith("abcdef", "abc") = true
       StringUtils.startsWith("ABCDEF", "abc") = false
       
      Parameters:
      str - the CharSequence to check, may be null
      prefix - the prefix to find, may be null
      Returns:
      true if the CharSequence starts with the prefix, case-sensitive, or both null
      See Also:
    • splitByWholeSeparator

      public static String[] splitByWholeSeparator(String str, String separator)

      Splits the provided text into an array, separator string specified.

      The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.

      A null input String returns null. A null separator splits on whitespace.

       StringUtils.splitByWholeSeparator(null, *)               = null
       StringUtils.splitByWholeSeparator("", *)                 = []
       StringUtils.splitByWholeSeparator("ab de fg", null)      = ["ab", "de", "fg"]
       StringUtils.splitByWholeSeparator("ab   de fg", null)    = ["ab", "de", "fg"]
       StringUtils.splitByWholeSeparator("ab:cd:ef", ":")       = ["ab", "cd", "ef"]
       StringUtils.splitByWholeSeparator("ab-!-cd-!-ef", "-!-") = ["ab", "cd", "ef"]
       
      Parameters:
      str - the String to parse, may be null
      separator - String containing the String to be used as a delimiter, null splits on whitespace
      Returns:
      an array of parsed Strings, null if null String was input
    • split

      public static String[] split(String str, char separatorChar)

      Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.

      The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

      A null input String returns null.

       StringUtils.split(null, *)         = null
       StringUtils.split("", *)           = []
       StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
       StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
       StringUtils.split("a:b:c", '.')    = ["a:b:c"]
       StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
       
      Parameters:
      str - the String to parse, may be null
      separatorChar - the character used as the delimiter
      Returns:
      an array of parsed Strings, null if null String input
      Since:
      2.0
    • split

      public static String[] split(String str, String separatorChars)

      Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.

      The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

      A null input String returns null. A null separatorChars splits on whitespace.

       StringUtils.split(null, *)         = null
       StringUtils.split("", *)           = []
       StringUtils.split("abc def", null) = ["abc", "def"]
       StringUtils.split("abc def", " ")  = ["abc", "def"]
       StringUtils.split("abc  def", " ") = ["abc", "def"]
       StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
       
      Parameters:
      str - the String to parse, may be null
      separatorChars - the characters used as the delimiters, null splits on whitespace
      Returns:
      an array of parsed Strings, null if null String input
    • capitalize

      public static String capitalize(String str)

      Capitalizes a String changing the first character to title case as per Character.toTitleCase(int). No other characters are changed.

      A null input String returns null.

       StringUtils.capitalize(null)  = null
       StringUtils.capitalize("")    = ""
       StringUtils.capitalize("cat") = "Cat"
       StringUtils.capitalize("cAt") = "CAt"
       StringUtils.capitalize("'cat'") = "'cat'"
       
      Parameters:
      str - the String to capitalize, may be null
      Returns:
      the capitalized String, null if null String input
      See Also:
    • uncapitalize

      public static String uncapitalize(String str)

      Uncapitalizes a String, changing the first character to lower case as per Character.toLowerCase(int). No other characters are changed.

      A null input String returns null.

       StringUtils.uncapitalize(null)  = null
       StringUtils.uncapitalize("")    = ""
       StringUtils.uncapitalize("cat") = "cat"
       StringUtils.uncapitalize("Cat") = "cat"
       StringUtils.uncapitalize("CAT") = "cAT"
       
      Parameters:
      str - the String to uncapitalize, may be null
      Returns:
      the uncapitalized String, null if null String input
      See Also:
    • normalize

      public static String normalize(String string)
      Normalizes the given string (which must be encoded into UTF-8) in order that the result contains only unified chars.

      Indeed, according to the environment of the user, sometimes it is sent data with combined characters which will make the server have a bad behavior, like throw an error on file download.

      Parameters:
      string - the string to normalize. There is no guarantee when the string is not encoded into UTF8.
      Returns:
      the normalized string.
    • normalizeByRemovingAccent

      public static String normalizeByRemovingAccent(String string)
      Same treatment as the one of normalize(String) but removes also the accented characters.
      Parameters:
      string - the string to normalize. There is no guarantee when the string is not encoded into UTF8.
      Returns:
      the normalized string.
    • defaultStringIfNotDefined

      public static String defaultStringIfNotDefined(String string)

      Returns either the passed in String, or if the String is not defined, an empty String ("").

       StringUtil.defaultStringIfNotDefined(null)   = ""
       StringUtil.defaultStringIfNotDefined("")     = ""
       StringUtil.defaultStringIfNotDefined("    ") = ""
       StringUtil.defaultStringIfNotDefined("bat")  = "bat"
       
      Parameters:
      string - the String to check, may be null, blank or filled by spaces if the input is not defined, may be null, blank or filled by spaces
      Returns:
      the passed in String, or the default if it was null
      See Also:
    • defaultStringIfNotDefined

      public static String defaultStringIfNotDefined(String string, String defaultString)

      Returns either the passed in String, or if the String is not defined, the value of defaultString.

       StringUtil.defaultStringIfNotDefined(null, "NULL")   = "NULL"
       StringUtil.defaultStringIfNotDefined("", "NULL")     = "NULL"
       StringUtil.defaultStringIfNotDefined("    ", "NULL") = "NULL"
       StringUtil.defaultStringIfNotDefined("bat", "NULL")  = "bat"
       
      Parameters:
      string - the String to check, may be null, blank or filled by spaces
      defaultString - the default String to return if the input is not defined, may be null, blank or filled by spaces
      Returns:
      the passed in String, or the default if it was null
      See Also:
    • definedString

      public static Optional<String> definedString(String string)
      This method allows the caller to handle the case where a string is not defined in a functional way.

      If the returned optional is present (so not empty), it means that the string given as parameter is defined (checked with isDefined(String)).

      If the returned optional is not present (so empty), it means that the string given as parameter is not defined. In a such cas, thanks to Optional, the caller can choose the behavior to adopt.

      Parameters:
      string - the String to check, may be null, blank or filled by spaces
      Returns:
      optional with given string if defined
    • isInteger

      public static boolean isInteger(String value)
      Is the specified value encodes an Integer?
      Parameters:
      value - the textual representation of an integer.
      Returns:
      true if the given value represents an integer. False otherwise.
    • asInt

      public static int asInt(String value, int defaultValue)
      Decodes the specified textual value as an integer.
      Parameters:
      value - the textual value to decode.
      defaultValue - the default value to use if the value doesn't encode an integer.
      Returns:
      either the integer representation of the value or the given default value if it isn't an integer representation.
    • isLong

      public static boolean isLong(String value)
      Is the specified value encodes a Long?
      Parameters:
      value - the textual representation of a long integer.
      Returns:
      true if the given value represents a long integer. False otherwise.
    • asFloat

      public static float asFloat(String value)
      Decodes the specified textual value as a float real.
      Parameters:
      value - the textual value to decode.
      Returns:
      either the float real representation of the value or 0 if it isn't a float real representation.
    • isFloat

      public static boolean isFloat(String value)
      Is the specified value encodes a Float?
      Parameters:
      value - the textual representation of a float real.
      Returns:
      true if the given value represents a float real. False otherwise.
    • escapeQuote

      public static String escapeQuote(String text)
      Parameters:
      text - the text from which the quotes must be escaped (replaced by spaces in fact).
      Returns:
      a String with all quotes replaced by spaces
    • toAcceptableFilename

      public static String toAcceptableFilename(String name)
      Replaces all quotes by spaces.
      Parameters:
      name - the original filename.
      Returns:
      a String with all quotes replaced by spaces
    • format

      public static String format(String label, Map<String,?> values)
      Format a string by extending the principle of the method format() of the class java.text.MessageFormat to string arguments. For instance, the string '{key}' contained in the original string to format will be replaced by the value corresponding to this key contained into the values map.
      Parameters:
      label - The string to format
      values - The values to insert into the string
      Returns:
      The formatted string, filled with values of the map.
    • truncate

      public static String truncate(String text, int maxLength)
      Parameters:
      text - The string to truncate if its size is greater than the maximum length given as parameter.
      maxLength - The maximum length required.
      Returns:
      The truncated string followed by '...' if needed. Returns the string itself if its length is smaller than the required maximum length.
    • regexReplace

      public static String regexReplace(String source, String regex, String replacement)
      Replace parts of a text by a replacement string. The text to replace is specified by a regex.
      Parameters:
      source - the original text
      regex - the regex that permits to identify parts of text to replace
      replacement - the replacement text
      Returns:
      The source text modified
    • isValidHour

      public static boolean isValidHour(String time)
      Is the specified text represents a time in the format expected by Silverpeas.
      Parameters:
      time - the textual representation of a time.
      Returns:
      true if the specified parameter represents a time formatted in the format expected by Silverpeas.
      See Also:
      • for the expected format of the time.
    • convertToEncoding

      public static String convertToEncoding(String toConvert, String encoding)
      Converts the given text into the specified charset. If the charset isn't supported, then an UnsupportedEncodingException exception is thrown.
      Parameters:
      toConvert - the text to convert.
      encoding - the charset into which the text has to be converted.
      Returns:
      the converted text.
    • getBooleanValue

      public static boolean getBooleanValue(String expression)
      Evaluate the expression and return true if expression equals "true", "yes", "y", "1" or "oui".
      Parameters:
      expression - the expression to be evaluated
      Returns:
      true if expression equals "true", "yes", "y", "1" or "oui".
    • areStringEquals

      public static boolean areStringEquals(String s1, String s2)
      Indicates if two Strings are equals, managing null.
      Parameters:
      s1 - the first String.
      s2 - the second String.
      Returns:
      true if the two Strings are equals.
    • asBase64

      public static String asBase64(byte[] binaryData)
      Encodes the specified binary data into a text of Base64 characters.
      Parameters:
      binaryData - the binary data to convert in Base64-based String.
      Returns:
      a String representation of the binary data in Base64 characters.
    • fromBase64

      public static byte[] fromBase64(String base64Text)
      Decodes the specified text with Base64 characters in binary.
      Parameters:
      base64Text - the text in Base64.
      Returns:
      the binary representation of the text.
    • splitString

      public static Iterable<String> splitString(String str, char separatorChar)

      Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.

      The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

      A null input String returns null.

       StringUtils.split(null, *)         = null
       StringUtils.split("", *)           = empty list
       StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
       StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
       StringUtils.split("a:b:c", '.')    = ["a:b:c"]
       StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
       
      Parameters:
      str - the String to parse, may be null
      separatorChar - the character used as the delimiter
      Returns:
      an array of parsed Strings, null if null String input
    • doubleAntiSlash

      public static String doubleAntiSlash(String path)
      Doubles the anti-slash character in a path value.
      Parameters:
      path - the String representing a path.
      Returns:
      the path corrected with the anti-slash doubled.
    • likeIgnoreCase

      public static boolean likeIgnoreCase(String actualValue, String expectedValue)
      Is the actual value is like the expected one? Case-sensitivity isn't taken into account in the like-matching.
      Parameters:
      actualValue - the actual value to compare.
      expectedValue - the expected value the actual one has to match.
      Returns:
      true if the actual value is like the expected one. False otherwise.
    • like

      public static boolean like(String actualValue, String expectedValue)
      Is the actual value is like the expected one? Case-sensitivity of the values matters.
      Parameters:
      actualValue - the actual value to compare.
      expectedValue - the expected value the actual one has to match.
      Returns:
      true if the actual value is like the expected one. False otherwise.