Class StringUtils

java.lang.Object
org.apache.hadoop.util.StringUtils

@Private @Unstable public class StringUtils extends Object
General string utils
  • Field Details

    • SHUTDOWN_HOOK_PRIORITY

      public static final int SHUTDOWN_HOOK_PRIORITY
      Priority of the StringUtils shutdown hook.
      See Also:
    • SHELL_ENV_VAR_PATTERN

      public static final Pattern SHELL_ENV_VAR_PATTERN
      Shell environment variables: $ followed by one letter or _ followed by multiple letters, numbers, or underscores. The group captures the environment variable name without the leading $.
    • WIN_ENV_VAR_PATTERN

      public static final Pattern WIN_ENV_VAR_PATTERN
      Windows environment variables: surrounded by %. The group captures the environment variable name without the leading and trailing %.
    • ENV_VAR_PATTERN

      public static final Pattern ENV_VAR_PATTERN
      Regular expression that matches and captures environment variable names according to platform-specific rules.
    • STRING_COLLECTION_SPLIT_EQUALS_INVALID_ARG

      @VisibleForTesting public static final String STRING_COLLECTION_SPLIT_EQUALS_INVALID_ARG
      getTrimmedStringCollectionSplitByEquals(String) throws IllegalArgumentException with error message starting with this string if the argument provided is not valid representation of non-empty key-value pairs. Value = "Trimmed string split by equals does not correctly represent non-empty key-value pairs."
      See Also:
    • emptyStringArray

      public static final String[] emptyStringArray
    • COMMA

      public static final char COMMA
      See Also:
    • COMMA_STR

      public static final String COMMA_STR
      See Also:
    • ESCAPE_CHAR

      public static final char ESCAPE_CHAR
      See Also:
  • Constructor Details

    • StringUtils

      public StringUtils()
  • Method Details

    • stringifyException

      public static String stringifyException(Throwable e)
      Make a string representation of the exception.
      Parameters:
      e - The exception to stringify
      Returns:
      A string with exception name and call stack.
    • simpleHostname

      public static String simpleHostname(String fullHostname)
      Given a full hostname, return the word upto the first dot.
      Parameters:
      fullHostname - the full hostname
      Returns:
      the hostname to the first dot
    • humanReadableInt

      @Deprecated public static String humanReadableInt(long number)
      Given an integer, return a string that is in an approximate, but human readable format.
      Parameters:
      number - the number to format
      Returns:
      a human readable form of the integer
    • format

      public static String format(String format, Object... objects)
      The same as String.format(Locale.ENGLISH, format, objects).
      Parameters:
      format - format.
      objects - objects.
      Returns:
      format string.
    • formatPercent

      public static String formatPercent(double fraction, int decimalPlaces)
      Format a percentage for presentation to the user.
      Parameters:
      fraction - the percentage as a fraction, e.g. 0.1 = 10%
      decimalPlaces - the number of decimal places
      Returns:
      a string representation of the percentage
    • arrayToString

      public static String arrayToString(String[] strs)
      Given an array of strings, return a comma-separated list of its elements.
      Parameters:
      strs - Array of strings
      Returns:
      Empty string if strs.length is 0, comma separated list of strings otherwise
    • byteToHexString

      public static String byteToHexString(byte[] bytes, int start, int end)
      Given an array of bytes it will convert the bytes to a hex string representation of the bytes
      Parameters:
      bytes - bytes.
      start - start index, inclusively
      end - end index, exclusively
      Returns:
      hex string representation of the byte array
    • byteToHexString

      public static String byteToHexString(byte[] bytes)
      Same as byteToHexString(bytes, 0, bytes.length).
      Parameters:
      bytes - bytes.
      Returns:
      byteToHexString.
    • byteToHexString

      public static String byteToHexString(byte b)
      Convert a byte to a hex string.
      Parameters:
      b - byte
      Returns:
      byte's hex value as a String
      See Also:
    • hexStringToByte

      public static byte[] hexStringToByte(String hex)
      Given a hexstring this will return the byte array corresponding to the string
      Parameters:
      hex - the hex String array
      Returns:
      a byte array that is a hex string representation of the given string. The size of the byte array is therefore hex.length/2
    • uriToString

      public static String uriToString(URI[] uris)
      uriToString.
      Parameters:
      uris - uris.
      Returns:
      uriToString.
    • stringToURI

      public static URI[] stringToURI(String[] str)
      Parameters:
      str - The string array to be parsed into an URI array.
      Returns:
      null if str is null, else the URI array equivalent to str.
      Throws:
      IllegalArgumentException - If any string in str violates RFC 2396.
    • stringToPath

      public static Path[] stringToPath(String[] str)
      stringToPath.
      Parameters:
      str - str.
      Returns:
      path array.
    • formatTimeDiff

      public static String formatTimeDiff(long finishTime, long startTime)
      Given a finish and start time in long milliseconds, returns a String in the format Xhrs, Ymins, Z sec, for the time difference between two times. If finish time comes before start time then negative valeus of X, Y and Z wil return.
      Parameters:
      finishTime - finish time
      startTime - start time
      Returns:
      a String in the format Xhrs, Ymins, Z sec, for the time difference between two times.
    • formatTime

      public static String formatTime(long timeDiff)
      Given the time in long milliseconds, returns a String in the format Xhrs, Ymins, Z sec.
      Parameters:
      timeDiff - The time difference to format
      Returns:
      formatTime String.
    • formatTimeSortable

      public static String formatTimeSortable(long timeDiff)
      Given the time in long milliseconds, returns a String in the sortable format Xhrs, Ymins, Zsec. X, Y, and Z are always two-digit. If the time is more than 100 hours ,it is displayed as 99hrs, 59mins, 59sec.
      Parameters:
      timeDiff - The time difference to format
      Returns:
      format time sortable.
    • getFormattedTimeWithDiff

      public static String getFormattedTimeWithDiff(org.apache.commons.lang3.time.FastDateFormat dateFormat, long finishTime, long startTime)
      Formats time in ms and appends difference (finishTime - startTime) as returned by formatTimeDiff(). If finish time is 0, empty string is returned, if start time is 0 then difference is not appended to return value.
      Parameters:
      dateFormat - date format to use
      finishTime - finish time
      startTime - start time
      Returns:
      formatted value.
    • getFormattedTimeWithDiff

      public static String getFormattedTimeWithDiff(String formattedFinishTime, long finishTime, long startTime)
      Formats time in ms and appends difference (finishTime - startTime) as returned by formatTimeDiff(). If finish time is 0, empty string is returned, if start time is 0 then difference is not appended to return value.
      Parameters:
      formattedFinishTime - formattedFinishTime to use
      finishTime - finish time
      startTime - start time
      Returns:
      formatted value.
    • getStrings

      public static String[] getStrings(String str)
      Returns an arraylist of strings.
      Parameters:
      str - the comma separated string values
      Returns:
      the arraylist of the comma separated string values
    • getStrings

      public static String[] getStrings(String str, String delim)
      Returns an arraylist of strings.
      Parameters:
      str - the string values
      delim - delimiter to separate the values
      Returns:
      the arraylist of the separated string values
    • getStringCollection

      public static Collection<String> getStringCollection(String str)
      Returns a collection of strings.
      Parameters:
      str - comma separated string values
      Returns:
      an ArrayList of string values
    • getStringCollection

      public static Collection<String> getStringCollection(String str, String delim)
      Returns a collection of strings.
      Parameters:
      str - String to parse
      delim - delimiter to separate the values
      Returns:
      Collection of parsed elements.
    • getTrimmedStringCollection

      public static Collection<String> getTrimmedStringCollection(String str, String delim)
      Returns a collection of strings, trimming leading and trailing whitespace on each value. Duplicates are not removed.
      Parameters:
      str - String separated by delim.
      delim - Delimiter to separate the values in str.
      Returns:
      Collection of string values.
    • getTrimmedStringCollection

      public static Collection<String> getTrimmedStringCollection(String str)
      Splits a comma separated value String, trimming leading and trailing whitespace on each value. Duplicate and empty values are removed.
      Parameters:
      str - a comma separated String with values, may be null
      Returns:
      a Collection of String values, empty Collection if null String input
    • getTrimmedStringCollectionSplitByEquals

      public static Map<String,String> getTrimmedStringCollectionSplitByEquals(String str)
      Splits an "=" separated value String, trimming leading and trailing whitespace on each value after splitting by comma and new line separator.
      Parameters:
      str - a comma separated String with values, may be null
      Returns:
      a Map of String keys and values, empty Collection if null String input.
    • getTrimmedStrings

      public static String[] getTrimmedStrings(String str)
      Splits a comma or newline separated value String, trimming leading and trailing whitespace on each value.
      Parameters:
      str - a comma or newline separated String with values, may be null
      Returns:
      an array of String values, empty array if null String input
    • getTrimmedStringsSplitByEquals

      public static String[] getTrimmedStringsSplitByEquals(String str)
      Splits "=" separated value String, trimming leading and trailing whitespace on each value.
      Parameters:
      str - an "=" separated String with values, may be null
      Returns:
      an array of String values, empty array if null String input
    • split

      public static String[] split(String str)
      Split a string using the default separator
      Parameters:
      str - a string that may have escaped separator
      Returns:
      an array of strings
    • split

      public static String[] split(String str, char escapeChar, char separator)
      Split a string using the given separator
      Parameters:
      str - a string that may have escaped separator
      escapeChar - a char that be used to escape the separator
      separator - a separator char
      Returns:
      an array of strings
    • split

      public static String[] split(String str, char separator)
      Split a string using the given separator, with no escaping performed.
      Parameters:
      str - a string to be split. Note that this may not be null.
      separator - a separator char
      Returns:
      an array of strings
    • findNext

      public static int findNext(String str, char separator, char escapeChar, int start, StringBuilder split)
      Finds the first occurrence of the separator character ignoring the escaped separators starting from the index. Note the substring between the index and the position of the separator is passed.
      Parameters:
      str - the source string
      separator - the character to find
      escapeChar - character used to escape
      start - from where to search
      split - used to pass back the extracted string
      Returns:
      index.
    • escapeString

      public static String escapeString(String str)
      Escape commas in the string using the default escape char
      Parameters:
      str - a string
      Returns:
      an escaped string
    • escapeString

      public static String escapeString(String str, char escapeChar, char charToEscape)
      Escape charToEscape in the string with the escape char escapeChar
      Parameters:
      str - string
      escapeChar - escape char
      charToEscape - the char to be escaped
      Returns:
      an escaped string
    • escapeString

      public static String escapeString(String str, char escapeChar, char[] charsToEscape)
      escapeString.
      Parameters:
      str - str.
      escapeChar - escapeChar.
      charsToEscape - array of characters to be escaped
      Returns:
      escapeString.
    • unEscapeString

      public static String unEscapeString(String str)
      Unescape commas in the string using the default escape char
      Parameters:
      str - a string
      Returns:
      an unescaped string
    • unEscapeString

      public static String unEscapeString(String str, char escapeChar, char charToEscape)
      Unescape charToEscape in the string with the escape char escapeChar
      Parameters:
      str - string
      escapeChar - escape char
      charToEscape - the escaped char
      Returns:
      an unescaped string
    • unEscapeString

      public static String unEscapeString(String str, char escapeChar, char[] charsToEscape)
      unEscapeString.
      Parameters:
      str - str.
      escapeChar - escapeChar.
      charsToEscape - array of characters to unescape
      Returns:
      escape string.
    • toStartupShutdownString

      public static String toStartupShutdownString(String prefix, String[] msg)
      Return a message for logging.
      Parameters:
      prefix - prefix keyword for the message
      msg - content of the message
      Returns:
      a message for logging
    • startupShutdownMessage

      public static void startupShutdownMessage(Class<?> clazz, String[] args, org.slf4j.Logger log)
      Print a log message for starting up and shutting down
      Parameters:
      clazz - the class of the server
      args - arguments
      log - the target log object
    • createStartupShutdownMessage

      public static String createStartupShutdownMessage(String classname, String hostname, String[] args)
      Generate the text for the startup/shutdown message of processes.
      Parameters:
      classname - short classname of the class
      hostname - hostname
      args - Command arguments
      Returns:
      a string to log.
    • escapeHTML

      public static String escapeHTML(String string)
      Escapes HTML Special characters present in the string.
      Parameters:
      string - param string.
      Returns:
      HTML Escaped String representation
    • byteDesc

      public static String byteDesc(long len)
      a byte description of the given long interger value.
      Parameters:
      len - len.
      Returns:
      a byte description of the given long interger value.
    • limitDecimalTo2

      @Deprecated public static String limitDecimalTo2(double d)
      Deprecated.
      use StringUtils.format("%.2f", d).
      limitDecimalTo2.
      Parameters:
      d - double param.
      Returns:
      string value ("%.2f").
    • join

      public static String join(CharSequence separator, Iterable<?> strings)
      Concatenates strings, using a separator.
      Parameters:
      separator - Separator to join with.
      strings - Strings to join.
      Returns:
      join string.
    • join

      public static String join(char separator, Iterable<?> strings)
    • join

      public static String join(CharSequence separator, String[] strings)
      Concatenates strings, using a separator.
      Parameters:
      separator - to join with
      strings - to join
      Returns:
      the joined string
    • join

      public static String join(char separator, String[] strings)
    • camelize

      public static String camelize(String s)
      Convert SOME_STUFF to SomeStuff
      Parameters:
      s - input string
      Returns:
      camelized string
    • replaceTokens

      public static String replaceTokens(String template, Pattern pattern, Map<String,String> replacements)
      Matches a template string against a pattern, replaces matched tokens with the supplied replacements, and returns the result. The regular expression must use a capturing group. The value of the first capturing group is used to look up the replacement. If no replacement is found for the token, then it is replaced with the empty string. For example, assume template is "%foo%_%bar%_%baz%", pattern is "%(.*?)%", and replacements contains 2 entries, mapping "foo" to "zoo" and "baz" to "zaz". The result returned would be "zoo__zaz".
      Parameters:
      template - String template to receive replacements
      pattern - Pattern to match for identifying tokens, must use a capturing group
      replacements - Map<String, String> mapping tokens identified by the capturing group to their replacement values
      Returns:
      String template with replacements
    • getStackTrace

      public static String getStackTrace(Thread t)
      Get stack trace for a given thread.
      Parameters:
      t - thread.
      Returns:
      stack trace string.
    • getStackTrace

      public static String getStackTrace(Throwable t)
      Get stack trace from throwable exception.
      Parameters:
      t - Throwable.
      Returns:
      stack trace string.
    • popOptionWithArgument

      public static String popOptionWithArgument(String name, List<String> args) throws IllegalArgumentException
      From a list of command-line arguments, remove both an option and the next argument.
      Parameters:
      name - Name of the option to remove. Example: -foo.
      args - List of arguments.
      Returns:
      null if the option was not found; the value of the option otherwise.
      Throws:
      IllegalArgumentException - if the option's argument is not present
    • popOption

      public static boolean popOption(String name, List<String> args)
      From a list of command-line arguments, remove an option.
      Parameters:
      name - Name of the option to remove. Example: -foo.
      args - List of arguments.
      Returns:
      true if the option was found and removed; false otherwise.
    • popFirstNonOption

      public static String popFirstNonOption(List<String> args)
      From a list of command-line arguments, return the first non-option argument. Non-option arguments are those which either come after a double dash (--) or do not start with a dash.
      Parameters:
      args - List of arguments.
      Returns:
      The first non-option argument, or null if there were none.
    • toLowerCase

      public static String toLowerCase(String str)
      Converts all of the characters in this String to lower case with Locale.ENGLISH.
      Parameters:
      str - string to be converted
      Returns:
      the str, converted to lowercase.
    • toUpperCase

      public static String toUpperCase(String str)
      Converts all of the characters in this String to upper case with Locale.ENGLISH.
      Parameters:
      str - string to be converted
      Returns:
      the str, converted to uppercase.
    • equalsIgnoreCase

      public static boolean equalsIgnoreCase(String s1, String s2)
      Compare strings locale-freely by using String#equalsIgnoreCase.
      Parameters:
      s1 - Non-null string to be converted
      s2 - string to be converted
      Returns:
      the str, converted to uppercase.
    • isAlpha

      public static boolean isAlpha(String str)

      Checks if the String contains only unicode letters.

      null will return false. An empty String (length()=0) will return true.

       StringUtils.isAlpha(null)   = false
       StringUtils.isAlpha("")     = true
       StringUtils.isAlpha("  ")   = false
       StringUtils.isAlpha("abc")  = true
       StringUtils.isAlpha("ab2c") = false
       StringUtils.isAlpha("ab-c") = false
       
      Parameters:
      str - the String to check, may be null
      Returns:
      true if only contains letters, and is non-null
    • wrap

      public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords)
      Same as WordUtils#wrap in commons-lang 2.6. Unlike commons-lang3, leading spaces on the first line are NOT stripped.
      Parameters:
      str - the String to be word wrapped, may be null
      wrapLength - the column to wrap the words at, less than 1 is treated as 1
      newLineStr - the string to insert for a new line, null uses the system property line separator
      wrapLongWords - true if long words (such as URLs) should be wrapped
      Returns:
      a line with newlines inserted, null if null input
    • hasLength

      public static boolean hasLength(String str)
      Checks whether the given string is not null and has a length greater than zero.
      Parameters:
      str - the string to check
      Returns:
      true if the string is not null and not empty; false otherwise