Class Utilities
- Author:
- Christopher Mindus
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final CollatorThe collator for the default system locale.static final PatternRegEx for formatting parameters as{},{param_index}.static final StringThe hexadecimal characters in upper case.static Stringstatic final String[]The month names.static final CharsetThe UTF-8 Character set for String or stream encodings.Constructor Summary
ConstructorsMethod Summary
Modifier and TypeMethodDescriptionstatic 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.static voidcopyDirectoryRecursively(File src, File dest, boolean ignoreCVS) Copies a directory recursively into a destination directory.static voidcopyDirectoryRecursively(File src, File dest, boolean ignoreCVS, boolean doReplace) Copies a directory recursively into a destination directory.static TransformerCreates a default transformer using UTF-8 encoding and indenting.static DocumentCreates an empty name-space aware Document.static FilecreateOrUpdateGzip(File file) Helper method to generate a new Gzip file (if required) from a File.static StringcreateString(byte[] data) Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.static StringcreateString(byte[] data, int offset, int length) Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.static TransferablecreateTransferable(String string, Image image) Creates a transferable used by clipboard and drag-drop.static byte[]Decodes a byte array from Base64 format.static StringReplaces potential encoded URI special characters %20 ' ', %21 '!', %27 "'", %28 '(', %29 '), %7E '~', all other characters are left as is.static StringDecodes 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 StringdeepToString(Object[] o) Returns a string representation of the "deep contents" of the specified array.static booleandeleteDirectoryRecursive(Path path, Map<File, IOException> errorsMap) Deletes the directory recursively.static StringencodeAnyPath(String path) Constructs an encoded version of the specified path string suitable for use in the construction of a URL.static StringencodeBase64(byte[] a) Encodes a byte array into Base64 format.static StringEncodes a byte array into Base64 format.static StringencodePath(String path) Constructs an encoded version of the specified path string suitable for use in the construction of a URL.static StringencodePath(String path, boolean flag) Constructs an encoded version of the specified path string suitable for use in the construction of a URL.static StringEncodes 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 Stringformat(LocaleInfo localeInfo, String string, Object... params) Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.static Stringformat(ILocaleString localeString, String string, Object... params) Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.static StringFormats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.static StringFormats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.static StringGets the current date.static StringformatDate(long timeInMillis) Formats theDateinstance to a string that is used by the dump methods in this class as well as other event logs.static StringFormats theDateinstance to a string that is used by the dump methods in this class as well as other event logs.static StringformatDate(Date date) Formats theDateinstance to a string that is used by the dump methods in this class as well as other event logs.static StringformatDurationMillis(long duration) Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.static StringformatDurationNanos(long nanoDuration) Formats a String from a duration in nanoseconds as h:mm:ss.mmm.nnn.nnn.static StringformatEnglishDuration(long duration) Formats a String from a duration in milliseconds to English text as e.g.static StringformatEnglishNanoDuration(long nanoDuration) Formats a String from a duration in milliseconds to English text as e.g.static StringformatInGroups(String text, int groupLength) Formats a text string in groups of characters with dashes in between.static byte[]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[]Helper function for non-initialized string-to-byte conversion using ISO 8859-1 character set.static FilegetCanonicalFile(File file) Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.static FilegetCanonicalFile(String fileName) Attempts to get the canonical file of a File, and if it fails, the absolute file is returned.static StringGets the text from the clipboard.static StringGets the current UTC date/time string according to RFC1123 date.static TransformerFactoryCreates the default transformer factory.static StringgetEnglishSize(long size) Gets a size as nn.m TB/GB/MB/KB or bytes.static StringExtracts only the valid characters from a String that can be used as a file name for all file systems.static StringgetFingerPrint(Certificate cert, String algorithm, boolean colonSeparator) Gets the fingerprint of a certificate using an algorithm, typically "SHA-1".static SecureRandomGets the secure random instance.static StringgetShortestDouble(double v) Formats a double in the shortest possible way (keeping 0.static StringAfter an exception, call this method to get the stack trace.static StringGets the date/time string according to RFC1123 date.static StringgetValidName(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 thesourcearray of the first occurrence of the specifiedsearchbyte 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(String email) Checks if a String is a valid email.static booleanisValidEmail(String email, boolean allowLocal, boolean allowTld) Checks if a String is a valid email.static booleanisValidURL(String url, 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 StringquoteStringWithSpaces(String string) Quotes a string if it contains spaces.static byte[]Reads all the bytes from an input stream.static byte[]readAllBytes(URL url) Reads all the bytes from a file specified as a URL.static intrelaxedSearchIndexOf(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 intrelaxedSearchIndexOf(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 intrelaxedSearchIndexOf(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 intrelaxedSearchIndexOf(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 PathrenameFileWithTimestamp(File file) Renames the file to "filename-timestamp.ext".static StringreplaceStringIgnoreCase(String original, String replace) Method to replace a string in another, regardless the case of the original string or the replace string.static StringreplaceStringIgnoreCase(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 booleansetClipboard(Image image) Sets the clipboard with an Image.static booleansetClipboard(String string) Sets the clipboard with a String.static booleansetClipboard(String string, 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 StringtoHex(byte[] ab) Converts to hexadecimal.static StringtoHex(byte[] ab, int offset, int len) Converts to hexadecimal.static StringtoSignedHex(int value, int digitCount) Converts to signed hexadecimal String as 0x1234 or -0x567898.static StringtoSignedHex(long value, int digitCount) Converts to signed hexadecimal String as 0x1234 or -0x567898.static StringCracks the "Object" using toString, or special handling if it's an array or throwable.static StringtoUnsignedHex(int value, int digitCount) Converts to unsigned hexadecimal String as 0x1234 or -0x567898.static StringtoUnsignedHex(long value, int length) Converts to unsigned hexadecimal String as 0x1234 or -0x567898.static StringunquotedStringWithSpaces(String string) Gets an unquoted string if it contains double-quotes around it and it contains spaces.
Field Details
UTF8
The UTF-8 Character set for String or stream encodings.COLLATOR
The collator for the default system locale.HEXES
The hexadecimal characters in upper case.- See Also:
monthNames
The month names.formatCurlyPattern
RegEx for formatting parameters as{},{param_index}.{[argument_index]}lastUsedFS
Constructor Details
Utilities
public Utilities()
Method Details
getSecureRandom
Gets the secure random instance.- Returns:
- The secure random instance.
getShortestDouble
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
Gets the current date.- Returns:
- String formatted as "31 jan 2014 23:59:59.123".
formatDate
Formats theDateinstance 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
Formats theDateinstance 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
Formats theDateinstance 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
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
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
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
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
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
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
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
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
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
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
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
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
Creates the default transformer factory.- Returns:
- The default transformer factory, same instance always!
createDefaultTransformer
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
Creates an empty name-space aware Document.- Returns:
- The document.
createString
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
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
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:
trueif thesourcebyte array starting at the specifiedsourceIndexstarts with theprefixbyte array;falseotherwise. The result isfalseifsourceIndexis 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:
trueif thesourcebyte array starts with theprefixbyte array;falseotherwise.
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:
trueif thesourcebyte array ends with thesuffixbyte array;falseotherwise.
hashCode
public static int hashCode(byte[] source) Returns a hash code for the byte array. The hash code is computed as
using(source[0]&0xFF)*31^(n-1) + (source[1]&0xFF)*31^(n-2) + ... + (source[n-1]&0xFF)
intarithmetic, wheresource[i]is the ith byte of the array,nis 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 thesourcearray of the first occurrence of the specifiedsearchbyte array. The integer returned is the smallest value k such that:
isstartsWith(source,search,k)
true.- Parameters:
source- the source byte array.search- the byte array to locate in the source array.- Returns:
- the index where
searchfirst occurs insource; -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 valuekfor which:
If no such value of k exists, then -1 is returned.k >= Math.min(fromIndex,source.length) && this.startsWith(source,search,k)- 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
sourcebyte array of the first occurrence of the specifiedsearchbyte 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:
-1if 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 valuesource.length. The returned index is the largest value k such that
is true.startsWith(source,search,k)
- 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,
-1is 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:
If no such value of k exists, then -1 is returned.k <= Math.min(fromIndex,source.length) && startsWith(source,search,k)- 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
Gets the text from the clipboard.- Returns:
- null for failure or nothing present.
setClipboard
Sets the clipboard with a String.- Parameters:
string- The data to set in the clipboard.- Returns:
- true for success, false for failure.
setClipboard
Sets the clipboard with an Image.- Parameters:
image- The image to set in the clipboard.- Returns:
- true for success, false for failure.
setClipboard
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
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
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
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
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
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
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
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
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
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 IOExceptionDeletes 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 theerrorsMapisnull.
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 flagdoReplaceistrue, 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
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
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
sis null.
decodeURIComponent
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
sis null. - Throws:
IllegalArgumentException- If the implementation encounters illegal characters.
decodeSpecialURIChars
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 isnull.
encodePath
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
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.trueindicates path uses platform dependentFile.separatorChar.- Returns:
- The encoded path.
encodeAnyPath
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
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
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
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
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
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
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
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,nullto use default locale.- Returns:
- The index found or -1 for not found.
relaxedSearchIndexOf
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,nullto use default locale.- Returns:
- The index found or -1 for not found.
replaceStringIgnoreCase
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
originalstring and thereplacestring. Once thereplacestring is found (no matter the case), the search for the next occurrence will start at the next position where thereplacewas found. This may not seem to be very optimal, but is necessary in order to replace all words in theoriginalstring.- Parameters:
original- The original String.replace- The replace String.- Returns:
- The replaced string.
replaceStringIgnoreCase
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
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
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
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
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
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
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,
nullif not valid.
quoteStringWithSpaces
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
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
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
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 byILog.toString(Object), unless they are themselves arrays.If an element
eis an array of a primitive type, it is converted to a string as by invoking the appropriate overloading ofArrays.toString(e). If an elementeis 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 isnull.- Parameters:
o- The array whose string representation to return.- Returns:
- a string representation of
a.
format
Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.Parameters referenced by
{[param_index]}are convertedtoString()using{@link Utilities#toString()}enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using%swill not receive this "toString" conversion (unless they target the sameparam_index.The formatting string replaces
{}with%sand{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 orString.format(Locale, String, Object...).params- The parameters.- Returns:
- The formatted string.
- See Also:
format
Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.Parameters referenced by
{[param_index]}are convertedtoString()using{@link Utilities#toString()}enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using%swill not receive this "toString" conversion (unless they target the sameparam_index.The formatting string replaces
{}with%sand{param_index}with%param_index$s.- Parameters:
locale- The Locale, ornullto look it up for the current thread if needed.string- The string to format.params- The parameters.- Returns:
- The formatted string.
- See Also:
format
Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.Parameters referenced by
{[param_index]}are convertedtoString()using{@link Utilities#toString()}enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using%swill not receive this "toString" conversion (unless they target the sameparam_index.The formatting string replaces
{}with%sand{param_index}with%param_index$s.- Parameters:
localeString- The locale string instance, ornullfor current session.string- The string to format.params- The parameters.- Returns:
- The formatted string.
- See Also:
format
Formats a String using curly brackets{}as parameter or{param_index}parameter whereparam_indexis an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)method using parameters in the form of%[flags][width]conversionor%[argument_index$][flags][width]conversion.Parameters referenced by
{[param_index]}are convertedtoString()using{@link Utilities#toString()}enable e.g. deep-to-String of e.g. Exceptions, Arrays, etc.. Parameters references e.g. using%swill not receive this "toString" conversion (unless they target the sameparam_index.The formatting string replaces
{}with%sand{param_index}with%param_index$s.- Parameters:
localeInfo- The Locale information, ornullto look it up from the current thread if needed.string- The string to format.params- The parameters, ornullfor none.- Returns:
- The formatted string.
- See Also: