public class Utilities extends Object
Modifier and Type | Field and Description |
---|---|
static String |
BAT_EXT
Batch file extension (".bat" for Windows, "" for the others).
|
static String |
EXE_EXT
Executable extension (".exe" for Windows, "" for the others).
|
static String |
HEXES
The hexadecimal characters in upper case.
|
static char[] |
HEXES_CA
The hexadecimal characters as a character array.
|
static boolean |
isLinux
Flag for Linux environment.
|
static boolean |
isMac
Flag for macOS environment.
|
static boolean |
isWindows
Flag for Windows environment.
|
static String |
LINE_SEPARATOR
The Line separator ("\r\n" for Windows, "\n" for Unix).
|
static String[] |
monthNames
The month names.
|
static Charset |
UTF8
The UTF-8 Character set for String or stream encodings.
|
Constructor and Description |
---|
Utilities() |
Modifier and Type | Method and Description |
---|---|
static void |
copyDirectoryRecursively(File src,
File dest,
boolean ignoreSVN)
Copies a directory recursively into a destination directory.
|
static Transformer |
createDefaultTransformer()
Creates a default transformer using UTF-8 encoding and indenting.
|
static Document |
createDocument()
Creates an empty name-space aware Document.
|
static String |
createString(byte[] data)
Helper function for non-initialized byte-to-string conversion
using ISO 8859-1 character set.
|
static String |
createString(byte[] data,
int offset,
int length)
Helper function for non-initialized byte-to-string conversion
using ISO 8859-1 character set.
|
static Transferable |
createTransferable(String string,
Image image)
Creates a transferable used by clipboard and drag-drop.
|
static byte[] |
decodeBase64(String s)
Decodes a byte array from Base64 format.
|
static boolean |
deleteDirectoryRecursive(Path path,
Map<File,IOException> errorsMap)
Deletes the directory recursively.
|
static String |
encodeBase64(byte[] a)
Encodes a byte array into Base64 format.
|
static String |
encodeBase64(String a)
Encodes a byte array into Base64 format.
|
static String |
encodePath(String path)
Constructs an encoded version of the specified path string suitable
for use in the construction of a URL.
|
static String |
encodePath(String path,
boolean flag)
Constructs an encoded version of the specified path string suitable
for use in the construction of a URL.
|
static String |
encodeURIComponent(String s)
Encodes a String as the JavaScript encodeURIComponent(string) would do as URIEncoder.encode(string,"UTF-8") does
not handle spaces and other characters correctly.
|
static boolean |
endsWith(byte[] source,
byte[] suffix)
Tests if the source byte array ends with the specified suffix byte array.
|
static String |
formatCurrentDate()
Gets the current date.
|
static String |
formatDate(Calendar c)
Formats the
Date instance to a string that is used
by the dump methods in this class as well as other event logs. |
static String |
formatDate(Date date)
Formats the
Date instance to a string that is used
by the dump methods in this class as well as other event logs. |
static String |
formatDate(long timeInMillis)
Formats the
Date instance to a string that is used
by the dump methods in this class as well as other event logs. |
static String |
formatDurationMillis(long duration)
Formats a String from a duration in milliseconds as hhhhh:mm:ss.mmm.
|
static String |
formatEnglishDuration(long duration)
Formats a String from a duration in milliseconds to English text as e.g.
|
static String |
formatInGroups(String text,
int groupLength)
Formats a text string in groups of characters with dashes in between.
|
static byte[] |
fromHex(String hexString)
Parses a String in hex (of even length) to a byte array.
|
static void |
fullGC()
Performs the full garbage collection in the current thread.
|
static byte[] |
getBytes(String data)
Helper function for non-initialized string-to-byte conversion
using ISO 8859-1 character set.
|
static File |
getCanonicalFile(File file)
Attempts to get the canonical file of a File, and if it fails,
the absolute file is returned.
|
static File |
getCanonicalFile(String fileName)
Attempts to get the canonical file of a File, and if it fails,
the absolute file is returned.
|
static String |
getClipboardString()
Gets the text from the clipboard.
|
static TransformerFactory |
getDefaultTransformerFactory()
Creates the default transformer factory.
|
static String |
getEnglishSize(long size)
Gets a size as nn.m TB/GB/MB/KB or bytes.
|
static String |
getFileSystemValidString(String in)
Extracts only the valid characters from a String that can be used as a file name for
all file systems.
|
static String |
getFingerPrint(Certificate cert,
String algorithm,
boolean colonSeparator)
Gets the fingerprint of a certificate using an algorithm, typically "SHA-1".
|
static SecureRandom |
getSecureRandom()
Gets the secure random instance.
|
static String |
getShortestDouble(double v)
Formats a double in the shortest possible way (keeping 0.
|
static String |
getStackTrace(Throwable e)
After an exception, call this method to get the stack trace.
|
static int |
hashCode(byte[] source)
Returns a hash code for the byte array.
|
static int |
indexOf(byte[] source,
byte[] search)
Returns the index within the
source array of the first occurrence of the
specified search byte array. |
static int |
indexOf(byte[] source,
byte[] search,
int fromIndex)
Returns the index within the source byte array of the first occurrence of the
specified search byte array, starting at the specified index.
|
static int |
indexOf(byte[] source,
int sourceOffset,
int sourceCount,
byte[] target,
int targetOffset,
int targetCount,
int fromIndex)
The source is the byte array being searched, and the target
is the byte array being searched for.
|
static boolean |
isValidEmail(String email)
Checks if a String is a valid email.
|
static boolean |
isValidEmail(String email,
boolean allowLocal,
boolean allowTld)
Checks if a String is a valid email.
|
static boolean |
isValidURL(String url,
String... schemes)
Validates an URL.
|
static int |
lastIndexOf(byte[] source,
byte[] search)
Returns the index within the source byte array of the rightmost occurrence
of the specified search byte array.
|
static int |
lastIndexOf(byte[] source,
byte[] search,
int fromIndex)
Returns the index within the source byte array of the last occurrence of the
specified search byte array, searching backward starting at the specified index.
|
static byte[] |
readAllBytes(InputStream in)
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 int |
relaxedSearchIndexOf(String original,
int start,
String search)
Utility method to search for a String in another, as relaxed as possible, typically used
when having a searching filter.
|
static int |
relaxedSearchIndexOf(String original,
int start,
String search,
Locale locale)
Utility method to search for a String in another, as relaxed as possible, typically used
when having a searching filter.
|
static int |
relaxedSearchIndexOf(String original,
String search)
Utility method to search for a String in another, as relaxed as possible, typically used
when having a searching filter.
|
static int |
relaxedSearchIndexOf(String original,
String search,
Locale locale)
Utility method to search for a String in another, as relaxed as possible, typically used
when having a searching filter.
|
static Path |
renameFileWithTimestamp(File file)
Renames the file to "filename-timestamp.ext".
|
static String |
replaceStringIgnoreCase(String original,
String replace)
Method to replace a string in another, regardless the case of the original string
or the replace string.
|
static String |
replaceStringIgnoreCase(String original,
String replace,
int start)
Method to replace a string in another, regardless the case of the original string
or the replace string.
|
static boolean |
setClipboard(Image image)
Sets the clipboard with an Image.
|
static boolean |
setClipboard(String string)
Sets the clipboard with a String.
|
static boolean |
setClipboard(String string,
Image image)
Sets the clipboard with a String and an Image.
|
static boolean |
startsWith(byte[] source,
byte[] prefix)
Tests if the source byte array starts with the specified prefix byte array.
|
static boolean |
startsWith(byte[] source,
byte[] prefix,
int sourceIndex)
Tests if the source sub-byte array of a byte array beginning at the
specified source index starts with the specified prefix.
|
static String |
toHex(byte[] ab)
Converts to hexadecimal.
|
static String |
toHex(byte[] ab,
int offset,
int len)
Converts to hexadecimal.
|
public static final Charset UTF8
public static final String HEXES
public static final char[] HEXES_CA
public static final String LINE_SEPARATOR
public static final String[] monthNames
public static final boolean isWindows
public static final boolean isMac
public static final boolean isLinux
public static final String EXE_EXT
public static final String BAT_EXT
public static SecureRandom getSecureRandom()
public static String getShortestDouble(double v)
v
- The double value.public static String formatCurrentDate()
public static String formatDate(long timeInMillis)
Date
instance to a string that is used
by the dump methods in this class as well as other event logs.timeInMillis
- Time in milliseconds since the epoch.public static String formatDate(Date date)
Date
instance to a string that is used
by the dump methods in this class as well as other event logs.date
- The date to format.public static String formatDate(Calendar c)
Date
instance to a string that is used
by the dump methods in this class as well as other event logs.c
- The calendar to format.public static String toHex(byte[] ab)
ab
- Array of bytes to convert to a hexadecimal string of twice the size.public static String toHex(byte[] ab, int offset, int len)
ab
- Array of bytes to convert to a hexadecimal string of twice the size.offset
- Offset in buffer.len
- Length of data.public static byte[] fromHex(String hexString)
hexString
- A String in hex, characters 0-9 and a-f or A-F, even length required.public static String encodeBase64(String a)
a
- an array containing the data bytes to be encoded.public static String encodeBase64(byte[] a)
a
- an array containing the data bytes to be encoded.public static byte[] decodeBase64(String s)
s
- a Base64 String to be decoded.IllegalArgumentException
- if the input is not valid Base64 encoded data.public static String getStackTrace(Throwable e)
e
- The exception.public static TransformerFactory getDefaultTransformerFactory()
public static Transformer createDefaultTransformer() throws TransformerConfigurationException
TransformerConfigurationException
- When the transformer configuration is in error.public static Document createDocument()
public static String createString(byte[] data)
data
- The data to convert.public static String createString(byte[] data, int offset, int length)
data
- The data to convert.offset
- The offset in the data.length
- The length in the data.public static byte[] getBytes(String data)
data
- The String data.public static boolean startsWith(byte[] source, byte[] prefix, int sourceIndex)
source
- The source byte array.prefix
- The prefix byte array.sourceIndex
- Where to begin looking in the source array.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.public static boolean startsWith(byte[] source, byte[] prefix)
source
- The source byte array.prefix
- The prefix byte array.true
if the source
byte array starts
with the prefix
byte array; false
otherwise.public static boolean endsWith(byte[] source, byte[] suffix)
source
- The source byte array.suffix
- The suffix byte array.true
if the source
byte array ends
with the suffix
byte array; false
otherwise.public static int hashCode(byte[] source)
using(source[0]&0xFF)*31^(n-1) + (source[1]&0xFF)*31^(n-2) + ... + (source[n-1]&0xFF)
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()
.
source
- the byte array.public static int indexOf(byte[] source, byte[] search)
source
array of the first occurrence of the
specified search
byte array. The integer returned is the smallest value
k such that:
isstartsWith(source,search,k)
true
.source
- the source byte array.search
- the byte array to locate in the source array.search
first occurs in source
;
-1 if isn't present.public static int indexOf(byte[] source, byte[] search, int fromIndex)
If no such value of k exists, then -1 is returned.k >= Math.min(fromIndex,source.length) && this.startsWith(source,search,k)
source
- the source byte array.search
- the byte array to locate in the source array.fromIndex
- the index from which to start the search.source
byte array of
the first occurrence of the specified search
byte array,
starting at the specified index.public static int indexOf(byte[] source, int sourceOffset, int sourceCount, byte[] target, int targetOffset, int targetCount, int fromIndex)
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.-1
if not found; otherwise the first occurrence of
what is being searched for.public static int lastIndexOf(byte[] source, byte[] search)
source.length
.
The returned index is the largest value k such that
is true.startsWith(source,search,k)
source
- the bytes being searched.search
- the byte array to search for.-1
is returned.public static int lastIndexOf(byte[] source, byte[] search, int fromIndex)
If no such value of k exists, then -1 is returned.k <= Math.min(fromIndex,source.length) && startsWith(source,search,k)
source
- the bytes being searched.search
- the byte array to search for.fromIndex
- the index to start the search from.public static String getClipboardString()
public static boolean setClipboard(String string)
string
- The data to set in the clipboard.public static boolean setClipboard(Image image)
image
- The image to set in the clipboard.public static boolean setClipboard(String string, Image image)
string
- The data to set in the clipboard, null for none.image
- The image to set in the clipboard, null for none.public static Transferable createTransferable(String string, Image image)
string
- The data to set for the clipboard, null for none.image
- The image to set for the clipboard, null for none.public static String formatDurationMillis(long duration)
duration
- Duration in milliseconds.public static String formatEnglishDuration(long duration)
duration
- Duration in milliseconds.public static String getEnglishSize(long size)
size
- The positive size value.public static void fullGC()
public static Path renameFileWithTimestamp(File file) throws IOException
file
- The file.IOException
- For failures.public static File getCanonicalFile(String fileName)
fileName
- File or directory.public static File getCanonicalFile(File file)
file
- File or directory.public static boolean deleteDirectoryRecursive(Path path, Map<File,IOException> errorsMap) throws IOException
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).IOException
- If an error occurred while deleting the directories and files and the
errorsMap
is null
.public static void copyDirectoryRecursively(File src, File dest, boolean ignoreSVN) throws IOException
src
- The source directory to copy.dest
- The destination directory.ignoreSVN
- Flag to ignore .svn* files and directories.IOException
- For I/O errors.public static String getFileSystemValidString(String in)
Atom.RESERVED_CHARS
.in
- Input string.public static String encodeURIComponent(String s)
s
- The string to encode.s
is null.public static String encodePath(String path)
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.
path
- The path to encode.public static String encodePath(String path, boolean flag)
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.
path
- The path to encode.flag
- Indicates whether path uses platform dependent
File.separatorChar or not. true
indicates
path uses platform dependent File.separatorChar
.public static boolean isValidEmail(String email)
email
- The email to verify.public static boolean isValidEmail(String email, boolean allowLocal, boolean allowTld)
email
- The email to verify.allowLocal
- Should local addresses be considered valid?allowTld
- Should TLDs be allowed?public static boolean isValidURL(String url, String... schemes)
url
- URL to verify.schemes
- The schemes to accept, empty for all.public static String getFingerPrint(Certificate cert, String algorithm, boolean colonSeparator) throws CertificateEncodingException, NoSuchAlgorithmException
cert
- The certificate.algorithm
- The algorithm (normally "SHA-1").colonSeparator
- Place color separators between groups of 2 hexes.CertificateEncodingException
- If there is a problem in the certificate.NoSuchAlgorithmException
- If the algorithm doesn't exist.public static String formatInGroups(String text, int groupLength)
text
- The text string to format, MUST be be exactly divisible by groupLength.groupLength
- The length of each group in characters.IllegalArgumentException
- If the text string is not exactly divisible by groupLength.public static int relaxedSearchIndexOf(String original, String search)
The default locale is used, and the original string is searched from the beginning.
original
- The original string to search in.search
- The search string to find in the original string.public static int relaxedSearchIndexOf(String original, int start, String search)
The default locale is used.
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.public static int relaxedSearchIndexOf(String original, String search, Locale locale)
The original string is searched from the beginning.
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.public static int relaxedSearchIndexOf(String original, int start, String search, Locale locale)
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.public static String replaceStringIgnoreCase(String original, String replace)
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.
original
- The original String.replace
- The replace String.public static String replaceStringIgnoreCase(String original, String replace, int start)
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 "ß".
original
- The original String.replace
- The replace String.start
- The start position in the original string, 0 or negative or first position.public static byte[] readAllBytes(URL url) throws IOException
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.
url
- The URL of the file.IOException
- If an I/O error occurs reading from the stream.public static byte[] readAllBytes(InputStream in) throws IOException
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.
in
- The input stream.IOException
- If an I/O error occurs reading from the stream.iizi® is a registered trademark of Mindus SARL. © Copyright Mindus SARL, 2020. All rights reserved.