Class Utilities
- java.lang.Object
- com.iizix.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 Type Field Description static java.text.Collator
COLLATOR
The collator for the default system locale.static java.util.regex.Pattern
formatCurlyPattern
RegEx for formatting parameters as{}
,{param_index}
.static java.lang.String
HEXES
The hexadecimal characters in upper case.static java.lang.String
lastUsedFS
static java.lang.String[]
monthNames
The month names.static java.nio.charset.Charset
UTF8
The UTF-8 Character set for String or stream encodings.
Constructor Summary
Constructors Constructor Description Utilities()
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static void
copyDirectoryRecursively(java.io.File src, java.io.File dest, boolean ignoreSVN)
Copies a directory recursively into a destination directory.static javax.xml.transform.Transformer
createDefaultTransformer()
Creates a default transformer using UTF-8 encoding and indenting.static org.w3c.dom.Document
createDocument()
Creates an empty name-space aware Document.static java.io.File
createOrUpdateGzip(java.io.File file)
Helper method to generate a new Gzip file (if required) from a File.static java.lang.String
createString(byte[] data)
Helper function for non-initialized byte-to-string conversion using ISO 8859-1 character set.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.static java.awt.datatransfer.Transferable
createTransferable(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.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.static java.lang.String
deepToString(java.lang.Object[] o)
Returns a string representation of the "deep contents" of the specified array.static boolean
deleteDirectoryRecursive(java.nio.file.Path path, java.util.Map<java.io.File,java.io.IOException> errorsMap)
Deletes the directory recursively.static java.lang.String
encodeBase64(byte[] a)
Encodes a byte array into Base64 format.static java.lang.String
encodeBase64(java.lang.String a)
Encodes a byte array into Base64 format.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.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.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.static boolean
endsWith(byte[] source, byte[] suffix)
Tests if the source byte array ends with the specified suffix byte array.static java.lang.String
format(LocaleInfo localeInfo, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)
method using parameters in the form of%[flags][width]conversion
or%[argument_index$][flags][width]conversion
.static java.lang.String
format(ILocaleString localeString, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)
method using parameters in the form of%[flags][width]conversion
or%[argument_index$][flags][width]conversion
.static java.lang.String
format(java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)
method using parameters in the form of%[flags][width]conversion
or%[argument_index$][flags][width]conversion
.static java.lang.String
format(java.util.Locale locale, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.format(Locale, String, Object...)
method using parameters in the form of%[flags][width]conversion
or%[argument_index$][flags][width]conversion
.static java.lang.String
formatCurrentDate()
Gets the current date.static java.lang.String
formatDate(long timeInMillis)
Formats theDate
instance to a string that is used by the dump methods in this class as well as other event logs.static java.lang.String
formatDate(java.util.Calendar c)
Formats theDate
instance to a string that is used by the dump methods in this class as well as other event logs.static java.lang.String
formatDate(java.util.Date date)
Formats theDate
instance to a string that is used by the dump methods in this class as well as other event logs.static java.lang.String
formatDurationMillis(long duration)
Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.static java.lang.String
formatEnglishDuration(long duration)
Formats a String from a duration in milliseconds to English text as e.g.static java.lang.String
formatInGroups(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 void
fullGC()
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.File
getCanonicalFile(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.File
getCanonicalFile(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.String
getClipboardString()
Gets the text from the clipboard.static java.lang.String
getCurrentUTC()
Gets the current UTC date/time string according to RFC1123 date.static javax.xml.transform.TransformerFactory
getDefaultTransformerFactory()
Creates the default transformer factory.static java.lang.String
getEnglishSize(long size)
Gets a size as nn.m TB/GB/MB/KB or bytes.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.static java.lang.String
getFingerPrint(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.SecureRandom
getSecureRandom()
Gets the secure random instance.static java.lang.String
getShortestDouble(double v)
Formats a double in the shortest possible way (keeping 0.static java.lang.String
getStackTrace(java.lang.Throwable e)
After an exception, call this method to get the stack trace.static java.lang.String
getUTC(java.util.Date date)
Gets the date/time string according to RFC1123 date.static java.lang.String
getValidName(java.lang.String name)
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 thesource
array of the first occurrence of the specifiedsearch
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
isValidEmail(java.lang.String email)
Checks if a String is a valid email.static boolean
isValidEmail(java.lang.String email, boolean allowLocal, boolean allowTld)
Checks if a String is a valid email.static boolean
isValidURL(java.lang.String url, java.lang.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 java.lang.String
quoteStringWithSpaces(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 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.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.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.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.static java.nio.file.Path
renameFileWithTimestamp(java.io.File file)
Renames the file to "filename-timestamp.ext".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.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.static boolean
setClipboard(java.awt.Image image)
Sets the clipboard with an Image.static boolean
setClipboard(java.lang.String string)
Sets the clipboard with a String.static boolean
setClipboard(java.lang.String string, java.awt.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 java.lang.String
toHex(byte[] ab)
Converts to hexadecimal.static java.lang.String
toHex(byte[] ab, int offset, int len)
Converts to hexadecimal.static java.lang.String
toSignedHex(int value, int digitCount)
Converts to signed hexadecimal String as 0x1234 or -0x567898.static java.lang.String
toSignedHex(long value, int digitCount)
Converts to signed hexadecimal String as 0x1234 or -0x567898.static java.lang.String
toString(java.lang.Object o)
Cracks the "Object" using toString, or special handling if it's an array or throwable.static java.lang.String
toUnsignedHex(int value, int digitCount)
Converts to unsigned hexadecimal String as 0x1234 or -0x567898.static java.lang.String
toUnsignedHex(long value, int length)
Converts to unsigned hexadecimal String as 0x1234 or -0x567898.static java.lang.String
unquotedStringWithSpaces(java.lang.String string)
Gets an unquoted string if it contains double-quotes around it and it contains spaces.
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
monthNames
public static final java.lang.String[] monthNames
The month names.
formatCurlyPattern
public static final java.util.regex.Pattern formatCurlyPattern
RegEx for formatting parameters as{}
,{param_index}
.{[argument_index]}
lastUsedFS
public static java.lang.String lastUsedFS
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 theDate
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 theDate
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 theDate
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 thesource
byte array starting at the specifiedsourceIndex
starts with theprefix
byte array;false
otherwise. The result isfalse
ifsourceIndex
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 thesource
byte array starts with theprefix
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 thesource
byte array ends with thesuffix
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
using(source[0]&0xFF)*31^(n-1) + (source[1]&0xFF)*31^(n-2) + ... + (source[n-1]&0xFF)
int
arithmetic, wheresource[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 thesource
array of the first occurrence of the specifiedsearch
byte 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
search
first 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 valuek
for 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
source
byte array of the first occurrence of the specifiedsearch
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 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,
-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:
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
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 theerrorsMap
isnull
.
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 dependentFile.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 thereplace
string. Once thereplace
string is found (no matter the case), the search for the next occurrence will start at the next position where thereplace
was found. This may not seem to be very optimal, but is necessary in order to replace all words in theoriginal
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.
toString
public static java.lang.String toString(java.lang.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 java.lang.String deepToString(java.lang.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 byILog.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 ofArrays.toString(e)
. If an elemente
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 isnull
.- Parameters:
o
- The array whose string representation to return.- Returns:
- a string representation of
a
.
format
public static java.lang.String format(java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.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 convertedtoString()
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 sameparam_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 orString.format(Locale, String, Object...)
.params
- The parameters.- Returns:
- The formatted string.
- See Also:
String.format(Locale, String, Object...)
format
public static java.lang.String format(java.util.Locale locale, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.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 convertedtoString()
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 sameparam_index
.The formatting string replaces
{}
with%s
and{param_index}
with%param_index$s.- Parameters:
locale
- The Locale, ornull
to look it up for the current thread if needed.string
- The string to format.params
- The parameters.- Returns:
- The formatted string.
- See Also:
String.format(Locale, String, Object...)
format
public static java.lang.String format(ILocaleString localeString, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.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 convertedtoString()
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 sameparam_index
.The formatting string replaces
{}
with%s
and{param_index}
with%param_index$s.- Parameters:
localeString
- The locale string instance, ornull
for current session.string
- The string to format.params
- The parameters.- Returns:
- The formatted string.
- See Also:
String.format(Locale, String, Object...)
format
public static java.lang.String format(LocaleInfo localeInfo, java.lang.String string, java.lang.Object... params)
Formats a String using curly brackets{}
as parameter or{param_index}
parameter whereparam_index
is an optional one-based index value, AND/OR the JavaString.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 convertedtoString()
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 sameparam_index
.The formatting string replaces
{}
with%s
and{param_index}
with%param_index$s.- Parameters:
localeInfo
- The Locale information, ornull
to look it up from the current thread if needed.string
- The string to format.params
- The parameters, ornull
for none.- Returns:
- The formatted string.
- See Also:
String.format(Locale, String, Object...)