Class StringUtils

java.lang.Object
org.apache.juneau.common.utils.StringUtils

public class StringUtils extends Object
Reusable string utility methods.
  • Field Details

  • Constructor Details

  • Method Details

    • abbreviate

      public static String abbreviate(String in, int length)
      Abbreviates a String using ellipses.
      Parameters:
      in - The input string.
      length - The max length of the resulting string.
      Returns:
      The abbreviated string.
    • base64Decode

      public static byte[] base64Decode(String in)
      BASE64-decodes the specified string.
      Parameters:
      in - The BASE-64 encoded string.
      Returns:
      The decoded byte array, or null if the input was null.
    • base64DecodeToString

      public static String base64DecodeToString(String in)
      Shortcut for calling base64Decode(String) and converting the result to a UTF-8 encoded string.
      Parameters:
      in - The BASE-64 encoded string to decode.
      Returns:
      The decoded string.
    • base64Encode

      public static String base64Encode(byte[] in)
      BASE64-encodes the specified byte array.
      Parameters:
      in - The input byte array to convert.
      Returns:
      The byte array converted to a BASE-64 encoded string.
    • base64EncodeToString

      public static String base64EncodeToString(String in)
      Shortcut for calling base64Encode(in.getBytes("UTF-8"))
      Parameters:
      in - The input string to convert.
      Returns:
      The string converted to BASE-64 encoding.
    • charAt

      public static char charAt(String s, int i)
      Returns the character at the specified index in the string without throwing exceptions.
      Parameters:
      s - The string.
      i - The index position.
      Returns:
      The character at the specified index, or 0 if the index is out-of-range or the string is null.
    • compare

      public static int compare(String s1, String s2)
      Compares two strings, but gracefully handles nulls.
      Parameters:
      s1 - The first string.
      s2 - The second string.
      Returns:
      The same as String.compareTo(String).
    • compress

      public static byte[] compress(String contents) throws Exception
      Converts string into a GZipped input stream.
      Parameters:
      contents - The contents to compress.
      Returns:
      The input stream converted to GZip.
      Throws:
      Exception - Exception occurred.
    • contains

      public static boolean contains(String value, CharSequence substring)
      Same as String.contains(CharSequence) except returns null if the value is null.
      Parameters:
      value - The string to check.
      substring - The value to check for.
      Returns:
      true if the value contains the specified substring.
    • containsAny

      public static boolean containsAny(String s, char... chars)
      Returns true if the specified string contains any of the specified characters.
      Parameters:
      s - The string to test.
      chars - The characters to look for.
      Returns:
      true if the specified string contains any of the specified characters.
      false if the string is null.
    • countChars

      public static int countChars(String s, char c)
      Counts the number of the specified character in the specified string.
      Parameters:
      s - The string to check.
      c - The character to check for.
      Returns:
      The number of those characters or zero if the string was null.
    • decodeHex

      public static String decodeHex(String s)
      Debug method for rendering non-ASCII character sequences.
      Parameters:
      s - The string to decode.
      Returns:
      A string with non-ASCII characters converted to "[hex]" sequences.
    • decompress

      public static String decompress(byte[] is) throws Exception
      Converts a GZipped input stream into a string.
      Parameters:
      is - The contents to decompress.
      Returns:
      The string.
      Throws:
      Exception - Exception occurred.
    • diffPosition

      public static int diffPosition(String s1, String s2)
      Finds the position where the two strings differ.
      Parameters:
      s1 - The first string.
      s2 - The second string.
      Returns:
      The position where the two strings differ, or -1 if they're equal.
    • diffPositionIc

      public static int diffPositionIc(String s1, String s2)
      Finds the position where the two strings differ ignoring case.
      Parameters:
      s1 - The first string.
      s2 - The second string.
      Returns:
      The position where the two strings differ, or -1 if they're equal.
    • endsWith

      public static boolean endsWith(String s, char c)
      An efficient method for checking if a string ends with a character.
      Parameters:
      s - The string to check. Can be null.
      c - The character to check for.
      Returns:
      true if the specified string is not null and ends with the specified character.
    • endsWith

      public static boolean endsWith(String s, char... c)
      Same as endsWith(String, char) except check for multiple characters.
      Parameters:
      s - The string to check. Can be null.
      c - The characters to check for.
      Returns:
      true if the specified string is not null and ends with the specified character.
    • escapeChars

      public static String escapeChars(String s, AsciiSet escaped)
      Escapes the specified characters in the string.
      Parameters:
      s - The string with characters to escape.
      escaped - The characters to escape.
      Returns:
      The string with characters escaped, or the same string if no escapable characters were found.
    • firstChar

      public static char firstChar(String s)
      Returns the first character in the specified string.
      Parameters:
      s - The string to check.
      Returns:
      The first character in the string, or 0 if the string is null or empty.
    • firstNonEmpty

      public static String firstNonEmpty(String... s)
      Returns the first non-null, non-empty string in the list.
      Parameters:
      s - The strings to test.
      Returns:
      The first non-empty string in the list, or null if they were all null or empty.
    • firstNonWhitespaceChar

      public static char firstNonWhitespaceChar(String s)
      Returns the first non-whitespace character in the string.
      Parameters:
      s - The string to check.
      Returns:
      The first non-whitespace character, or 0 if the string is null, empty, or composed of only whitespace.
    • fixUrl

      public static String fixUrl(String in)
      Attempts to escape any invalid characters found in a URI.
      Parameters:
      in - The URI to fix.
      Returns:
      The fixed URI.
    • format

      public static String format(String pattern, Object... args)
      Similar to MessageFormat.format(String, Object...) except allows you to specify POJO arguments.
      Parameters:
      pattern - The string pattern.
      args - The arguments.
      Returns:
      The formatted string.
    • fromHex

      public static byte[] fromHex(String hex)
      Converts a hexadecimal character string to a byte array.
      Parameters:
      hex - The string to convert to a byte array.
      Returns:
      A new byte array.
    • fromHexToUTF8

      public static String fromHexToUTF8(String hex)
      Converts a hexadecimal byte stream (e.g. "34A5BC") into a UTF-8 encoded string.
      Parameters:
      hex - The hexadecimal string.
      Returns:
      The UTF-8 string.
    • fromSpacedHex

      public static byte[] fromSpacedHex(String hex)
      Same as fromHex(String) except expects spaces between the byte strings.
      Parameters:
      hex - The string to convert to a byte array.
      Returns:
      A new byte array.
    • fromSpacedHexToUTF8

      public static String fromSpacedHexToUTF8(String hex)
      Converts a space-deliminted hexadecimal byte stream (e.g. "34 A5 BC") into a UTF-8 encoded string.
      Parameters:
      hex - The hexadecimal string.
      Returns:
      The UTF-8 string.
    • getAuthorityUri

      public static String getAuthorityUri(String s)
      Given an absolute URI, returns just the authority portion (e.g. "http://hostname:port")
      Parameters:
      s - The URI string.
      Returns:
      Just the authority portion of the URI.
    • getDuration

      public static long getDuration(String s)
      Parses a duration string.

      Examples:

      • "1000" - 1000 milliseconds.
      • "10s" - 10 seconds.
      • "10 sec" - 10 seconds.
      • "10 seconds" - 10 seconds.

      Use any of the following suffixes:

      • None (time in milliseconds).
      • "s"/"sec"/"second"/"seconds"
      • "m"/"min"/"minutes"/"seconds"
      • "h"/"hour"/"hours"
      • "d"/"day"/"days"
      • "w"/"week"/"weeks"

      Suffixes are case-insensitive.
      Whitespace is ignored.

      Parameters:
      s - The string to parse.
      Returns:
      The time in milliseconds, or -1 if the string is empty or null.
    • getNumberedLines

      public static String getNumberedLines(String s)
      Takes in a string, splits it by lines, and then prepends each line with line numbers.
      Parameters:
      s - The string.
      Returns:
      The string with line numbers added.
    • getNumberedLines

      public static String getNumberedLines(String s, int start, int end)
      Same as getNumberedLines(String) except only returns the specified lines.

      Out-of-bounds values are allowed and fixed.

      Parameters:
      s - The string.
      start - The starting line (1-indexed).
      end - The ending line (1-indexed).
      Returns:
      The string with line numbers added.
    • indexOf

      public static int indexOf(String s, char... c)
      Same as String.indexOf(int) except allows you to check for multiple characters.
      Parameters:
      s - The string to check.
      c - The characters to check for.
      Returns:
      The index into the string that is one of the specified characters.
    • isAbsoluteUri

      public static boolean isAbsoluteUri(String s)
      Efficiently determines whether a URL is of the pattern "xxx://xxx"
      Parameters:
      s - The string to test.
      Returns:
      true if it's an absolute path.
    • isDecimal

      public static boolean isDecimal(String s)
      Returns true if the specified string is numeric.
      Parameters:
      s - The string to check.
      Returns:
      true if the specified string is numeric.
    • isFirstNumberChar

      public static boolean isFirstNumberChar(char c)
      Returns true if the specified character is a valid first character for a number.
      Parameters:
      c - The character to test.
      Returns:
      true if the specified character is a valid first character for a number.
    • isFloat

      public static boolean isFloat(String s)
      Returns true if the specified string is a floating point number.
      Parameters:
      s - The string to check.
      Returns:
      true if the specified string is a floating point number.
    • isJson

      public static boolean isJson(String s)
      Returns true if the specified string is valid JSON.

      Leading and trailing spaces are ignored.
      Leading and trailing comments are not allowed.

      Parameters:
      s - The string to test.
      Returns:
      true if the specified string is valid JSON.
    • isJsonArray

      public static boolean isJsonArray(Object o, boolean ignoreWhitespaceAndComments)
      Returns true if the specified string appears to be an JSON array.
      Parameters:
      o - The object to test.
      ignoreWhitespaceAndComments - If true, leading and trailing whitespace and comments will be ignored.
      Returns:
      true if the specified string appears to be a JSON array.
    • isJsonObject

      public static boolean isJsonObject(Object o, boolean ignoreWhitespaceAndComments)
      Returns true if the specified string appears to be a JSON object.
      Parameters:
      o - The object to test.
      ignoreWhitespaceAndComments - If true, leading and trailing whitespace and comments will be ignored.
      Returns:
      true if the specified string appears to be a JSON object.
    • isNumberChar

      public static boolean isNumberChar(char c)
      Returns true if the specified character is a valid number character.
      Parameters:
      c - The character to check.
      Returns:
      true if the specified character is a valid number character.
    • isNumeric

      public static boolean isNumeric(String s)
      Returns true if this string can be parsed by parseNumber(String, Class).
      Parameters:
      s - The string to check.
      Returns:
      true if this string can be parsed without causing an exception.
    • isOneOf

      public static boolean isOneOf(String s, String... values)
      Returns true if the specified string is one of the specified values.
      Parameters:
      s - The string to test. Can be null.
      values - The values to test. Can contain null.
      Returns:
      true if the specified string is one of the specified values.
    • isUri

      public static boolean isUri(String s)
      Efficiently determines whether a URL is of the pattern "xxx:/xxx".

      The pattern matched is: [a-z]{2,}\:\/.*

      Note that this excludes filesystem paths such as "C:/temp".

      Parameters:
      s - The string to test.
      Returns:
      true if it's an absolute path.
    • joine

      public static String joine(List<?> tokens, char d)
      Same as Utils.join(Collection, char) but escapes the delimiter if found in the tokens.
      Parameters:
      tokens - The tokens to join.
      d - The delimiter.
      Returns:
      The delimited string. If tokens is null, returns null.
    • lastNonWhitespaceChar

      public static char lastNonWhitespaceChar(String s)
      Returns the last non-whitespace character in the string.
      Parameters:
      s - The string to check.
      Returns:
      The last non-whitespace character, or 0 if the string is null, empty, or composed of only whitespace.
    • parseCharacter

      public static Character parseCharacter(Object o)
      Converts a String to a Character
      Parameters:
      o - The string to convert.
      Returns:
      The first character of the string if the string is of length 1, or null if the string is null or empty.
      Throws:
      IllegalArgumentException - If the string length is not 1.
    • parseIntWithSuffix

      public static int parseIntWithSuffix(String s)
      Converts a string containing a possible multiplier suffix to an integer.

      The string can contain any of the following multiplier suffixes:

      • "K" - x 1024
      • "M" - x 1024*1024
      • "G" - x 1024*1024*1024
      • "k" - x 1000
      • "m" - x 1000*1000
      • "g" - x 1000*1000*1000
      Parameters:
      s - The string to parse.
      Returns:
      The parsed value.
    • parseIsoCalendar

      Parses an ISO8601 string into a calendar.

      Supports any of the following formats:
      yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddThh, yyyy-MM-ddThh:mm, yyyy-MM-ddThh:mm:ss, yyyy-MM-ddThh:mm:ss.SSS

      Parameters:
      date - The date string.
      Returns:
      The parsed calendar.
      Throws:
      IllegalArgumentException - Value was not a valid date.
    • parseIsoDate

      public static Date parseIsoDate(String date) throws IllegalArgumentException
      Parses an ISO8601 string into a date.

      Supports any of the following formats:
      yyyy, yyyy-MM, yyyy-MM-dd, yyyy-MM-ddThh, yyyy-MM-ddThh:mm, yyyy-MM-ddThh:mm:ss, yyyy-MM-ddThh:mm:ss.SSS

      Parameters:
      date - The date string.
      Returns:
      The parsed date.
      Throws:
      IllegalArgumentException - Value was not a valid date.
    • parseLongWithSuffix

      public static long parseLongWithSuffix(String s)
      Converts a string containing a possible multiplier suffix to a long.

      The string can contain any of the following multiplier suffixes:

      • "K" - x 1024
      • "M" - x 1024*1024
      • "G" - x 1024*1024*1024
      • "T" - x 1024*1024*1024*1024
      • "P" - x 1024*1024*1024*1024*1024
      • "k" - x 1000
      • "m" - x 1000*1000
      • "g" - x 1000*1000*1000
      • "t" - x 1000*1000*1000*1000
      • "p" - x 1000*1000*1000*1000*1000
      Parameters:
      s - The string to parse.
      Returns:
      The parsed value.
    • parseNumber

      public static Number parseNumber(String s, Class<? extends Number> type)
      Parses a number from the specified string.
      Parameters:
      s - The string to parse the number from.
      type - The number type to created. Can be any of the following:
      • Integer
      • Double
      • Float
      • Long
      • Short
      • Byte
      • BigInteger
      • BigDecimal
      If null or Number, uses the best guess.
      Returns:
      The parsed number, or null if the string was null.
    • random

      public static String random(int numchars)
      Generated a random UUID with the specified number of characters.

      Characters are composed of lower-case ASCII letters and numbers only.

      This method conforms to the restrictions for hostnames as specified in RFC 952 Since each character has 36 possible values, the square approximation formula for the number of generated IDs that would produce a 50% chance of collision is: sqrt(36^N). Dividing this number by 10 gives you an approximation of the number of generated IDs needed to produce a <1% chance of collision.

      For example, given 5 characters, the number of generated IDs need to produce a <1% chance of collision would be: sqrt(36^5)/10=777

      Parameters:
      numchars - The number of characters in the generated UUID.
      Returns:
      A new random UUID.
    • repeat

      public static String repeat(int count, String pattern)
      Creates a repeated pattern.
      Parameters:
      count - The number of times to repeat the pattern.
      pattern - The pattern to repeat.
      Returns:
      A new string consisting of the repeated pattern.
    • replaceUnicodeSequences

      Replaces "\\uXXXX" character sequences with their unicode characters.
      Parameters:
      s - The string to replace unicode sequences in.
      Returns:
      A string with unicode sequences replaced.
    • replaceVars

      public static String replaceVars(String s, Map<String,Object> m)
      Simple utility for replacing variables of the form "{key}" with values in the specified map.

      Nested variables are supported in both the input string and map values.

      If the map does not contain the specified value, the variable is not replaced.

      null values in the map are treated as blank strings.

      Parameters:
      s - The string containing variables to replace.
      m - The map containing the variable values.
      Returns:
      The new string with variables replaced, or the original string if it didn't have variables in it.
    • startsWith

      public static boolean startsWith(String s, char c)
      An efficient method for checking if a string starts with a character.
      Parameters:
      s - The string to check. Can be null.
      c - The character to check for.
      Returns:
      true if the specified string is not null and starts with the specified character.
    • stringifyDeep

      public static String stringifyDeep(Object o)
      Converts the specified array to a string.
      Parameters:
      o - The array to convert to a string.
      Returns:
      The array converted to a string, or null if the object was null.
    • strip

      public static String strip(String s)
      Strips the first and last character from a string.
      Parameters:
      s - The string to strip.
      Returns:
      The striped string, or the same string if the input was null or less than length 2.
    • stripInvalidHttpHeaderChars

      Strips invalid characters such as CTRL characters from a string meant to be encoded as an HTTP header value.
      Parameters:
      s - The string to strip chars from.
      Returns:
      The string with invalid characters removed.
    • toCdl

      public static String toCdl(Object o)
      Converts the specified object to a comma-delimited list.
      Parameters:
      o - The object to convert.
      Returns:
      The specified object as a comma-delimited list.
    • toHex

      public static String toHex(byte b)
      Converts the specified byte into a 2 hexadecimal characters.
      Parameters:
      b - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toHex

      public static String toHex(byte[] bytes)
      Converts a byte array into a simple hexadecimal character string.
      Parameters:
      bytes - The bytes to convert to hexadecimal.
      Returns:
      A new string consisting of hexadecimal characters.
    • toHex

      public static String toHex(InputStream is)
      Converts the contents of the specified input stream to a hex string.
      Parameters:
      is - The input stream to convert.
      Returns:
      The hex string representation of the input stream contents, or null if the stream is null.
    • toHex2

      public static char[] toHex2(int num)
      Converts the specified number into a 2 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toHex4

      public static char[] toHex4(int num)
      Converts the specified number into a 4 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[4] containing the specified characters.
    • toHex8

      public static char[] toHex8(long num)
      Converts the specified number into a 8 hexadecimal characters.
      Parameters:
      num - The number to convert to hex.
      Returns:
      A char[8] containing the specified characters.
    • toIsoDate

      public static String toIsoDate(Calendar c)
      Converts the specified object to an ISO8601 date string.
      Parameters:
      c - The object to convert.
      Returns:
      The converted object.
    • toIsoDateTime

      public static String toIsoDateTime(Calendar c)
      Converts the specified object to an ISO8601 date-time string.
      Parameters:
      c - The object to convert.
      Returns:
      The converted object.
    • toReadableBytes

      public static String toReadableBytes(byte[] b)
      Converts the specified bytes into a readable string.
      Parameters:
      b - The number to convert to hex.
      Returns:
      A char[2] containing the specified characters.
    • toSpacedHex

      public static String toSpacedHex(byte[] bytes)
      Same as toHex(byte[]) but puts spaces between the byte strings.
      Parameters:
      bytes - The bytes to convert to hexadecimal.
      Returns:
      A new string consisting of hexadecimal characters.
    • toURI

      public static URI toURI(Object o)
      Converts the specified object to a URI.
      Parameters:
      o - The object to convert to a URI.
      Returns:
      A new URI, or the same object if the object was already a URI, or
    • toUtf8

      public static String toUtf8(byte[] b)
      Converts the specified byte array to a UTF-8 string.
      Parameters:
      b - The byte array to convert.
      Returns:
      The UTF-8 string representation, or null if the array is null.
    • toUtf8

      public static String toUtf8(InputStream is)
      Converts the contents of the specified input stream to a UTF-8 string.
      Parameters:
      is - The input stream to convert.
      Returns:
      The UTF-8 string representation of the input stream contents, or null if the stream is null.
    • trim

      public static String trim(String s)
      Same as String.trim() but prevents NullPointerExceptions.
      Parameters:
      s - The string to trim.
      Returns:
      The trimmed string, or null if the string was null.
    • trimEnd

      public static String trimEnd(String s)
      Trims whitespace characters from the end of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      The trimmed string, or null if the string was null.
    • trimLeadingSlashes

      public static String trimLeadingSlashes(String s)
      Trims '/' characters from the beginning of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      A new trimmed string, or the same string if no trimming was necessary.
    • trimSlashes

      public static String trimSlashes(String s)
      Trims '/' characters from both the start and end of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      A new trimmed string, or the same string if no trimming was necessary.
    • trimSlashesAndSpaces

      public static String trimSlashesAndSpaces(String s)
      Trims '/' and space characters from both the start and end of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      A new trimmed string, or the same string if no trimming was necessary.
    • trimStart

      public static String trimStart(String s)
      Trims whitespace characters from the beginning of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      The trimmed string, or null if the string was null.
    • trimTrailingSlashes

      public static String trimTrailingSlashes(String s)
      Trims '/' characters from the end of the specified string.
      Parameters:
      s - The string to trim.
      Returns:
      A new trimmed string, or the same string if no trimming was necessary.
    • unEscapeChars

      public static String unEscapeChars(String s, AsciiSet escaped)
      Removes escape characters from the specified characters.
      Parameters:
      s - The string to remove escape characters from.
      escaped - The characters escaped.
      Returns:
      A new string if characters were removed, or the same string if not or if the input was null.
    • unicodeSequence

      public static String unicodeSequence(char c)
      Creates an escaped-unicode sequence (e.g. "\\u1234") for the specified character.
      Parameters:
      c - The character to create a sequence for.
      Returns:
      An escaped-unicode sequence.
    • urlDecode

      public static String urlDecode(String s)
      Decodes a application/x-www-form-urlencoded string using UTF-8 encoding scheme.
      Parameters:
      s - The string to decode.
      Returns:
      The decoded string, or null if input is null.
    • urlEncode

      public static String urlEncode(String s)
      Encodes a application/x-www-form-urlencoded string using UTF-8 encoding scheme.
      Parameters:
      s - The string to encode.
      Returns:
      The encoded string, or null if input is null.
    • urlEncodeLax

      public static String urlEncodeLax(String s)
      Same as urlEncode(String) except only escapes characters that absolutely need to be escaped.
      Parameters:
      s - The string to escape.
      Returns:
      The encoded string, or null if input is null.
    • urlEncodePath

      public static String urlEncodePath(Object o)
      Similar to URLEncoder.encode(String, String) but doesn't encode "/" characters.
      Parameters:
      o - The object to encode.
      Returns:
      The URL encoded string, or null if the object was null.