Package jadex.common
Class SUtil
java.lang.Object
jadex.common.SUtil
This class provides several useful static util methods.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic class
An subclass of print stream to allow accessing the underlying stream.static interface
Runnable for the noEx() method.static interface
Function for the noEx() method. -
Field Summary
FieldsModifier and TypeFieldDescriptionprotected static File
Application directory, current working dir under normal Java, special with Android.static final Charset
ASCII charset.static final String[]
Units for representing byte values.static final DecimalFormat
The byte formatter for one predecimal digit.static final DecimalFormat
The byte formatter for two predecimal digits.static final DecimalFormat
The byte formatter for three predecimal digits.static final int
Constant that indicates a conversion of all known characters.static final int
Constant that indicates a conversion of all known characters except invalid input: '&'.static final int
Constant that indicates a conversion of no characters.protected static AtomicLong
The counter for conversation ids.static boolean
Global Debug Flag for additional debug information on the consolestatic final long
Default timeout e.g.static final long
static final Class[]
An empty class array.static final Enumeration
An empty enumeration.static final Object[]
An empty class array.static final String[]
An empty string array.protected static ExecutorService
Shared executor service for all components.static final Random
Access to non-secure fast random source.Mapping from single characters to encoded version for displaying on xml-style interfaces.protected static final char[]
Lookup table used for unique strings.static final String[]
ISO8601 fallbacks assuming UTC.static final String[]
ISO8601 fallbacks with included timezone.static final Charset
ISO-8859-1 charset.static final String
Directory were jadex stores files generated during runtime, to be used for later runs.static final String
Line separator.static String[]
Cached for speed.The mime types.protected static List
<NetworkInterface> The cached network interfaces.protected static long
The time of the last caching of network interfaces.static final String
A Null value.protected static OutputStream
protected static final IResultCommand<ResourceInfo,
URLConnection>[] static final ThreadLocal
<DateFormat> Simple date format.static final ThreadLocal
<DateFormat> static final ThreadLocal
<DateFormat> static SecureRandom
Access to secure random source.protected static final String
Holds the single characters.static final Charset
UTF-8 charset. -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic void
addSystemErrListener
(IChangeListener listener) Add a listener to System.err.static void
addSystemOutListener
(IChangeListener listener) Add a listener to System.out.static boolean
arrayContains
(Object array, Object value) Check if an element is contained in an array.static final boolean
arrayEmptyOrNull
(Object array) Test if two arrays are content equal or both null.static boolean
arrayEquals
(Object array1, Object array2) Test if two arrays are content equal or both null.static int
Calculate a hash code for an array.static <T> List
<T> Transform an array to a vector.static <T> Set
<T> arrayToSet
(Object a) Transform an array to a vector.static String
arrayToString
(Object array) Get a string representation for an array.static byte[]
base16Decode
(String data) Decodes a Base16-encoded String and returns the data.static String
base16Encode
(byte[] data) Encodes a set of data as a Base16 String (hex).static int
bytesToInt
(byte[] buffer) Convert bytes to an integer.static int
bytesToInt
(byte[] buffer, int offset) Convert bytes to an integer.static long
bytesToLong
(byte[] buffer) Convert bytes to a long.static long
bytesToLong
(byte[] buffer, int offset) Convert bytes to a long.static short
bytesToShort
(byte[] buffer) Convert bytes to a short.static short
bytesToShort
(byte[] buffer, int offset) Convert bytes to a short.static String
bytesToString
(long bytes) Get bytes as human readable string.calculateCartesianProduct
(T[] names, E[] values) Calculate the cartesian product of parameters.static String
camelToSnakeCase
(String camel) Convert CamelCase to snake_case.static void
Attempt to close a Closeable (e.g.static void
Attempt to close a Socket (e.g.collectClasspathURLs
(ClassLoader baseloader) Get other contained (but not directly managed) urls from parent classloaders.protected static void
collectClasspathURLs
(ClassLoader classloader, Set<URL> set, Set<String> jarnames) Collect all URLs belonging to a class loader.static void
Collect all URLs as specified in a manifest.static int
Compares two strings, ignoring case.static byte[]
computeFileHash
(String filename) Compute a file hash.static byte[]
computeFileHash
(String filename, String algorithm) Compute a file hash.static boolean
Test if a string contains a digit.convertMapKeysToLowercase
(Map<String, T> map) Create a map copy with all keys in lowercase.static String
convertPathToPackage
(String path, URL[] urls) Find a package name from a path.static String
convertPathToRelative
(String absolute) Convert an absolute path to a relative path based on the current user directory.static final RuntimeException
Converts an exception to RuntimeException, returns original if already a RuntimeException.static String
convertURLToString
(URL url) Convert an URL to a local file name.static <T> T[]
copyArray
(T[] original) Copy an array.static void
Copy a file.static int
copyStream
(InputStream is, OutputStream os) Copy all data from input to output stream.static int
countOccurrences
(String string, char find) Count the occurrences of a char in a string.static <T> List
<T> createArrayList
(T[] values) Create an array list from values.static <K,
T> Map <K, T> createHashMap
(K[] keys, T[] values) Create a hash map from keys and values.static <T> Set
<T> createHashSet
(T[] values) Create a hash set from values.static String
createPlainRandomId
(String name, int length) Create a random id with only alphanumeric chars.static Pattern
createRegexFromGlob
(String glob) Create a regex from a normal bnf pattern.static String
Create a securely generated, globally unique id with low collision probability.static String
createUniqueId
(String name) Create a securely generated, globally unique id with low collision probability.static Object
Cut two arrays.static Date
dateFromIso8601
(String isostring) Attempts to create a date object in Java from an ISO 8601 string.static String
dateToIso8601
(Date date) Creates an ISO 8601-compliant string out of a java Date object.static boolean
deleteDirectory
(File dir) Delete a directory completely (including all subdirs and files).static final int
Generate a diffuse string hash.static void
Ensures SecureRandom use is nonblocking in all cases.static boolean
static String
escapeLineBreaks
(String unescapedstring) Escapes all line breaks similar to Java string literals.static String
escapeString
(String str) Escape a java string.static File
findDirForProject
(String project) Find dir for given project.static <K,
V> K findKeyForValue
(Map<K, V> map, V value) Helper to find first matching key (if any) for a value (identity check).static String
firstToUpperCase
(String str) Convert a string to the same string with first letter in upper case.static String
formatByteSize
(long bytes) Converts a number of bytes into a human-friendly binary prefix unit string (kiB, MiB, GiB, ...).static File
Gets the "application directory", normally the current working directory, except in Android.static int
getArrayDimension
(Object array) Get the array dimension.static String
getClassFileLocation
(Class<?> clazz) Get the file location for a class (either filename or jar url).getClasspathURLs
(ClassLoader classloader, boolean includebootpath) Get the current classpath as a list of URLsstatic String
getCodeSource
(String filename, String pck) Get the source code base using a packagename and a filename.static File
Get the home directory.static String
getDisplayName
(File file) Get the display name (e.g.static String
getDurationHMS
(long ms) Get a string representation for a duration.static String
Get the exception stacktrace.static final ExecutorService
Returns the shared executor for starting new threads.static File
Get the file from an URL.static File[]
Get the files of a directory.static String
Determine the location of the local computer using some GeoIP web service.static File
Get the home directory.static InetAddress
Get a IPV4 address of the local host.static InetAddress
Get a IPV4 address of the local host.static InetAddress
Get an address of the local host.static String
getJarName
(String filename) Get the name of a jar file without extension and version info.static String
Get the mac address.static String
getMacAddressAsString
(byte[] mac) Convert a mac address to a string.static String[]
Get the mac address.static InetAddress[]
Get the addresses to be used for transports.static List
<NetworkInterface> Get the network interfaces.static InetAddress
getNetworkIp
(InetAddress addr, short prefixlen) Get the network ip for an internet address and the prefix length.static List
<InetAddress> Get the network ips.static short
Get the network prefix length for IPV4 address 24=C, 16=B, 8=A classes.static OutputStream
Get an output stream that is automatically fed into the new System.in, i.e.static File
getParentDirectory
(File file) Get the parent directory.static String
Get the plural of a word in singular.static int
getPrefixLength
(File file) Get the prefix length of a file.static InputStream
getResource
(String name, ClassLoader classloader) Get an input stream for whatever provided.static InputStream
getResource0
(String name, ClassLoader classloader) Get an input stream for whatever provided.static ResourceInfo
getResourceInfo0
(String name, ClassLoader classloader) Get an input stream for whatever provided.static final SecureRandom
Gets the global secure random.static String
Get the singular of a word in plural.static String
Get the exception stack trace as string.static final String
getStackTraceString
(String topline, StackTraceElement[] trace) Converts a stack trace array to a printable string.static String[]
getStringArray
(String key, Properties props) Get a string array of properties that are separated by commas.static String
guessContentTypeByBytes
(byte[] data) Guess the mime type by the file name.static String
Guess the mime type by the file name.protected static void
hashDirectory
(String root, File dir, MessageDigest md) Get the hash code of a directory recursively.protected static void
hashStream
(InputStream is, MessageDigest md) static String
hex
(byte[] data) Convert a byte array to a string representation.static String
hex
(byte[] data, boolean uppercase) Convert a byte array to a string representation.static String
Convert a byte array to a string representation.static String
Convert a byte array to a string representation.static String
hex
(char ch) Convert char to hex vavlue.static int
indexOfFilename
(String url, List<String> urlstrings) Test if a file name is contained.static int
Find index of last upper case letter.static final String
Optimized version of String.intern() that actually uses String.intern() but provides faster lookups if the String is already interned.protected static void
internalMoveFile
(File source, File target) Moves a file to a target location.static void
intIntoBytes
(int val, byte[] buffer, int offset) Convert a long to bytes.static byte[]
intToBytes
(int val) Convert an integer to bytes.static boolean
isFloppyDrive
(File file) Check if a file represents a floppy.static boolean
Test if a call is running on the swing thread.static boolean
Test if the date is in the range.static boolean
isJavaSourceFilename
(String filename) Test if a file is a Java source file.static boolean
isUTF8
(byte[] bytes) Test if starts with UTF-8 BOM.static final boolean
static final boolean
Tests if the OS is Windows.static <T> Object[]
iteratorToArray
(Iterator<T> it, Class<T> clazz) Transform an iterator to an array.static <T> List
<T> iteratorToList
(Iterator<T> it) Transform an iterator to a list.static <T> List
<T> iteratorToList
(Iterator<T> it, List<T> ret) Transform an iterator to a list.static <T> T[]
joinArbitraryArrays
(Object[] as) Joins any arrays of (possibly) different type.static Object
joinArrays
(Object... arrays) Joins two arrays of the same type.static String
loadBinary
(String file) Load a binary file as base 64 string, e.g.static int
log2
(int num) Fast way to compute log2(x).static int
log2
(long num) Fast way to compute log2(x).static void
longIntoBytes
(long val, byte[] buffer) Convert a long to bytes.static void
longIntoBytes
(long val, byte[] buffer, int offset) Convert a long to bytes.static byte[]
longToBytes
(long val) Convert a long to bytes.static void
static String
makeConform
(String input) Convert an output to html/wml conform presentation.static String
makeConform
(String input, int flag) Convert an output to html/wml conform presentation.static String
makeEnglishConform
(String input) Convert an output readable in english.static byte[]
mergeData
(byte[]... data) Primitive encoding approach: Merges multiple byte arrays into a single one so it can be split later.static void
Moves a file to a target location.static void
Run code ignoring exceptions.static Object
Run code ignoring exceptions.static <T> Collection
<T> notNull
(Collection<T> coll) Helper method to allow iterating over possibly null collections.static <T> List
<T> Helper method to allow iterating over possibly null lists.static <K,
E> Map <K, E> Helper method to allow iterating over possibly null maps.static <T> Set
<T> Helper method to allow iterating over possibly null sets.static byte[]
Reads a file into memory (byte array).static String
Read a file to string.static String
readFile
(String filename, ClassLoader cl) Read a file to string.static void
readStream
(byte[] buf, int off, int len, InputStream is) Reads part of an input stream into a buffer.static void
readStream
(byte[] buf, int off, int len, InputStream is, long skip) Reads part of an input stream into a buffer.static void
readStream
(byte[] buf, InputStream is) Fills buffer from an input stream.static byte[]
Reads an input stream into memory (byte array).static String[]
Reads a (text) stream line-wise and returns lines as array.static String[]
readStreamLines
(InputStream is, Charset encoding) Reads a (text) stream line-wise and returns lines as array.static String
Remove BOM from UTF text.static String
Remove file extension.static void
removeSystemErrListener
(IChangeListener listener) Remove a listener from System.err.static void
removeSystemOutListener
(IChangeListener listener) Remove a listener from System.out.static final URL[]
removeSystemUrls
(URL[] urls) Removes the (.jar) URLs contained in directories associated with the JVM.static void
replace
(String source, StringBuffer dest, String old, String newstring) Parse a source string replacing occurrences and storing the result in the given string buffer.static String
Parse a source string replacing occurrences and returning the result.static String
replaceLast
(String string, String toreplace, String replacement) Replace the last occurrence of a substring.static final void
Re-throws a throwable as a RuntimeException.static void
shortIntoBytes
(int val, byte[] buffer, int offset) Convert a short into byte array.static byte[]
shortToBytes
(int val) Convert a short to bytes.static final void
sleep
(long millis) Sleep the current thread, ignore exceptions.static String
snakeToCamelCase
(String snake) Convert snake_case to CamelCase.static String[]
splitCommandline
(String line) Taken from ant.static List
<byte[]> splitData
(byte[] data) Primitive encoding approach: Splits a byte array that was encoded with mergeData().static List
<byte[]> splitData
(byte[] data, int offset, int length) Primitive encoding approach: Splits a byte array that was encoded with mergeData().static String
Strip tags (e.g.static Object
substractArrays
(Object a1, Object a2) First array minus second array.protected static void
static RuntimeException
Convert a throwable to an unchecked exception (i.e.static final File
Converts a file URL to a File, returns null if invalid.static final File
Converts a file URL to a File, returns null if invalid.static URI
Convert stringified URI (as used in transports for some weird reason) to URI.static URI
toURI
(String scheme, InetAddress address, int port) Convert a scheme, InetAdress and port to a valid URI or throw.static URI
Convert a URL to a URI but ignore exceptionsstatic URI
Convert a URL to a URI but ignore exceptionsstatic URL
Convert a file/string/url.static URL
Convert a URI to a URL but ignore exceptionsstatic URL[]
Convert a file/string/url array.static String
toUTF8
(byte[] bytes) Returns a UTF8 byte array as string.static String
unescapeLineBreaks
(String escapedstring) Unescapes all line breaks from strings similar to Java string literals.static void
Unzip a file into a specific dir.static File
Convert an URL to a file.static String
Wrap a text at a given line length.static String
Wrap a text at a given line length.static void
writeDirectory
(File dir, OutputStream out) Write a directory as jar to an output stream.protected static void
writeDirectory
(String prefix, File dir, ZipOutputStream zos, byte[] buf) Write a directory as jar to an output stream.static void
Write a string to a file.static void
Write a string to a file.
-
Field Details
-
DEBUG
public static boolean DEBUGGlobal Debug Flag for additional debug information on the console -
JADEXDIR
Directory were jadex stores files generated during runtime, to be used for later runs.- See Also:
-
LF
Line separator. -
BYTE_UNITS
Units for representing byte values. -
BYTEFORMATTER1
The byte formatter for one predecimal digit. -
BYTEFORMATTER2
The byte formatter for two predecimal digits. -
BYTEFORMATTER3
The byte formatter for three predecimal digits. -
CONVERT_ALL
public static final int CONVERT_ALLConstant that indicates a conversion of all known characters.- See Also:
-
CONVERT_ALL_EXCEPT_AMP
public static final int CONVERT_ALL_EXCEPT_AMPConstant that indicates a conversion of all known characters except invalid input: '&'.- See Also:
-
CONVERT_NONE
public static final int CONVERT_NONEConstant that indicates a conversion of no characters.- See Also:
-
NULL
A Null value.- See Also:
-
ASCII
ASCII charset. -
UTF8
UTF-8 charset. -
ISO8859_1
ISO-8859-1 charset. -
FAST_RANDOM
Access to non-secure fast random source. -
SECURE_RANDOM
Access to secure random source. -
MIMETYPES
The mime types. -
SDF
Simple date format. -
SDF2
-
SDF3
-
ISO8601UTCFALLBACKS
ISO8601 fallbacks assuming UTC. -
ISO8601ZONEDFALLBACKS
ISO8601 fallbacks with included timezone. -
executor
Shared executor service for all components. -
appdir
Application directory, current working dir under normal Java, special with Android. -
htmlwraps
Mapping from single characters to encoded version for displaying on xml-style interfaces. -
seps
Holds the single characters. -
EMPTY_ENUMERATION
An empty enumeration. -
EMPTY_STRING_ARRAY
An empty string array. -
EMPTY_CLASS_ARRAY
An empty class array. -
EMPTY_OBJECT_ARRAY
An empty class array. -
RESOURCEINFO_MAPPERS
-
DEFTIMEOUT
public static final long DEFTIMEOUTDefault timeout e.g. from environment. -
DEFTIMEOUT_DEFAULT
public static final long DEFTIMEOUT_DEFAULT- See Also:
-
convidcnt
The counter for conversation ids. -
OUT_FOR_SYSTEM_IN
-
NIS
The cached network interfaces. -
NISTIME
protected static long NISTIMEThe time of the last caching of network interfaces. -
macs
Cached for speed. -
ID_CHARS
protected static final char[] ID_CHARSLookup table used for unique strings.
-
-
Constructor Details
-
SUtil
public SUtil()
-
-
Method Details
-
isVirtualExecutor
public static final boolean isVirtualExecutor() -
getExecutor
Returns the shared executor for starting new threads. Supports virtual threads if available.- Returns:
- A shared executor.
-
getSecureRandom
Gets the global secure random.- Returns:
- The secure random.
-
getStringArray
Get a string array of properties that are separated by commas.- Parameters:
key
- The key.props
- The properties.- Returns:
- The strings.
-
joinArrays
Joins two arrays of the same type. Creates a new array containing the values of the first array followed by the values of the second.- Parameters:
a1
- The first array.a2
- The second array.- Returns:
- The joined array.
-
joinArbitraryArrays
Joins any arrays of (possibly) different type. todo: Does not support basic types yet. Problem basic type array and object arrays cannot be mapped (except they are mapped).- Parameters:
as
- The array of arrays to join..- Returns:
- The joined array.
-
cutArrays
Cut two arrays.- Parameters:
a1
- The first array.a2
- The second array.- Returns:
- The cutted array.
-
substractArrays
First array minus second array.- Parameters:
a1
- The first array.a2
- The second array.- Returns:
- The substracted array.
-
arrayToList
Transform an array to a vector.- Parameters:
a
- The array.- Returns:
- The vector for the array.
-
arrayToSet
Transform an array to a vector.- Parameters:
a
- The array.- Returns:
- The vector for the array.
-
iteratorToList
Transform an iterator to a list. -
iteratorToList
Transform an iterator to a list. -
iteratorToArray
Transform an iterator to an array. -
arrayContains
Check if an element is contained in an array.- Parameters:
array
- The array.value
- The value.
-
getArrayDimension
Get the array dimension.- Parameters:
array
- The array.- Returns:
- The number of dimensions.
-
equals
-
arrayEmptyOrNull
Test if two arrays are content equal or both null.- Parameters:
array1
- The first array.array2
- The second array.- Returns:
- True when the arrays are content equal.
-
arrayEquals
Test if two arrays are content equal or both null.- Parameters:
array1
- The first array.array2
- The second array.- Returns:
- True when the arrays are content equal.
-
arrayHashCode
Calculate a hash code for an array. -
arrayToString
Get a string representation for an array.- Parameters:
array
- The array.- Returns:
- formatted string.
-
convertMapKeysToLowercase
Create a map copy with all keys in lowercase.- Parameters:
map
- The original map.- Returns:
- The converted map.
-
getSingular
Get the singular of a word in plural. Does NOT find all correct singular.- Parameters:
s
- The plural word.- Returns:
- The singular of this word.
-
getPlural
Get the plural of a word in singular. Does NOT find all correct plurals.- Parameters:
s
- The word.- Returns:
- The plural of this word.
-
compareTo
Compares two strings, ignoring case.- Parameters:
a
- The first string.b
- The second string.- Returns:
- ainvalid input: '<'b => invalid input: '<'0
-
isInRange
Test if the date is in the range. Start or end may null and will so not be checked.- Parameters:
date
- The date.start
- The start.end
- The end.- Returns:
- True, if date is in range.
-
removeExtension
Remove file extension.- Parameters:
fn
- The filename..- Returns:
- filename without extension.
-
wrapText
Wrap a text at a given line length. Doesn't to word wrap, just inserts linebreaks every nth character. If the string already contains linebreaks, these are handled properly (extra linebreaks will only be inserted when needed).- Parameters:
text
- The text to wrap.
-
wrapText
Wrap a text at a given line length. Doesn't to word wrap, just inserts linebreaks every nth character. If the string already contains linebreaks, these are handled properly (extra linebreaks will only be inserted when needed).- Parameters:
text
- The text to wrap.wrap
- The column width.
-
makeConform
Convert an output to html/wml conform presentation.- Parameters:
input
- The input string.- Returns:
- The converted output string.
-
makeConform
Convert an output to html/wml conform presentation.- Parameters:
input
- The input string.flag
- CONVERT_ALL, CONVERT_NONE, CONVERT_ALL_EXCEPT_AMP;- Returns:
- The converted output string.
-
stripTags
Strip tags (e.g. html) from a string, leaving only the text content. -
makeEnglishConform
Convert an output readable in english. Therefore remove all äs, ös, üs etc.- Parameters:
input
- The input string.- Returns:
- The converted output string.
-
camelToSnakeCase
Convert CamelCase to snake_case. -
snakeToCamelCase
Convert snake_case to CamelCase. -
replace
Parse a source string replacing occurrences and storing the result in the given string buffer. This is a fast alternative to String.replaceAll(), because it does not use regular expressions.- Parameters:
source
- The source string.dest
- The destination string buffer.old
- The string to replace.newstring
- The string to use as replacement.
-
replace
Parse a source string replacing occurrences and returning the result. This is a fast alternative to String.replaceAll(), because it does not use regular expressions.- Parameters:
source
- The source string.old
- The string to replace.newstring
- The string to use as replacement.
-
getResource
Get an input stream for whatever provided. 1. It is tried to load the resource as file. 2. It is tried to load the resource via the ClassLoader. 3. It is tried to load the resource as URL.- Parameters:
name
- The resource description.- Returns:
- The input stream for the resource.
- Throws:
IOException
- when the resource was not found.
-
getResource0
Get an input stream for whatever provided. 1. It is tried to load the resource as file. 2. It is tried to load the resource via the ClassLoader. 3. It is tried to load the resource as URL.- Parameters:
name
- The resource description.- Returns:
- The input stream for the resource or null when the resource was not found.
-
getResourceInfo0
Get an input stream for whatever provided. 1. It is tried to load the resource as file. 2. It is tried to load the resource via the ClassLoader. 3. It is tried to load the resource as URL.- Parameters:
name
- The resource description.- Returns:
- The info object for the resource or null when the resource was not found.
-
copyStream
Copy all data from input to output stream. -
getDurationHMS
Get a string representation for a duration.- Parameters:
ms
- The duration in ms.- Returns:
- The string representation.
-
convertPathToPackage
Find a package name from a path. Searches the most specific classpath and uses the rest of the pathname as package name.- Parameters:
path
- The directory.- Returns:
- The package.
-
getClasspathURLs
Get the current classpath as a list of URLs -
collectClasspathURLs
Get other contained (but not directly managed) urls from parent classloaders.- Returns:
- The set of urls.
-
collectClasspathURLs
protected static void collectClasspathURLs(ClassLoader classloader, Set<URL> set, Set<String> jarnames) Collect all URLs belonging to a class loader. -
getJarName
Get the name of a jar file without extension and version info. -
collectManifestURLs
Collect all URLs as specified in a manifest. -
calculateCartesianProduct
Calculate the cartesian product of parameters. Example: names = {"a", "b"}, values = {{"1", "2"}, {"3", "4"}} result = {{"a"="1", "b"="3"}, {"a"="2", "b"="3"}, {"a"="1", "b"="4"}, {"a=2", b="4"}}- Parameters:
names
- The names.values
- The values (must be some form of collection, i.e. array, list, iterator etc.)
-
isJavaSourceFilename
Test if a file is a Java source file.- Parameters:
filename
- The filename.- Returns:
- True, if it is a Java source file.
-
createHashMap
Create a hash map from keys and values.- Parameters:
keys
- The keys.values
- The values.- Returns:
- The map.
-
createHashSet
Create a hash set from values.- Parameters:
values
- The values.- Returns:
- The map.
-
createArrayList
Create an array list from values.- Parameters:
values
- The values.- Returns:
- The map.
-
createUniqueId
Create a securely generated, globally unique id with low collision probability.- Returns:
- The id.
-
createUniqueId
Create a securely generated, globally unique id with low collision probability.- Parameters:
name
- Name to include in the ID.- Returns:
- The id.
-
createPlainRandomId
Create a random id with only alphanumeric chars.- Returns:
- The id.
-
testIntByteConversion
protected static void testIntByteConversion() -
convertPathToRelative
Convert an absolute path to a relative path based on the current user directory. -
toURLs
Convert a file/string/url array.- Parameters:
urls
- The url strings.- Returns:
- The urls.
-
toURL
Convert a file/string/url. -
toURL0
Convert a URI to a URL but ignore exceptions -
toURI0
Convert a URL to a URI but ignore exceptions -
toURI
Convert a URL to a URI but ignore exceptions -
toURI
Convert a scheme, InetAdress and port to a valid URI or throw.- Parameters:
scheme
-address
-port
-- Returns:
- URI
-
toURI
Convert stringified URI (as used in transports for some weird reason) to URI.- Parameters:
transporturi
- Transport-style URI (tcp-mtp://hostpart:port or tcp-mtp://[h:o:s:t%scope]:port for ipv6)- Returns:
- URI
-
toFile
Converts a file URL to a File, returns null if invalid.- Parameters:
url
- The URL.- Returns:
- File or null if invalid.
-
toFile0
Converts a file URL to a File, returns null if invalid.- Parameters:
url
- The URL.- Returns:
- File or null if invalid.
-
sleep
public static final void sleep(long millis) Sleep the current thread, ignore exceptions.- Parameters:
millis
- Time to sleep in milliseconds
-
convertToRuntimeException
Converts an exception to RuntimeException, returns original if already a RuntimeException.- Parameters:
e
- The throwable to be returned as RuntimeException- Returns:
- RuntimeException.
-
rethrowAsUnchecked
Re-throws a throwable as a RuntimeException. If the throwable is already a RuntimeException, the exception itself is thrown, otherwise it is wrapped.- Parameters:
e
- The throwable to be thrown as RuntimeException
-
main
-
formatByteSize
Converts a number of bytes into a human-friendly binary prefix unit string (kiB, MiB, GiB, ...).- Parameters:
bytes
- Number of bytes.
-
bytesToShort
public static short bytesToShort(byte[] buffer) Convert bytes to a short. -
bytesToShort
public static short bytesToShort(byte[] buffer, int offset) Convert bytes to a short. -
shortToBytes
public static byte[] shortToBytes(int val) Convert a short to bytes. -
shortIntoBytes
public static void shortIntoBytes(int val, byte[] buffer, int offset) Convert a short into byte array. -
bytesToInt
public static int bytesToInt(byte[] buffer) Convert bytes to an integer. -
bytesToInt
public static int bytesToInt(byte[] buffer, int offset) Convert bytes to an integer. -
intToBytes
public static byte[] intToBytes(int val) Convert an integer to bytes. -
intIntoBytes
public static void intIntoBytes(int val, byte[] buffer, int offset) Convert a long to bytes. -
bytesToLong
public static long bytesToLong(byte[] buffer) Convert bytes to a long. -
bytesToLong
public static long bytesToLong(byte[] buffer, int offset) Convert bytes to a long. -
longToBytes
public static byte[] longToBytes(long val) Convert a long to bytes. -
longIntoBytes
public static void longIntoBytes(long val, byte[] buffer) Convert a long to bytes. -
longIntoBytes
public static void longIntoBytes(long val, byte[] buffer, int offset) Convert a long to bytes. -
getNetworkIp
Get the network ip for an internet address and the prefix length. Example: ip: 134.100.33.22 / prefixlen: 24 (c class) -> 134.100.33.0- Parameters:
addr
- The internet address.prefixlen
- The prefix length.- Returns:
- The net address.
-
bytesToString
Get bytes as human readable string. -
getClassFileLocation
Get the file location for a class (either filename or jar url). -
convertURLToString
Convert an URL to a local file name.- Parameters:
url
- The url.- Returns:
- The absolute path to the url resource.
-
indexOfFilename
Test if a file name is contained. -
urlToFile
Convert an URL to a file.- Returns:
- null, if the URL is neither 'file:' nor 'jar:file:' URL and no path point to an existing file.
-
intern
Optimized version of String.intern() that actually uses String.intern() but provides faster lookups if the String is already interned.- Parameters:
string
- The String being interned.- Returns:
- The interned String.
-
removeSystemUrls
Removes the (.jar) URLs contained in directories associated with the JVM.- Parameters:
urls
- The input URLs.- Returns:
- URLs without the system path URLs.
-
dateToIso8601
Creates an ISO 8601-compliant string out of a java Date object.- Parameters:
date
- The date object.- Returns:
- ISO 8601-compliant string.
-
dateFromIso8601
Attempts to create a date object in Java from an ISO 8601 string.- Parameters:
isostring
- The ISO string, must contain enough data for the date object.- Returns:
- Date object.
-
addSystemOutListener
Add a listener to System.out. -
removeSystemOutListener
Remove a listener from System.out. -
addSystemErrListener
Add a listener to System.err. -
removeSystemErrListener
Remove a listener from System.err. -
getOutForSystemIn
Get an output stream that is automatically fed into the new System.in, i.e. this method replaces System.in and delivers an output stream to which can be written. Note that writing to the output stream may block when no one reads from system in (default buffer size is 1024 characters).- Throws:
IOException
-
getInet4Address
Get a IPV4 address of the local host. Ignores loopback address and V6 addresses.- Returns:
- First found IPV4 address.
-
getInet6Address
Get a IPV4 address of the local host. Ignores loopback address and V4 addresses.- Returns:
- First found IPV4 address.
-
getInetAddress
Get an address of the local host. Tries to get a IPV4 address and if not available tries to get a IPV6 address.- Returns:
- First found IPV4 or IPV6 address.
-
getNetworkPrefixLength
Get the network prefix length for IPV4 address 24=C, 16=B, 8=A classes. Returns -1 in case of V6 address.- Parameters:
iadr
- The address.- Returns:
- The length of the prefix.
-
getNetworkIps
Get the network ips. -
copyArray
public static <T> T[] copyArray(T[] original) Copy an array. -
getCodeSource
Get the source code base using a packagename and a filename. Looks at the filename and subtracts the package name.- Parameters:
filename
- The filename.pck
- The package name.- Returns:
- The source base.
-
countOccurrences
Count the occurrences of a char in a string.- Parameters:
string
- The string.find
- The char to find.- Returns:
- The number of occurrences.
-
getNetworkInterfaces
Get the network interfaces. The result is cached for a short time period to speed things up.- Throws:
SocketException
-
getNetworkAddresses
Get the addresses to be used for transports.- Throws:
SocketException
-
unzip
Unzip a file into a specific dir.- Parameters:
zip
- The zip file.dir
- The target dir.
-
deleteDirectory
Delete a directory completely (including all subdirs and files).- Parameters:
dir
- The dir to delete.- Returns:
- True, if was successfully deleted.
-
getHomeDirectory
Get the home directory. -
getDefaultDirectory
Get the home directory. -
getParentDirectory
Get the parent directory. -
getFiles
Get the files of a directory. -
getPrefixLength
Get the prefix length of a file. -
isFloppyDrive
Check if a file represents a floppy. Returns false on android. -
getDisplayName
Get the display name (e.g. of a system drive). Returns null on android. -
isGuiThread
public static boolean isGuiThread()Test if a call is running on the swing thread. -
escapeString
Escape a java string.- Parameters:
str
- The string to escape.- Returns:
- The escaped string.
-
mergeData
public static byte[] mergeData(byte[]... data) Primitive encoding approach: Merges multiple byte arrays into a single one so it can be split later.- Parameters:
data
- The input data.- Returns:
- A merged byte array.
-
splitData
Primitive encoding approach: Splits a byte array that was encoded with mergeData().- Parameters:
data
- The input data.- Returns:
- A list of byte arrays representing the original set.
-
splitData
Primitive encoding approach: Splits a byte array that was encoded with mergeData().- Parameters:
data
- The input data.offset
- Offset where the data is located.length
- Length of the data, rest of data used if length invalid input: '<' 0.- Returns:
- A list of byte arrays representing the original set.
-
hex
Convert char to hex vavlue. -
hex
Convert a byte array to a string representation. -
hex
Convert a byte array to a string representation. -
hex
Convert a byte array to a string representation. -
hex
Convert a byte array to a string representation. -
base16Encode
Encodes a set of data as a Base16 String (hex).- Parameters:
data
- The data.- Returns:
- Base16-encoded String.
-
base16Decode
Decodes a Base16-encoded String and returns the data.- Parameters:
data
- The encoded data.- Returns:
- The decoded data.
-
escapeLineBreaks
Escapes all line breaks similar to Java string literals.- Parameters:
unescapedstring
- Unescaped input string.- Returns:
- Escaped string.
-
unescapeLineBreaks
Unescapes all line breaks from strings similar to Java string literals.- Parameters:
escapedstring
- Escaped input string.- Returns:
- Unescaped string.
-
splitCommandline
Taken from ant. Split a command line.- Parameters:
line
- The command line to process.- Returns:
- The command line broken into strings. An empty or null toProcess parameter results in a zero sized array.
-
getFile
Get the file from an URL.- Parameters:
url
- The file URL.- Returns:
- The file.
-
copyFile
Copy a file.- Parameters:
source
- The source file.target
- The target file or directory (will be deleted first).- Throws:
IOException
-
moveFile
Moves a file to a target location.- Parameters:
source
- The source file.target
- The target file location (will be deleted first, if it exists).- Throws:
IOException
-
internalMoveFile
Moves a file to a target location.- Parameters:
source
- The source file.target
- The target file location (will be deleted first, if it exists).- Throws:
IOException
-
readFile
Reads a file into memory (byte array). Note: This only works for files smaller than 2GiB.- Parameters:
file
- The file.- Returns:
- Contents of the file.
- Throws:
IOException
- Exception on IO errors.
-
readStream
Reads an input stream into memory (byte array). Note: This only works for files smaller than 2GiB.- Parameters:
is
- The InputStream.- Returns:
- Contents of the file.
- Throws:
IOException
- Exception on IO errors.
-
readStream
Fills buffer from an input stream. Note: This only works for sizes smaller than 2GiB.- Parameters:
buf
- The buffer.is
- The InputStream.
-
readStream
Reads part of an input stream into a buffer. Note: This only works for sizes smaller than 2GiB.- Parameters:
buf
- The buffer.off
- Offset for writing into the buffer.len
- Number of bytes to read from stream, set to -1 to fill the rest of the buffer.is
- The InputStream.
-
readStream
Reads part of an input stream into a buffer. Note: This only works for sizes smaller than 2GiB.- Parameters:
buf
- The buffer.off
- Offset for writing into the buffer.len
- Number of bytes to read from stream, set to -1 to fill the rest of the buffer.is
- The InputStream.skip
- Skip this number of bytes from the stream before reading, skipinvalid input: '<'=0 for no skip.
-
readStreamLines
Reads a (text) stream line-wise and returns lines as array.- Parameters:
is
- InputStream.- Returns:
- Array of lines.
-
readStreamLines
Reads a (text) stream line-wise and returns lines as array.- Parameters:
is
- InputStream.encoding
- Character encoding, defaults to UTF8 if null.- Returns:
- Array of lines.
-
close
Attempt to close a Socket (e.g. on error recovery) ignoring any error. (compatibility for Java versions below 7 where Closeable exists but is not implemented by Socket because stupid)- Parameters:
socket
- The socket.
-
noEx
Run code ignoring exceptions.- Parameters:
r
- Expression whose exceptions are ignored.
-
noExRet
Run code ignoring exceptions.- Parameters:
r
- Expression whose exceptions are ignored.
-
close
Attempt to close a Closeable (e.g. on error recovery) ignoring any error.- Parameters:
closeable
- The closeable.
-
getStackTrace
Get the exception stack trace as string.- Parameters:
e
- The exception.- Returns:
- The string.
-
log2
public static int log2(int num) Fast way to compute log2(x).- Parameters:
num
- The number.- Returns:
- The log2(x).
-
log2
public static int log2(long num) Fast way to compute log2(x).- Parameters:
num
- The number.- Returns:
- The log2(x).
-
computeFileHash
Compute a file hash.- Parameters:
filename
- The filename.- Returns:
- The hash.
-
computeFileHash
Compute a file hash.- Parameters:
filename
- The filename.algorithm
- The hash algorithm.- Returns:
- The hash.
-
firstToUpperCase
Convert a string to the same string with first letter in upper case.- Parameters:
str
- The string.- Returns:
- The string with first letter in uppercase.
-
getMacAddress
Get the mac address.- Returns:
- The mac address.
-
getMacAddresses
Get the mac address.- Returns:
- The mac address.
-
createRegexFromGlob
Create a regex from a normal bnf pattern. -
readFile
Read a file to string.- Parameters:
filename
- The file name.- Returns:
- The string.
-
readFile
Read a file to string.- Parameters:
filename
- The file name.- Returns:
- The string.
-
writeFile
Write a string to a file.- Parameters:
val
- The string to write.filename
- The file name.
-
writeFile
Write a string to a file.- Parameters:
val
- The string to write.filename
- The file name.
-
getAppDir
Gets the "application directory", normally the current working directory, except in Android.- Returns:
- Application directory.
-
loadBinary
Load a binary file as base 64 string, e.g. for embedded html images. -
removeBOM
Remove BOM from UTF text.- Parameters:
text
- The text.- Returns:
- The corrected string.
-
isUTF8
public static boolean isUTF8(byte[] bytes) Test if starts with UTF-8 BOM.- Parameters:
bytes
- The text.- Returns:
- Bytes without BOM.
-
toUTF8
Returns a UTF8 byte array as string.- Parameters:
bytes
- The bytes.- Returns:
- The string.
-
getExceptionStacktrace
Get the exception stacktrace.- Parameters:
e
- The exception.- Returns:
- The exception stacktrace.
-
throwUnchecked
Convert a throwable to an unchecked exception (i.e. error or runtime exception). Also unpacks InvocationTargeteException and ErrorException.- Parameters:
t
- The throwable.- Returns:
- Dummy return value as exception will be thrown inside. Use as
throw SUtil.throwUnchecked(t);
to avoid compilation errors. - Throws:
Error
RuntimeException
-
guessContentTypeByFilename
Guess the mime type by the file name.- Parameters:
name
- The filename- Returns:
- The mime type.
-
guessContentTypeByBytes
Guess the mime type by the file name.- Parameters:
name
- The file content in bytes.- Returns:
- The mime type.
-
containsDigit
Test if a string contains a digit.- Parameters:
s
- The string.- Returns:
- True, if the string contains a digit.
-
hashDirectory
Get the hash code of a directory recursively.- Throws:
Exception
-
hashStream
- Throws:
Exception
-
writeDirectory
Write a directory as jar to an output stream. -
writeDirectory
protected static void writeDirectory(String prefix, File dir, ZipOutputStream zos, byte[] buf) throws Exception Write a directory as jar to an output stream.- Throws:
Exception
-
notNull
Helper method to allow iterating over possibly null lists. -
notNull
Helper method to allow iterating over possibly null collections. -
notNull
Helper method to allow iterating over possibly null sets. -
notNull
Helper method to allow iterating over possibly null maps. -
findKeyForValue
Helper to find first matching key (if any) for a value (identity check). -
getStackTraceString
Converts a stack trace array to a printable string.- Parameters:
topline
- The first line to be printed with info, if needed.trace
- The stack trace.- Returns:
- Printable string.
-
findDirForProject
Find dir for given project. This allows to run under different environments with different working paths (e.g. intellij by default uses WP jadex/ while gradle uses WP jadex/jadex-integration-test- Parameters:
project
-- Returns:
- File
-
diffuseStringHash
Generate a diffuse string hash.- Parameters:
s
- The string.- Returns:
- The hash.
-
inndexOfLastUpperCaseCharacter
Find index of last upper case letter.- Parameters:
str
- The string.- Returns:
- The index (or -1).
-
isWindows
public static final boolean isWindows()Tests if the OS is Windows.- Returns:
- True, if Windows.
-
replaceLast
Replace the last occurrence of a substring.- Parameters:
string
- The stringtoreplace
- The substring to replace.replacement
- The new substring- Returns:
- The new string.
-
getGeoIPLocation
Determine the location of the local computer using some GeoIP web service.- Returns:
- The location as [
][, ][ ] depending on what's available.
-
ensureNonblockingSecureRandom
public static void ensureNonblockingSecureRandom()Ensures SecureRandom use is nonblocking in all cases. Must be called before first new SecureRandom() use. Safe to call multiple times. Note: On certain systems like Linux, SecureRandom ends up using /dev/random as a entropy source for initialization. This has the severe disadvantage of blocking indefinitely once the entropy pool "runs out of entropy" (whatever that means). Calling this method prevents this undesirable behavior. -
getMacAddressAsString
Convert a mac address to a string.- Parameters:
mac
- The address.- Returns:
- The string.
-