Package com.iizix

Class Utilities

java.lang.Object
com.iizix.Utilities

public class Utilities extends Object
This is a utility class containing static helper functions.
Author:
Christopher Mindus
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final Collator
    The collator for the default system locale.
    static final Pattern
    RegEx for formatting parameters as {}, {param_index}.
    static final String
    The hexadecimal characters in upper case.
    static String
     
    static final String[]
    The month names.
    static final Charset
    The UTF-8 Character set for String or stream encodings.
  • Constructor Summary

    Constructors
    Constructor
    Description
     
  • Method Summary

    Modifier and Type
    Method
    Description
    static byte[]
    Gets the content of the ByteBuffer as a byte[] without mutating the buffer (so thread safe) and minimizing GC (i.e.
    static void
    copyDirectoryRecursively(File src, File dest, boolean ignoreCVS)
    Copies a directory recursively into a destination directory.
    static void
    copyDirectoryRecursively(File src, File dest, boolean ignoreCVS, boolean doReplace)
    Copies a directory recursively into a destination directory.
    Creates a default transformer using UTF-8 encoding and indenting.
    static Document
    Creates an empty name-space aware Document.
    static File
    Helper method to generate a new Gzip file (if required) from a File.
    static String
    createString(byte[] data)
    Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
    static String
    createString(byte[] data, int offset, int length)
    Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
    Creates a transferable used by clipboard and drag-drop.
    static byte[]
    Decodes a byte array from Base64 format.
    static String
    Replaces potential encoded URI special characters %20 ' ', %21 '!', %27 "'", %28 '(', %29 '), %7E '~', all other characters are left as is.
    static String
    Decodes a String as the JavaScript decodeURIComponent(string) would do as URIDecoder.decode(string,"UTF-8") does not handle spaces and some other characters correctly.
    static String
    Returns a string representation of the "deep contents" of the specified array.
    static boolean
    Deletes the directory recursively.
    static String
    Constructs an encoded version of the specified path string suitable for use in the construction of a URL.
    static String
    encodeBase64(byte[] a)
    Encodes a byte array into Base64 format.
    static String
    Encodes a byte array into Base64 format.
    static String
    Constructs an encoded version of the specified path string suitable for use in the construction of a URL.
    static String
    encodePath(String path, boolean flag)
    Constructs an encoded version of the specified path string suitable for use in the construction of a URL.
    static String
    Encodes a String as the JavaScript encodeURIComponent(string) would do as URIEncoder.encode(string,"UTF-8") does not handle spaces and some other characters correctly.
    static boolean
    endsWith(byte[] source, byte[] suffix)
    Tests if the source byte array ends with the specified suffix byte array.
    static String
    format(LocaleInfo localeInfo, String string, Object... params)
    Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.
    static String
    format(ILocaleString localeString, String string, Object... params)
    Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.
    static String
    format(String string, Object... params)
    Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.
    static String
    format(Locale locale, String string, Object... params)
    Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.
    static String
    Gets the current date.
    static String
    formatDate(long timeInMillis)
    Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
    static String
    Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
    static String
    Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
    static String
    formatDurationMillis(long duration)
    Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.
    static String
    formatDurationNanos(long nanoDuration)
    Formats a String from a duration in nanoseconds as h:mm:ss.mmm.nnn.nnn.
    static String
    formatEnglishDuration(long duration)
    Formats a String from a duration in milliseconds to English text as e.g.
    static String
    formatEnglishNanoDuration(long nanoDuration)
    Formats a String from a duration in milliseconds to English text as e.g.
    static String
    formatInGroups(String text, int groupLength)
    Formats a text string in groups of characters with dashes in between.
    static byte[]
    fromHex(String hexString)
    Parses a String in hex (of even length) to a byte array.
    static void
    Performs the full garbage collection in the current thread.
    static byte[]
    Helper function for non-initialized string-to-byte conversion using ISO 8859-1 character set.
    static File
    Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
    static File
    Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
    static String
    Gets the text from the clipboard.
    static String
    Gets the current UTC date/time string according to RFC1123 date.
    Creates the default transformer factory.
    static String
    getEnglishSize(long size)
    Gets a size as nn.m TB/GB/MB/KB or bytes.
    static String
    Extracts only the valid characters from a String that can be used as a file name for all file systems.
    static String
    getFingerPrint(Certificate cert, String algorithm, boolean colonSeparator)
    Gets the fingerprint of a certificate using an algorithm, typically "SHA-1".
    Gets the secure random instance.
    static String
    Formats a double in the shortest possible way (keeping 0.
    static String
    After an exception, call this method to get the stack trace.
    static String
    getUTC(Date date)
    Gets the date/time string according to RFC1123 date.
    static String
    Name validation for e.g.
    static int
    hashCode(byte[] source)
    Returns a hash code for the byte array.
    static int
    indexOf(byte[] source, byte[] search)
    Returns the index within the source array of the first occurrence of the specified search byte array.
    static int
    indexOf(byte[] source, byte[] search, int fromIndex)
    Returns the index within the source byte array of the first occurrence of the specified search byte array, starting at the specified index.
    static int
    indexOf(byte[] source, int sourceOffset, int sourceCount, byte[] target, int targetOffset, int targetCount, int fromIndex)
    The source is the byte array being searched, and the target is the byte array being searched for.
    static boolean
    Checks if a String is a valid email.
    static boolean
    isValidEmail(String email, boolean allowLocal, boolean allowTld)
    Checks if a String is a valid email.
    static boolean
    isValidURL(String url, String... schemes)
    Validates an URL.
    static int
    lastIndexOf(byte[] source, byte[] search)
    Returns the index within the source byte array of the rightmost occurrence of the specified search byte array.
    static int
    lastIndexOf(byte[] source, byte[] search, int fromIndex)
    Returns the index within the source byte array of the last occurrence of the specified search byte array, searching backward starting at the specified index.
    static String
    Quotes a string if it contains spaces.
    static byte[]
    Reads all the bytes from an input stream.
    static byte[]
    Reads all the bytes from a file specified as a URL.
    static int
    relaxedSearchIndexOf(String original, int start, String search)
    Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
    static int
    relaxedSearchIndexOf(String original, int start, String search, Locale locale)
    Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
    static int
    relaxedSearchIndexOf(String original, String search)
    Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
    static int
    relaxedSearchIndexOf(String original, String search, Locale locale)
    Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
    static Path
    Renames the file to "filename-timestamp.ext".
    static String
    Method to replace a string in another, regardless the case of the original string or the replace string.
    static String
    replaceStringIgnoreCase(String original, String replace, int start)
    Method to replace a string in another, regardless the case of the original string or the replace string.
    static boolean
    Sets the clipboard with an Image.
    static boolean
    Sets the clipboard with a String.
    static boolean
    setClipboard(String string, Image image)
    Sets the clipboard with a String and an Image.
    static boolean
    startsWith(byte[] source, byte[] prefix)
    Tests if the source byte array starts with the specified prefix byte array.
    static boolean
    startsWith(byte[] source, byte[] prefix, int sourceIndex)
    Tests if the source sub-byte array of a byte array beginning at the specified source index starts with the specified prefix.
    static String
    toHex(byte[] ab)
    Converts to hexadecimal.
    static String
    toHex(byte[] ab, int offset, int len)
    Converts to hexadecimal.
    static String
    toSignedHex(int value, int digitCount)
    Converts to signed hexadecimal String as 0x1234 or -0x567898.
    static String
    toSignedHex(long value, int digitCount)
    Converts to signed hexadecimal String as 0x1234 or -0x567898.
    static String
    Cracks the "Object" using toString, or special handling if it's an array or throwable.
    static String
    toUnsignedHex(int value, int digitCount)
    Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
    static String
    toUnsignedHex(long value, int length)
    Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
    static String
    Gets an unquoted string if it contains double-quotes around it and it contains spaces.

    Methods inherited from class java.lang.Object

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

    • UTF8

      public static final Charset UTF8
      The UTF-8 Character set for String or stream encodings.
    • COLLATOR

      public static final Collator COLLATOR
      The collator for the default system locale.
    • HEXES

      public static final String HEXES
      The hexadecimal characters in upper case.
      See Also:
    • monthNames

      public static final String[] monthNames
      The month names.
    • formatCurlyPattern

      public static final Pattern formatCurlyPattern
      RegEx for formatting parameters as {}, {param_index}.
         {[argument_index]}
       
    • lastUsedFS

      public static String lastUsedFS
  • Constructor Details

    • Utilities

      public Utilities()
  • Method Details

    • getSecureRandom

      public static SecureRandom getSecureRandom()
      Gets the secure random instance.
      Returns:
      The secure random instance.
    • getShortestDouble

      public static String getShortestDouble(double v)
      Formats a double in the shortest possible way (keeping 0. if less than zero) without using exponential notation.
      Parameters:
      v - The double value.
      Returns:
      String The string.
    • formatCurrentDate

      public static String formatCurrentDate()
      Gets the current date.
      Returns:
      String formatted as "31 jan 2014 23:59:59.123".
    • formatDate

      public static String formatDate(long timeInMillis)
      Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
      Parameters:
      timeInMillis - Time in milliseconds since the epoch.
      Returns:
      String formatted as "31 jan 2014 23:59:59.123".
    • formatDate

      public static String formatDate(Date date)
      Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
      Parameters:
      date - The date to format.
      Returns:
      String formatted as "31 jan 2014 23:59:59.123".
    • formatDate

      public static String formatDate(Calendar c)
      Formats the Date instance to a string that is used by the dump methods in this class as well as other event logs.
      Parameters:
      c - The calendar to format.
      Returns:
      String formatted as "31 jan 2014 23:59:59.123".
    • toSignedHex

      public static String toSignedHex(int value, int digitCount)
      Converts to signed hexadecimal String as 0x1234 or -0x567898.
      Parameters:
      value - The value to convert.
      digitCount - Number of digits to fill out (valid value is 1 to 8, where "0x" and "sign" are not included in the count of digits).
      Returns:
      The formatted string, all in upper case (except the "0x" part).
    • toSignedHex

      public static String toSignedHex(long value, int digitCount)
      Converts to signed hexadecimal String as 0x1234 or -0x567898.
      Parameters:
      value - The value to convert.
      digitCount - Number of digits to fill out (valid value is 1 to 16, where "0x" and "sign" are not included in the count of digits).
      Returns:
      The formatted string, all in upper case (except the "0x" part).
    • toUnsignedHex

      public static String toUnsignedHex(int value, int digitCount)
      Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
      Parameters:
      value - The value to convert.
      digitCount - Number of digits to fill out (valid value is 1 to 8, where "0x" is not included in the count of digits).
      Returns:
      The formatted string, all in upper case (except the "0x" part).
    • toUnsignedHex

      public static String toUnsignedHex(long value, int length)
      Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
      Parameters:
      value - The value to convert.
      length - Number of digits to fill out (valid value is 1 to 16, where "0x" is not included in the count of digits).
      Returns:
      The formatted string.
    • toHex

      public static String toHex(byte[] ab)
      Converts to hexadecimal.
      Parameters:
      ab - Array of bytes to convert to a hexadecimal string of twice the size.
      Returns:
      The hexadecimal representation of the byte array.
    • toHex

      public static String toHex(byte[] ab, int offset, int len)
      Converts to hexadecimal.
      Parameters:
      ab - Array of bytes to convert to a hexadecimal string of twice the size.
      offset - Offset in buffer.
      len - Length of data.
      Returns:
      The hexadecimal representation of the byte array.
    • fromHex

      public static byte[] fromHex(String hexString)
      Parses a String in hex (of even length) to a byte array.
      Parameters:
      hexString - A String in hex, characters 0-9 and a-f or A-F, even length required.
      Returns:
      A byte array of half the size of the hex string, null if an error is encountered.
    • encodeBase64

      public static String encodeBase64(String a)
      Encodes a byte array into Base64 format. No blanks or line breaks are inserted.
      Parameters:
      a - an array containing the data bytes to be encoded.
      Returns:
      A String with the Base64 encoded data.
    • encodeBase64

      public static String encodeBase64(byte[] a)
      Encodes a byte array into Base64 format. No blanks or line breaks are inserted.
      Parameters:
      a - an array containing the data bytes to be encoded.
      Returns:
      A String with the Base64 encoded data.
    • decodeBase64

      public static byte[] decodeBase64(String s)
      Decodes a byte array from Base64 format.
      Parameters:
      s - a Base64 String to be decoded.
      Returns:
      An array containing the decoded data bytes.
      Throws:
      IllegalArgumentException - if the input is not valid Base64 encoded data.
    • asByteArray

      public static byte[] asByteArray(ByteBuffer buf)
      Gets the content of the ByteBuffer as a byte[] without mutating the buffer (so thread safe) and minimizing GC (i.e. object creation).
      Parameters:
      buf - The ByteBuffer.
      Returns:
      The byte array, perhaps not newly allocated, but using the ByteArray buf.array().
    • getStackTrace

      public static String getStackTrace(Throwable e)
      After an exception, call this method to get the stack trace. This method is "fail-safe", i.e. if it's a StackOverflowError or the stack trace causes an OutOfMemoryError, just the exception string is returned.
      Parameters:
      e - The exception.
      Returns:
      The stack trace.
    • getDefaultTransformerFactory

      public static TransformerFactory getDefaultTransformerFactory()
      Creates the default transformer factory.
      Returns:
      The default transformer factory, same instance always!
    • createDefaultTransformer

      public static Transformer createDefaultTransformer() throws TransformerConfigurationException
      Creates a default transformer using UTF-8 encoding and indenting.
      Returns:
      The transformer, initialized properly.
      Throws:
      TransformerConfigurationException - When the transformer configuration is in error.
    • createDocument

      public static Document createDocument()
      Creates an empty name-space aware Document.
      Returns:
      The document.
    • createString

      public static String createString(byte[] data)
      Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
      Parameters:
      data - The data to convert.
      Returns:
      The String in ISO-8859-1 character set.
    • createString

      public static String createString(byte[] data, int offset, int length)
      Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
      Parameters:
      data - The data to convert.
      offset - The offset in the data.
      length - The length in the data.
      Returns:
      The String in ISO-8859-1 character set.
    • getBytes

      public static byte[] getBytes(String data)
      Helper function for non-initialized string-to-byte conversion using ISO 8859-1 character set.
      Parameters:
      data - The String data.
      Returns:
      The bytes of the String in ISO-8859-1 character set.
    • startsWith

      public static boolean startsWith(byte[] source, byte[] prefix, int sourceIndex)
      Tests if the source sub-byte array of a byte array beginning at the specified source index starts with the specified prefix.
      Parameters:
      source - The source byte array.
      prefix - The prefix byte array.
      sourceIndex - Where to begin looking in the source array.
      Returns:
      true if the source byte array starting at the specified sourceIndex starts with the prefix byte array; false otherwise. The result is false if sourceIndex is negative or greater than the length of this source array.
    • startsWith

      public static boolean startsWith(byte[] source, byte[] prefix)
      Tests if the source byte array starts with the specified prefix byte array.
      Parameters:
      source - The source byte array.
      prefix - The prefix byte array.
      Returns:
      true if the source byte array starts with the prefix byte array; false otherwise.
    • endsWith

      public static boolean endsWith(byte[] source, byte[] suffix)
      Tests if the source byte array ends with the specified suffix byte array.
      Parameters:
      source - The source byte array.
      suffix - The suffix byte array.
      Returns:
      true if the source byte array ends with the suffix byte array; false otherwise.
    • hashCode

      public static int hashCode(byte[] source)
      Returns a hash code for the byte array. The hash code is computed as
       (source[0]&0xFF)*31^(n-1) + (source[1]&0xFF)*31^(n-2) + ... + (source[n-1]&0xFF)
       
      using int arithmetic, where source[i] is the ith byte of the array, n is the length of the byte array, and ^ indicates exponentiation. (The hash value of the array length is zero.)

      Note: each byte uses the value 0-255 and not -127 to 128.

      Note 2: this method returns the same hash code as new String(source,StandardCharsets.ISO_8859_1).hashCode().

      Parameters:
      source - the byte array.
      Returns:
      a hash code value for the byte array.
    • indexOf

      public static int indexOf(byte[] source, byte[] search)
      Returns the index within the source array of the first occurrence of the specified search byte array. The integer returned is the smallest value k such that:
       startsWith(source,search,k)
       
      is true.
      Parameters:
      source - the source byte array.
      search - the byte array to locate in the source array.
      Returns:
      the index where search first occurs in source; -1 if isn't present.
    • indexOf

      public static int indexOf(byte[] source, byte[] search, int fromIndex)
      Returns the index within the source byte array of the first occurrence of the specified search byte array, starting at the specified index. The integer returned is the smallest value k for which:
           k >= Math.min(fromIndex,source.length) && this.startsWith(source,search,k)
       
      If no such value of k exists, then -1 is returned.
      Parameters:
      source - the source byte array.
      search - the byte array to locate in the source array.
      fromIndex - the index from which to start the search.
      Returns:
      the index within the source byte array of the first occurrence of the specified search byte array, starting at the specified index.
    • indexOf

      public static int indexOf(byte[] source, int sourceOffset, int sourceCount, byte[] target, int targetOffset, int targetCount, int fromIndex)
      The source is the byte array being searched, and the target is the byte array being searched for.
      Parameters:
      source - the bytes being searched.
      sourceOffset - offset of the source.
      sourceCount - count of the source.
      target - the bytes being searched for.
      targetOffset - offset of the target.
      targetCount - count of the target.
      fromIndex - the index to begin searching from.
      Returns:
      -1 if not found; otherwise the first occurrence of what is being searched for.
    • lastIndexOf

      public static int lastIndexOf(byte[] source, byte[] search)
      Returns the index within the source byte array of the rightmost occurrence of the specified search byte array. The rightmost empty byte array is considered to occur at the index value source.length. The returned index is the largest value k such that
       startsWith(source,search,k)
       
      is true.
      Parameters:
      source - the bytes being searched.
      search - the byte array to search for.
      Returns:
      if the search argument occurs one or more times as a sub-byte array within the source byte array, then the index of the first byte of the last such search sub-byte array is returned. If it does not occur as a sub-byte array, -1 is returned.
    • lastIndexOf

      public static int lastIndexOf(byte[] source, byte[] search, int fromIndex)
      Returns the index within the source byte array of the last occurrence of the specified search byte array, searching backward starting at the specified index. The integer returned is the largest value k such that:
           k <= Math.min(fromIndex,source.length) && startsWith(source,search,k)
       
      If no such value of k exists, then -1 is returned.
      Parameters:
      source - the bytes being searched.
      search - the byte array to search for.
      fromIndex - the index to start the search from.
      Returns:
      the index within the source byte array of the last occurrence of the specified source byte array.
    • getClipboardString

      public static String getClipboardString()
      Gets the text from the clipboard.
      Returns:
      null for failure or nothing present.
    • setClipboard

      public static boolean setClipboard(String string)
      Sets the clipboard with a String.
      Parameters:
      string - The data to set in the clipboard.
      Returns:
      true for success, false for failure.
    • setClipboard

      public static boolean setClipboard(Image image)
      Sets the clipboard with an Image.
      Parameters:
      image - The image to set in the clipboard.
      Returns:
      true for success, false for failure.
    • setClipboard

      public static boolean setClipboard(String string, Image image)
      Sets the clipboard with a String and an Image.
      Parameters:
      string - The data to set in the clipboard, null for none.
      image - The image to set in the clipboard, null for none.
      Returns:
      true for success, false for failure.
    • createTransferable

      public static Transferable createTransferable(String string, Image image)
      Creates a transferable used by clipboard and drag-drop.
      Parameters:
      string - The data to set for the clipboard, null for none.
      image - The image to set for the clipboard, null for none.
      Returns:
      The transferable to set in the clipboard for the potential string and image.
    • formatDurationNanos

      public static String formatDurationNanos(long nanoDuration)
      Formats a String from a duration in nanoseconds as h:mm:ss.mmm.nnn.nnn.
      Parameters:
      nanoDuration - Duration in nanoseconds.
      Returns:
      A String representation of the duration as h:mm:ss.mmm.nnn.nnn.
    • formatDurationMillis

      public static String formatDurationMillis(long duration)
      Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.
      Parameters:
      duration - Duration in milliseconds.
      Returns:
      A String representation of the duration as hhhhh:mm:ss.mmm.
    • formatEnglishNanoDuration

      public static String formatEnglishNanoDuration(long nanoDuration)
      Formats a String from a duration in milliseconds to English text as e.g. 1 hour and 5 seconds.
      Parameters:
      nanoDuration - Duration in nanoseconds.
      Returns:
      The string in English, e.g. 1 hour and 5 seconds.
    • formatEnglishDuration

      public static String formatEnglishDuration(long duration)
      Formats a String from a duration in milliseconds to English text as e.g. 1 hour and 5 seconds.
      Parameters:
      duration - Duration in milliseconds.
      Returns:
      The string in English, e.g. 1 hour and 5 seconds.
    • getEnglishSize

      public static String getEnglishSize(long size)
      Gets a size as nn.m TB/GB/MB/KB or bytes.
      Parameters:
      size - The positive size value.
      Returns:
      A string formatted with the current user's decimal separator as M.NN [unit].
    • fullGC

      public static void fullGC()
      Performs the full garbage collection in the current thread.
    • renameFileWithTimestamp

      public static Path renameFileWithTimestamp(File file) throws IOException
      Renames the file to "filename-timestamp.ext". If the timestamped file exists, this method will throw an exception.
      Parameters:
      file - The file.
      Returns:
      The renamed file path.
      Throws:
      IOException - For failures.
    • getCanonicalFile

      public static File getCanonicalFile(String fileName)
      Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
      Parameters:
      fileName - File or directory.
      Returns:
      The canonical file or directory, and if it failed, the absolute file or directory.
    • getCanonicalFile

      public static File getCanonicalFile(File file)
      Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
      Parameters:
      file - File or directory.
      Returns:
      The canonical file or directory, and if it failed, the absolute file or directory.
    • deleteDirectoryRecursive

      public static boolean deleteDirectoryRecursive(Path path, Map<File,IOException> errorsMap) throws IOException
      Deletes the directory recursively.
      Parameters:
      path - The path.
      errorsMap - The errors map that is filled in for each error, null for none (this will throw and IOExeception instead upon first error).
      Returns:
      true for success, false for failure.
      Throws:
      IOException - If an error occurred while deleting the directories and files and the errorsMap is null.
    • copyDirectoryRecursively

      public static void copyDirectoryRecursively(File src, File dest, boolean ignoreCVS) throws IOException
      Copies a directory recursively into a destination directory. The destination files and directories will not be replaced and will then throw an error.
      Parameters:
      src - The source directory to copy.
      dest - The destination directory.
      ignoreCVS - Flag to ignore .svn* and .git* files and directories.
      Throws:
      IOException - For I/O errors.
    • copyDirectoryRecursively

      public static void copyDirectoryRecursively(File src, File dest, boolean ignoreCVS, boolean doReplace) throws IOException
      Copies a directory recursively into a destination directory. The destination files and directories will not be replaced and will then throw an error if the flag doReplace is true, but will throw an error if one is a file and the other is a directory.
      Parameters:
      src - The source directory to copy.
      dest - The destination directory.
      ignoreCVS - Flag to ignore .svn* and .git* files and directories.
      doReplace - Replace existing files or fail if it exists.
      Throws:
      IOException - For I/O errors.
    • getFileSystemValidString

      public static String getFileSystemValidString(String in)
      Extracts only the valid characters from a String that can be used as a file name for all file systems. Valid characters are between ASCII 32 and 253, not 127, and not < > : ; " ' / \ | ? *. Other invalid characters are Atom.RESERVED_CHARS.
      Parameters:
      in - Input string.
      Returns:
      String with only "valid" characters.
    • encodeURIComponent

      public static String encodeURIComponent(String s)
      Encodes a String as the JavaScript encodeURIComponent(string) would do as URIEncoder.encode(string,"UTF-8") does not handle spaces and some other characters correctly.
      Parameters:
      s - The string to encode.
      Returns:
      The encoded string, null if s is null.
    • decodeURIComponent

      public static String decodeURIComponent(String s)
      Decodes a String as the JavaScript decodeURIComponent(string) would do as URIDecoder.decode(string,"UTF-8") does not handle spaces and some other characters correctly.
      Parameters:
      s - The string to decode.
      Returns:
      The decoded string, null if s is null.
      Throws:
      IllegalArgumentException - If the implementation encounters illegal characters.
    • decodeSpecialURIChars

      public static String decodeSpecialURIChars(String s)
      Replaces potential encoded URI special characters %20 ' ', %21 '!', %27 "'", %28 '(', %29 '), %7E '~', all other characters are left as is.
      Parameters:
      s - The string to decode.
      Returns:
      The decoded string.
      Throws:
      NullPointerException - If the parameter is null.
    • encodePath

      public static String encodePath(String path)
      Constructs an encoded version of the specified path string suitable for use in the construction of a URL.

      A path separator is replaced by a forward slash. The string is UTF8 encoded. The % escape sequence is used for characters that are above 0x7F or those defined in RFC2396 as reserved or excluded in the path component of a URL.

      Parameters:
      path - The path to encode.
      Returns:
      The encoded path.
    • encodePath

      public static String encodePath(String path, boolean flag)
      Constructs an encoded version of the specified path string suitable for use in the construction of a URL.

      A path separator is replaced by a forward slash. The string is UTF8 encoded. The % escape sequence is used for characters that are above 0x7F or those defined in RFC2396 as reserved or excluded in the path component of a URL.

      Parameters:
      path - The path to encode.
      flag - Indicates whether path uses platform dependent File.separatorChar or not. true indicates path uses platform dependent File.separatorChar.
      Returns:
      The encoded path.
    • encodeAnyPath

      public static String encodeAnyPath(String path)
      Constructs an encoded version of the specified path string suitable for use in the construction of a URL.

      A path separator is replaced by a forward or backward slash. The string is UTF8 encoded. The % escape sequence is used for characters that are above 0x7F or those defined in RFC2396 as reserved or excluded in the path component of a URL.

      Parameters:
      path - The path to encode, with forward or backslash as separator.
      Returns:
      The encoded path, always using '/' as path separator.
    • isValidEmail

      public static boolean isValidEmail(String email)
      Checks if a String is a valid email. Local address is not valid and TLDs are not allowed.
      Parameters:
      email - The email to verify.
      Returns:
      true if valid, false otherwise (or email is null).
    • isValidEmail

      public static boolean isValidEmail(String email, boolean allowLocal, boolean allowTld)
      Checks if a String is a valid email.
      Parameters:
      email - The email to verify.
      allowLocal - Should local addresses be considered valid?
      allowTld - Should TLDs be allowed?
      Returns:
      true if valid, false otherwise (or email is null).
    • isValidURL

      public static boolean isValidURL(String url, String... schemes)
      Validates an URL.
      Parameters:
      url - URL to verify.
      schemes - The schemes to accept, empty for all.
      Returns:
      true for valid, false for not valid (or null).
    • getFingerPrint

      public static String getFingerPrint(Certificate cert, String algorithm, boolean colonSeparator) throws CertificateEncodingException, NoSuchAlgorithmException
      Gets the fingerprint of a certificate using an algorithm, typically "SHA-1".
      Parameters:
      cert - The certificate.
      algorithm - The algorithm (normally "SHA-1").
      colonSeparator - Place color separators between groups of 2 hexes.
      Returns:
      The fingerprint in hex as "12:34:56:78:9A:BC..." (if colonSeparator is true), otherwise the hex string.
      Throws:
      CertificateEncodingException - If there is a problem in the certificate.
      NoSuchAlgorithmException - If the algorithm doesn't exist.
    • formatInGroups

      public static String formatInGroups(String text, int groupLength)
      Formats a text string in groups of characters with dashes in between.
      Parameters:
      text - The text string to format, MUST be be exactly divisible by groupLength.
      groupLength - The length of each group in characters.
      Returns:
      The formatted string in groups of groupLength characters separated with a dash ('-').
      Throws:
      IllegalArgumentException - If the text string is not exactly divisible by groupLength.
    • relaxedSearchIndexOf

      public static int relaxedSearchIndexOf(String original, String search)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.

      The default locale is used, and the original string is searched from the beginning.

      Parameters:
      original - The original string to search in.
      search - The search string to find in the original string.
      Returns:
      The index found or -1 for not found.
    • relaxedSearchIndexOf

      public static int relaxedSearchIndexOf(String original, int start, String search)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.

      The default locale is used.

      Parameters:
      original - The original string to search in.
      start - The staring position in the original string, -1 for the first position.
      search - The search string to find in the original string.
      Returns:
      The index found or -1 for not found.
    • relaxedSearchIndexOf

      public static int relaxedSearchIndexOf(String original, String search, Locale locale)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.

      The original string is searched from the beginning.

      Parameters:
      original - The original string to search in.
      search - The search string to find in the original string.
      locale - The locale to use for the search, null for default, null to use default locale.
      Returns:
      The index found or -1 for not found.
    • relaxedSearchIndexOf

      public static int relaxedSearchIndexOf(String original, int start, String search, Locale locale)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
      Parameters:
      original - The original string to search in.
      start - The staring position in the original string, -1 for the first position.
      search - The search string to find in the original string.
      locale - The locale to use for the search, null for default, null to use default locale.
      Returns:
      The index found or -1 for not found.
    • replaceStringIgnoreCase

      public static String replaceStringIgnoreCase(String original, String replace)
      Method to replace a string in another, regardless the case of the original string or the replace string.

      Note: there are cases where the replacement might not occur properly when the case of the strings upper/lower do not match in length (e.g. German Double-S: upper case "SS" and lower case "ß".

      The word casing is of no importance: the string search is always performed from the beginning of the original string and the replace string. Once the replace string is found (no matter the case), the search for the next occurrence will start at the next position where the replace was found. This may not seem to be very optimal, but is necessary in order to replace all words in the original string.

      Parameters:
      original - The original String.
      replace - The replace String.
      Returns:
      The replaced string.
    • replaceStringIgnoreCase

      public static String replaceStringIgnoreCase(String original, String replace, int start)
      Method to replace a string in another, regardless the case of the original string or the replace string.

      Note: there are cases where the replacement might not occur properly when the case of the strings upper/lower do not match in length (e.g. German Double-S: upper case "SS" and lower case "ß".

      Parameters:
      original - The original String.
      replace - The replace String.
      start - The start position in the original string, 0 or negative or first position.
      Returns:
      The replaced string.
    • readAllBytes

      public static byte[] readAllBytes(URL url) throws IOException
      Reads all the bytes from a file specified as a URL. The method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

      Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.

      Parameters:
      url - The URL of the file.
      Returns:
      A byte array containing the bytes read from the file.
      Throws:
      IOException - If an I/O error occurs reading from the stream.
    • readAllBytes

      public static byte[] readAllBytes(InputStream in) throws IOException
      Reads all the bytes from an input stream. The InputStream is closed before this method returns.

      Note that this method is intended for simple cases where it is convenient to read all bytes into a byte array. It is not intended for reading in large files.

      Parameters:
      in - The input stream.
      Returns:
      A byte array containing the bytes read from the input stream.
      Throws:
      IOException - If an I/O error occurs reading from the stream.
    • createOrUpdateGzip

      public static File createOrUpdateGzip(File file) throws IOException
      Helper method to generate a new Gzip file (if required) from a File. The timestamp is verified for match in case the Gzip file is present. If a Gzip file is created or updated, the timestamp of the original file is applied.
      Returns:
      The file created or updated, null if it was not required.
      Throws:
      IOException - For failures.
    • getCurrentUTC

      public static String getCurrentUTC()
      Gets the current UTC date/time string according to RFC1123 date.
      Returns:
      A String formatted as "EEE, dd MMM yyyy HH:mm:ss 'GMT'" with the current date.
    • getUTC

      public static String getUTC(Date date)
      Gets the date/time string according to RFC1123 date.
      Parameters:
      date - The date.
      Returns:
      A String formatted as "EEE, dd MMM yyyy HH:mm:ss 'GMT'" with the date.
    • getValidName

      public static String getValidName(String name)
      Name validation for e.g. App ID and Topic (for Push Notification).

      Validates that the name consists of groups or characters a-z, A-Z, 0-9 or dash (-). The group length is between 1 and 63 characters. Each group cannot start or end with dash (-), nor contain two or more consecutive dashes (e.g. --). The last group must be a-z or A-Z of length between 2 and 63. Each group can be separated by a dot and. The total maximum name length is 253.

      The server database stores the App ID and Topic in lower case, thus this method returns the valid string in lower case.

      Parameters:
      name - The name to validate.
      Returns:
      The name in lower case if valid, null if not valid.
    • quoteStringWithSpaces

      public static String quoteStringWithSpaces(String string)
      Quotes a string if it contains spaces.
      Parameters:
      string - The string value.
      Returns:
      The string, perhaps surrounded by double-quotes (if it isn't already).
    • unquotedStringWithSpaces

      public static String unquotedStringWithSpaces(String string)
      Gets an unquoted string if it contains double-quotes around it and it contains spaces.
      Parameters:
      string - The string.
      Returns:
      The unquoted string if it contained spaces and double-quotes, otherwise the original string.
    • toString

      public static String toString(Object o)
      Cracks the "Object" using toString, or special handling if it's an array or throwable.
      Parameters:
      o - The Object to expand.
      Returns:
      The expanded string of the object.
    • deepToString

      public static String deepToString(Object[] o)
      Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.

      The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by ILog.toString(Object), unless they are themselves arrays.

      If an element e is an array of a primitive type, it is converted to a string as by invoking the appropriate overloading of Arrays.toString(e). If an element e is an array of a reference type, it is converted to a string as by invoking this method recursively.

      To avoid infinite recursion, if the specified array contains itself as an element, or contains an indirect reference to itself through one or more levels of arrays, the self-reference is converted to the string "[...]". For example, an array containing only a reference to itself would be rendered as "[[...]]".

      This method returns "null" if the specified array is null.

      Parameters:
      o - The array whose string representation to return.
      Returns:
      a string representation of a.
    • format

      public static String format(String string, Object... params)
      Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.

      Parameters referenced by {[param_index]} are converted toString() using {@link Utilities#toString()} enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using %s will not receive this "toString" conversion (unless they target the same param_index.

      The formatting string replaces {} with %s and {param_index} with %param_index$s.

      The locale is looked up from the current thread if required.

      Parameters:
      string - The string to format using curly-bracket reference or String.format(Locale, String, Object...).
      params - The parameters.
      Returns:
      The formatted string.
      See Also:
    • format

      public static String format(Locale locale, String string, Object... params)
      Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.

      Parameters referenced by {[param_index]} are converted toString() using {@link Utilities#toString()} enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using %s will not receive this "toString" conversion (unless they target the same param_index.

      The formatting string replaces {} with %s and {param_index} with %param_index$s.

      Parameters:
      locale - The Locale, or null to look it up for the current thread if needed.
      string - The string to format.
      params - The parameters.
      Returns:
      The formatted string.
      See Also:
    • format

      public static String format(ILocaleString localeString, String string, Object... params)
      Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.

      Parameters referenced by {[param_index]} are converted toString() using {@link Utilities#toString()} enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using %s will not receive this "toString" conversion (unless they target the same param_index.

      The formatting string replaces {} with %s and {param_index} with %param_index$s.

      Parameters:
      localeString - The locale string instance, or null for current session.
      string - The string to format.
      params - The parameters.
      Returns:
      The formatted string.
      See Also:
    • format

      public static String format(LocaleInfo localeInfo, String string, Object... params)
      Formats a String using curly brackets {} as parameter or {param_index} parameter where param_index is an optional one-based index value, AND/OR the Java String.format(Locale, String, Object...) method using parameters in the form of %[flags][width]conversion or %[argument_index$][flags][width]conversion.

      Parameters referenced by {[param_index]} are converted toString() using {@link Utilities#toString()} enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using %s will not receive this "toString" conversion (unless they target the same param_index.

      The formatting string replaces {} with %s and {param_index} with %param_index$s.

      Parameters:
      localeInfo - The Locale information, or null to look it up from the current thread if needed.
      string - The string to format.
      params - The parameters, or null for none.
      Returns:
      The formatted string.
      See Also: