Package com.iizix

Class Utilities


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

      Fields 
      Modifier and TypeFieldDescription
      static java.lang.StringBAT_EXT
      Batch file extension (".bat" for Windows, "" for the others).
      static java.text.CollatorCOLLATOR
      The collator for the default system locale.
      static java.lang.StringEXE_EXT
      Executable extension (".exe" for Windows, "" for the others).
      static java.lang.StringHEXES
      The hexadecimal characters in upper case.
      static booleanisLinux
      Flag for Linux environment.
      static booleanisMac
      Flag for macOS environment.
      static booleanisWindows
      Flag for Windows environment.
      static java.lang.StringLINE_SEPARATOR
      The Line separator ("\r\n" for Windows, "\n" for Unix).
      static java.lang.String[]monthNames
      The month names.
      static java.nio.charset.CharsetUTF8
      The UTF-8 Character set for String or stream encodings.
    • Constructor Summary

      Constructors 
      ConstructorDescription
      Utilities() 
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and TypeMethodDescription
      static voidcopyDirectoryRecursively​(java.io.File src, java.io.File dest, boolean ignoreSVN)
      Copies a directory recursively into a destination directory.
      static javax.xml.transform.TransformercreateDefaultTransformer()
      Creates a default transformer using UTF-8 encoding and indenting.
      static org.w3c.dom.DocumentcreateDocument()
      Creates an empty name-space aware Document.
      static java.io.FilecreateOrUpdateGzip​(java.io.File file)
      Helper method to generate a new Gzip file (if required) from a File.
      static java.lang.StringcreateString​(byte[] data)
      Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
      static java.lang.StringcreateString​(byte[] data, int offset, int length)
      Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.
      static java.awt.datatransfer.TransferablecreateTransferable​(java.lang.String string, java.awt.Image image)
      Creates a transferable used by clipboard and drag-drop.
      static byte[]decodeBase64​(java.lang.String s)
      Decodes a byte array from Base64 format.
      static java.lang.StringdecodeURIComponent​(java.lang.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.
      static booleandeleteDirectoryRecursive​(java.nio.file.Path path, java.util.Map<java.io.File,​java.io.IOException> errorsMap)
      Deletes the directory recursively.
      static java.lang.StringencodeBase64​(byte[] a)
      Encodes a byte array into Base64 format.
      static java.lang.StringencodeBase64​(java.lang.String a)
      Encodes a byte array into Base64 format.
      static java.lang.StringencodePath​(java.lang.String path)
      Constructs an encoded version of the specified path string suitable for use in the construction of a URL.
      static java.lang.StringencodePath​(java.lang.String path, boolean flag)
      Constructs an encoded version of the specified path string suitable for use in the construction of a URL.
      static java.lang.StringencodeURIComponent​(java.lang.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.
      static booleanendsWith​(byte[] source, byte[] suffix)
      Tests if the source byte array ends with the specified suffix byte array.
      static java.lang.StringformatCurrentDate()
      Gets the current date.
      static java.lang.StringformatDate​(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 java.lang.StringformatDate​(java.util.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.
      static java.lang.StringformatDate​(java.util.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.
      static java.lang.StringformatDurationMillis​(long duration)
      Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.
      static java.lang.StringformatEnglishDuration​(long duration)
      Formats a String from a duration in milliseconds to English text as e.g.
      static java.lang.StringformatInGroups​(java.lang.String text, int groupLength)
      Formats a text string in groups of characters with dashes in between.
      static byte[]fromHex​(java.lang.String hexString)
      Parses a String in hex (of even length) to a byte array.
      static voidfullGC()
      Performs the full garbage collection in the current thread.
      static byte[]getBytes​(java.lang.String data)
      Helper function for non-initialized string-to-byte conversion using ISO 8859-1 character set.
      static java.io.FilegetCanonicalFile​(java.io.File file)
      Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
      static java.io.FilegetCanonicalFile​(java.lang.String fileName)
      Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.
      static java.lang.StringgetClipboardString()
      Gets the text from the clipboard.
      static java.lang.StringgetCurrentUTC()
      Gets the current UTC date/time string according to RFC1123 date.
      static javax.xml.transform.TransformerFactorygetDefaultTransformerFactory()
      Creates the default transformer factory.
      static java.lang.StringgetEnglishSize​(long size)
      Gets a size as nn.m TB/GB/MB/KB or bytes.
      static java.lang.StringgetFileSystemValidString​(java.lang.String in)
      Extracts only the valid characters from a String that can be used as a file name for all file systems.
      static java.lang.StringgetFingerPrint​(java.security.cert.Certificate cert, java.lang.String algorithm, boolean colonSeparator)
      Gets the fingerprint of a certificate using an algorithm, typically "SHA-1".
      static java.security.SecureRandomgetSecureRandom()
      Gets the secure random instance.
      static java.lang.StringgetShortestDouble​(double v)
      Formats a double in the shortest possible way (keeping 0.
      static java.lang.StringgetStackTrace​(java.lang.Throwable e)
      After an exception, call this method to get the stack trace.
      static java.lang.StringgetUTC​(java.util.Date date)
      Gets the date/time string according to RFC1123 date.
      static java.lang.StringgetValidName​(java.lang.String name)
      Name validation for e.g.
      static inthashCode​(byte[] source)
      Returns a hash code for the byte array.
      static intindexOf​(byte[] source, byte[] search)
      Returns the index within the source array of the first occurrence of the specified search byte array.
      static intindexOf​(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 intindexOf​(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 booleanisValidEmail​(java.lang.String email)
      Checks if a String is a valid email.
      static booleanisValidEmail​(java.lang.String email, boolean allowLocal, boolean allowTld)
      Checks if a String is a valid email.
      static booleanisValidURL​(java.lang.String url, java.lang.String... schemes)
      Validates an URL.
      static intlastIndexOf​(byte[] source, byte[] search)
      Returns the index within the source byte array of the rightmost occurrence of the specified search byte array.
      static intlastIndexOf​(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 java.lang.StringquoteStringWithSpaces​(java.lang.String string)
      Quotes a string if it contains spaces.
      static byte[]readAllBytes​(java.io.InputStream in)
      Reads all the bytes from an input stream.
      static byte[]readAllBytes​(java.net.URL url)
      Reads all the bytes from a file specified as a URL.
      static intrelaxedSearchIndexOf​(java.lang.String original, int start, java.lang.String search)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
      static intrelaxedSearchIndexOf​(java.lang.String original, int start, java.lang.String search, java.util.Locale locale)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
      static intrelaxedSearchIndexOf​(java.lang.String original, java.lang.String search)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
      static intrelaxedSearchIndexOf​(java.lang.String original, java.lang.String search, java.util.Locale locale)
      Utility method to search for a String in another, as relaxed as possible, typically used when having a searching filter.
      static java.nio.file.PathrenameFileWithTimestamp​(java.io.File file)
      Renames the file to "filename-timestamp.ext".
      static java.lang.StringreplaceStringIgnoreCase​(java.lang.String original, java.lang.String replace)
      Method to replace a string in another, regardless the case of the original string or the replace string.
      static java.lang.StringreplaceStringIgnoreCase​(java.lang.String original, java.lang.String replace, int start)
      Method to replace a string in another, regardless the case of the original string or the replace string.
      static booleansetClipboard​(java.awt.Image image)
      Sets the clipboard with an Image.
      static booleansetClipboard​(java.lang.String string)
      Sets the clipboard with a String.
      static booleansetClipboard​(java.lang.String string, java.awt.Image image)
      Sets the clipboard with a String and an Image.
      static booleanstartsWith​(byte[] source, byte[] prefix)
      Tests if the source byte array starts with the specified prefix byte array.
      static booleanstartsWith​(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 java.lang.StringtoHex​(byte[] ab)
      Converts to hexadecimal.
      static java.lang.StringtoHex​(byte[] ab, int offset, int len)
      Converts to hexadecimal.
      static java.lang.StringtoSignedHex​(int value, int digitCount)
      Converts to signed hexadecimal String as 0x1234 or -0x567898.
      static java.lang.StringtoSignedHex​(long value, int digitCount)
      Converts to signed hexadecimal String as 0x1234 or -0x567898.
      static java.lang.StringtoUnsignedHex​(int value, int digitCount)
      Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
      static java.lang.StringtoUnsignedHex​(long value, int length)
      Converts to unsigned hexadecimal String as 0x1234 or -0x567898.
      static java.lang.StringunquotedStringWithSpaces​(java.lang.String 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 Detail

      • UTF8

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

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

        public static final java.lang.String HEXES
        The hexadecimal characters in upper case.
        See Also:
        Constant Field Values
      • LINE_SEPARATOR

        public static final java.lang.String LINE_SEPARATOR
        The Line separator ("\r\n" for Windows, "\n" for Unix).
      • monthNames

        public static final java.lang.String[] monthNames
        The month names.
      • isWindows

        public static final boolean isWindows
        Flag for Windows environment.
      • isMac

        public static final boolean isMac
        Flag for macOS environment.
      • isLinux

        public static final boolean isLinux
        Flag for Linux environment.
      • EXE_EXT

        public static final java.lang.String EXE_EXT
        Executable extension (".exe" for Windows, "" for the others).
      • BAT_EXT

        public static final java.lang.String BAT_EXT
        Batch file extension (".bat" for Windows, "" for the others).
    • Constructor Detail

      • Utilities

        public Utilities()
    • Method Detail

      • getSecureRandom

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

        public static java.lang.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 java.lang.String formatCurrentDate()
        Gets the current date.
        Returns:
        String formatted as "31 jan 2014 23:59:59.123".
      • formatDate

        public static java.lang.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 java.lang.String formatDate​(java.util.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 java.lang.String formatDate​(java.util.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 java.lang.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 java.lang.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 java.lang.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 java.lang.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 java.lang.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 java.lang.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​(java.lang.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 java.lang.String encodeBase64​(java.lang.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 java.lang.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​(java.lang.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:
        java.lang.IllegalArgumentException - if the input is not valid Base64 encoded data.
      • getStackTrace

        public static java.lang.String getStackTrace​(java.lang.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 javax.xml.transform.TransformerFactory getDefaultTransformerFactory()
        Creates the default transformer factory.
        Returns:
        The default transformer factory, same instance always!
      • createDefaultTransformer

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

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

        public static java.lang.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 java.lang.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​(java.lang.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 java.lang.String getClipboardString()
        Gets the text from the clipboard.
        Returns:
        null for failure or nothing present.
      • setClipboard

        public static boolean setClipboard​(java.lang.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​(java.awt.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​(java.lang.String string,
                                           java.awt.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 java.awt.datatransfer.Transferable createTransferable​(java.lang.String string,
                                                                            java.awt.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.
      • formatDurationMillis

        public static java.lang.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.
      • formatEnglishDuration

        public static java.lang.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 java.lang.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 java.nio.file.Path renameFileWithTimestamp​(java.io.File file)
                                                          throws java.io.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:
        java.io.IOException - For failures.
      • getCanonicalFile

        public static java.io.File getCanonicalFile​(java.lang.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 java.io.File getCanonicalFile​(java.io.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​(java.nio.file.Path path,
                                                       java.util.Map<java.io.File,​java.io.IOException> errorsMap)
                                                throws java.io.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:
        java.io.IOException - If an error occurred while deleting the directories and files and the errorsMap is null.
      • copyDirectoryRecursively

        public static void copyDirectoryRecursively​(java.io.File src,
                                                    java.io.File dest,
                                                    boolean ignoreSVN)
                                             throws java.io.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.
        ignoreSVN - Flag to ignore .svn* files and directories.
        Throws:
        java.io.IOException - For I/O errors.
      • getFileSystemValidString

        public static java.lang.String getFileSystemValidString​(java.lang.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 java.lang.String encodeURIComponent​(java.lang.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 java.lang.String decodeURIComponent​(java.lang.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 encode.
        Returns:
        The encoded string, null if s is null.
      • encodePath

        public static java.lang.String encodePath​(java.lang.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 java.lang.String encodePath​(java.lang.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.
      • isValidEmail

        public static boolean isValidEmail​(java.lang.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​(java.lang.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​(java.lang.String url,
                                         java.lang.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 java.lang.String getFingerPrint​(java.security.cert.Certificate cert,
                                                      java.lang.String algorithm,
                                                      boolean colonSeparator)
                                               throws java.security.cert.CertificateEncodingException,
                                                      java.security.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:
        java.security.cert.CertificateEncodingException - If there is a problem in the certificate.
        java.security.NoSuchAlgorithmException - If the algorithm doesn't exist.
      • formatInGroups

        public static java.lang.String formatInGroups​(java.lang.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:
        java.lang.IllegalArgumentException - If the text string is not exactly divisible by groupLength.
      • relaxedSearchIndexOf

        public static int relaxedSearchIndexOf​(java.lang.String original,
                                               java.lang.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​(java.lang.String original,
                                               int start,
                                               java.lang.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​(java.lang.String original,
                                               java.lang.String search,
                                               java.util.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​(java.lang.String original,
                                               int start,
                                               java.lang.String search,
                                               java.util.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 java.lang.String replaceStringIgnoreCase​(java.lang.String original,
                                                               java.lang.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 java.lang.String replaceStringIgnoreCase​(java.lang.String original,
                                                               java.lang.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​(java.net.URL url)
                                   throws java.io.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:
        java.io.IOException - If an I/O error occurs reading from the stream.
      • readAllBytes

        public static byte[] readAllBytes​(java.io.InputStream in)
                                   throws java.io.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:
        java.io.IOException - If an I/O error occurs reading from the stream.
      • createOrUpdateGzip

        public static java.io.File createOrUpdateGzip​(java.io.File file)
                                               throws java.io.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:
        java.io.IOException - For failures.
      • getCurrentUTC

        public static java.lang.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 java.lang.String getUTC​(java.util.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 java.lang.String getValidName​(java.lang.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 java.lang.String quoteStringWithSpaces​(java.lang.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 java.lang.String unquotedStringWithSpaces​(java.lang.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.