Package jadex.commons

Class SUtil


  • public class SUtil
    extends java.lang.Object
    This class provides several useful static util methods.
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  SUtil.AccessiblePrintStream
      An subclass of print stream to allow accessing the underlying stream.
      static interface  SUtil.NoExRunnable
      Runnable for the noEx() method.
      static interface  SUtil.NoExSupplier
      Function for the noEx() method.
    • Field Summary

      Fields 
      Modifier and Type Field Description
      protected static java.io.File appdir
      Application directory, current working dir under normal Java, special with Android.
      static java.nio.charset.Charset ASCII
      ASCII charset.
      static java.lang.String[] BYTE_UNITS
      Units for representing byte values.
      static java.text.DecimalFormat BYTEFORMATTER1
      The byte formatter for one predecimal digit.
      static java.text.DecimalFormat BYTEFORMATTER2
      The byte formatter for two predecimal digits.
      static java.text.DecimalFormat BYTEFORMATTER3
      The byte formatter for three predecimal digits.
      static int CONVERT_ALL
      Constant that indicates a conversion of all known characters.
      static int CONVERT_ALL_EXCEPT_AMP
      Constant that indicates a conversion of all known characters except &.
      static int CONVERT_NONE
      Constant that indicates a conversion of no characters.
      protected static java.util.concurrent.atomic.AtomicLong convidcnt
      The counter for conversation ids.
      static long DEFTIMEOUT
      Default timeout e.g.
      static long DEFTIMEOUT_DEFAULT  
      static java.lang.Class[] EMPTY_CLASS_ARRAY
      An empty class array.
      static java.util.Enumeration EMPTY_ENUMERATION
      An empty enumeration.
      static java.lang.Object[] EMPTY_OBJECT_ARRAY
      An empty class array.
      static java.lang.String[] EMPTY_STRING_ARRAY
      An empty string array.
      static java.util.Random FAST_RANDOM
      Access to non-secure fast random source.
      protected static LRU<java.lang.String,​Tuple2<java.lang.Long,​java.lang.String>> HASHES
      LRU for hashes.
      protected static java.util.Map<java.lang.String,​java.lang.String> htmlwraps
      Mapping from single characters to encoded version for displaying on xml-style interfaces.
      protected static char[] ID_CHARS
      Lookup table used for unique strings.
      static java.lang.String[] ISO8601UTCFALLBACKS
      ISO8601 fallbacks assuming UTC.
      static java.lang.String[] ISO8601ZONEDFALLBACKS
      ISO8601 fallbacks with included timezone.
      static java.nio.charset.Charset ISO8859_1
      ISO-8859-1 charset.
      static java.lang.String JADEXDIR
      Directory were jadex stores files generated during runtime, to be used for later runs.
      protected static LRU<java.lang.String,​java.lang.Long> LASTMODS
      LRU for directory modification dates.
      static java.lang.String LF
      Line separator.
      static java.lang.String[] macs
      Cached for speed.
      protected static java.util.Map<java.lang.String,​java.lang.String> MIMETYPES
      The mime types.
      protected static java.util.List<java.net.NetworkInterface> NIS
      The cached network interfaces.
      protected static long NISTIME
      The time of the last caching of network interfaces.
      static java.lang.String NULL
      A Null value.
      protected static java.io.OutputStream OUT_FOR_SYSTEM_IN  
      protected static IResultCommand<ResourceInfo,​java.net.URLConnection>[] RESOURCEINFO_MAPPERS  
      static java.lang.ThreadLocal<java.text.DateFormat> SDF
      Simple date format.
      static java.lang.ThreadLocal<java.text.DateFormat> SDF2  
      static java.lang.ThreadLocal<java.text.DateFormat> SDF3  
      static java.security.SecureRandom SECURE_RANDOM
      Access to secure random source.
      protected static java.lang.String seps
      Holds the single characters.
      static java.nio.charset.Charset UTF8
      UTF-8 charset.
    • Constructor Summary

      Constructors 
      Constructor Description
      SUtil()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void addSystemErrListener​(IChangeListener listener)
      Add a listener to System.err.
      static void addSystemOutListener​(IChangeListener listener)
      Add a listener to System.out.
      static boolean arrayContains​(java.lang.Object array, java.lang.Object value)
      Check if an element is contained in an array.
      static boolean arrayEmptyOrNull​(java.lang.Object array)
      Test if two arrays are content equal or both null.
      static boolean arrayEquals​(java.lang.Object array1, java.lang.Object array2)
      Test if two arrays are content equal or both null.
      static int arrayHashCode​(java.lang.Object a)
      Calculate a hash code for an array.
      static <T> java.util.List<T> arrayToList​(java.lang.Object a)
      Transform an array to a vector.
      static <T> java.util.Set<T> arrayToSet​(java.lang.Object a)
      Transform an array to a vector.
      static java.lang.String arrayToString​(java.lang.Object array)
      Get a string representation for an array.
      static byte[] base16Decode​(java.lang.String data)
      Decodes a Base16-encoded String and returns the data.
      static java.lang.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 java.lang.String bytesToString​(long bytes)
      Get bytes as human readable string.
      static <T,​E>
      java.util.List<java.util.Map<T,​E>>
      calculateCartesianProduct​(T[] names, E[] values)
      Calculate the cartesian product of parameters.
      static java.lang.String camelToSnakeCase​(java.lang.String camel)
      Convert CamelCase to snake_case.
      static void close​(java.io.Closeable closeable)
      Attempt to close a Closeable (e.g.
      static void close​(java.net.Socket socket)
      Attempt to close a Socket (e.g.
      static java.util.Set<java.net.URL> collectClasspathURLs​(java.lang.ClassLoader baseloader)
      Get other contained (but not directly managed) urls from parent classloaders.
      protected static void collectClasspathURLs​(java.lang.ClassLoader classloader, java.util.Set<java.net.URL> set, java.util.Set<java.lang.String> jarnames)
      Collect all URLs belonging to a class loader.
      static void collectManifestURLs​(java.net.URL url, java.util.Set<java.net.URL> set, java.util.Set<java.lang.String> jarnames)
      Collect all URLs as specified in a manifest.
      static int compareTo​(java.lang.String a, java.lang.String b)
      Compares two strings, ignoring case.
      static byte[] computeFileHash​(java.lang.String filename)
      Compute a file hash.
      static byte[] computeFileHash​(java.lang.String filename, java.lang.String algorithm)
      Compute a file hash.
      static boolean containsDigit​(java.lang.String s)
      Test if a string contains a digit.
      static <T> java.util.Map<java.lang.String,​T> convertMapKeysToLowercase​(java.util.Map<java.lang.String,​T> map)
      Create a map copy with all keys in lowercase.
      static java.lang.String convertPathToPackage​(java.lang.String path, java.net.URL[] urls)
      Find a package name from a path.
      static java.lang.String convertPathToRelative​(java.lang.String absolute)
      Convert an absolute path to a relative path based on the current user directory.
      static java.lang.RuntimeException convertToRuntimeException​(java.lang.Throwable e)
      Converts an exception to RuntimeException, returns original if already a RuntimeException.
      static java.lang.String convertURLToString​(java.net.URL url)
      Convert an URL to a local file name.
      static <T> T[] copyArray​(T[] original)
      Copy an array.
      static void copyFile​(java.io.File source, java.io.File target)
      Copy a file.
      static int copyStream​(java.io.InputStream is, java.io.OutputStream os)
      Copy all data from input to output stream.
      static int countOccurrences​(java.lang.String string, char find)
      Count the occurrences of a char in a string.
      static <T> java.util.List<T> createArrayList​(T[] values)
      Create an array list from values.
      static <K,​T>
      java.util.Map<K,​T>
      createHashMap​(K[] keys, T[] values)
      Create a hash map from keys and values.
      static <T> java.util.Set<T> createHashSet​(T[] values)
      Create a hash set from values.
      static java.lang.String createPlainRandomId​(java.lang.String name, int length)
      Create a random id with only alphanumeric chars.
      static java.util.regex.Pattern createRegexFromGlob​(java.lang.String glob)
      Create a regex from a normal bnf pattern.
      static java.lang.String createUniqueId()
      Create a globally unique conversation id.
      static java.lang.String createUniqueId​(java.lang.String name)
      Create a globally unique conversation id.
      static java.lang.Object cutArrays​(java.lang.Object a1, java.lang.Object a2)
      Cut two arrays.
      static java.util.Date dateFromIso8601​(java.lang.String isostring)
      Attempts to create a date object in Java from an ISO 8601 string.
      static java.lang.String dateToIso8601​(java.util.Date date)
      Creates an ISO 8601-compliant string out of a java Date object.
      static boolean deleteDirectory​(java.io.File dir)
      Delete a directory completely (including all subdirs and files).
      static int diffuseStringHash​(java.lang.String s)
      Generate a diffuse string hash.
      static void ensureNonblockingSecureRandom()
      Ensures SecureRandom use is nonblocking in all cases.
      static boolean equals​(java.lang.Object val1, java.lang.Object val2)  
      static java.lang.String escapeLineBreaks​(java.lang.String unescapedstring)
      Escapes all line breaks similar to Java string literals.
      static java.lang.String escapeString​(java.lang.String str)
      Escape a java string.
      static java.io.File findDirForProject​(java.lang.String project)
      Find dir for given project.
      static <K,​V>
      K
      findKeyForValue​(java.util.Map<K,​V> map, V value)
      Helper to find first matching key (if any) for a value (identity check).
      static java.io.File[] findOutputDirs​(java.lang.String projectroot, boolean includeTestClasses)
      Try to find the correct classpath root directories for current build tool chain.
      static java.lang.String firstToUpperCase​(java.lang.String str)
      Convert a string to the same string with first letter in upper case.
      static java.lang.String formatByteSize​(long bytes)
      Converts a number of bytes into a human-friendly binary prefix unit string (kiB, MiB, GiB, ...).
      static java.io.File getAppDir()
      Gets the "application directory", normally the current working directory, except in Android.
      static int getArrayDimension​(java.lang.Object array)
      Get the array dimension.
      static java.lang.String getClassFileLocation​(java.lang.Class<?> clazz)
      Get the file location for a class (either filename or jar url).
      static java.util.List<java.net.URL> getClasspathURLs​(java.lang.ClassLoader classloader, boolean includebootpath)
      Get the current classpath as a list of URLs
      static java.lang.String getCodeSource​(java.lang.String filename, java.lang.String pck)
      Get the source code base using a packagename and a filename.
      static java.io.File getDefaultDirectory()
      Get the home directory.
      static java.lang.String getDisplayName​(java.io.File file)
      Get the display name (e.g.
      static java.lang.String getDurationHMS​(long ms)
      Get a string representation for a duration.
      static java.lang.String getExceptionStacktrace​(java.lang.Throwable e)
      Get the exception stacktrace.
      static java.io.File getFile​(java.net.URL url)
      Get the file from an URL.
      static java.io.File[] getFiles​(java.io.File file, boolean hiding)
      Get the files of a directory.
      static java.lang.String getGeoIPLocation()
      Determine the location of the local computer using some GeoIP web service.
      static java.io.File getHomeDirectory()
      Get the home directory.
      static java.net.InetAddress getInet4Address()
      Get a IPV4 address of the local host.
      static java.net.InetAddress getInet6Address()
      Get a IPV4 address of the local host.
      static java.net.InetAddress getInetAddress()
      Get an address of the local host.
      static java.lang.String getJarName​(java.lang.String filename)
      Get the name of a jar file without extension and version info.
      static long getLastModified​(java.io.File f)
      Recursively get the newest last modified of a file or directory tree.
      static long getLastModified​(java.io.File f, boolean nocache)
      Recursively get the newest last modified of a file or directory tree.
      static java.lang.String getMacAddress()
      Get the mac address.
      static java.lang.String getMacAddressAsString​(byte[] mac)
      Convert a mac address to a string.
      static java.lang.String[] getMacAddresses()
      Get the mac address.
      static java.net.InetAddress[] getNetworkAddresses()
      Get the addresses to be used for transports.
      static java.util.List<java.net.NetworkInterface> getNetworkInterfaces()
      Get the network interfaces.
      static java.net.InetAddress getNetworkIp​(java.net.InetAddress addr, short prefixlen)
      Get the network ip for an internet address and the prefix length.
      static java.util.List<java.net.InetAddress> getNetworkIps()
      Get the network ips.
      static short getNetworkPrefixLength​(java.net.InetAddress iadr)
      Get the network prefix length for IPV4 address 24=C, 16=B, 8=A classes.
      static java.io.OutputStream getOutForSystemIn()
      Get an output stream that is automatically fed into the new System.in, i.e.
      static java.lang.String getOutputDirsExpression​(java.lang.String projectroot, boolean includeTestClasses)
      Try to find the correct classpath root directories for current build tool chain.
      static java.io.File getParentDirectory​(java.io.File file)
      Get the parent directory.
      static java.lang.String getPlural​(java.lang.String s)
      Get the plural of a word in singular.
      static int getPrefixLength​(java.io.File file)
      Get the prefix length of a file.
      static java.io.InputStream getResource​(java.lang.String name, java.lang.ClassLoader classloader)
      Get an input stream for whatever provided.
      static java.io.InputStream getResource0​(java.lang.String name, java.lang.ClassLoader classloader)
      Get an input stream for whatever provided.
      static ResourceInfo getResourceInfo0​(java.lang.String name, java.lang.ClassLoader classloader)
      Get an input stream for whatever provided.
      static java.security.SecureRandom getSecureRandom()
      Gets the global secure random.
      static java.lang.String getSingular​(java.lang.String s)
      Get the singular of a word in plural.
      static java.lang.String getStackTrace​(java.lang.Exception e)
      Get the exception stack trace as string.
      static java.lang.String getStackTraceString​(java.lang.String topline, java.lang.StackTraceElement[] trace)
      Converts a stack trace array to a printable string.
      static java.lang.String[] getStringArray​(java.lang.String key, java.util.Properties props)
      Get a string array of properties that are separated by commas.
      static java.lang.String guessContentTypeByBytes​(byte[] data)
      Guess the mime type by the file name.
      static java.lang.String guessContentTypeByFilename​(java.lang.String name)
      Guess the mime type by the file name.
      protected static void hashDirectory​(java.lang.String root, java.io.File dir, java.security.MessageDigest md)
      Get the hash code of a directory recursively.
      protected static void hashStream​(java.io.InputStream is, java.security.MessageDigest md)  
      static java.lang.String hex​(byte[] data)
      Convert a byte array to a string representation.
      static java.lang.String hex​(byte[] data, boolean uppercase)
      Convert a byte array to a string representation.
      static java.lang.String hex​(byte[] data, java.lang.String delim, int block)
      Convert a byte array to a string representation.
      static java.lang.String hex​(byte[] data, java.lang.String delim, int block, boolean uppercase)
      Convert a byte array to a string representation.
      static java.lang.String hex​(char ch)
      Convert char to hex vavlue.
      static int indexOfFilename​(java.lang.String url, java.util.List<java.lang.String> urlstrings)
      Test if a file name is contained.
      static int inndexOfLastUpperCaseCharacter​(java.lang.String str)
      Find index of last upper case letter.
      static java.lang.String intern​(java.lang.String 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​(java.io.File source, java.io.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​(java.io.File file)
      Check if a file represents a floppy.
      static boolean isGuiThread()
      Test if a call is running on the swing thread.
      static boolean isInRange​(java.util.Date date, java.util.Date start, java.util.Date end)
      Test if the date is in the range.
      static boolean isJavaSourceFilename​(java.lang.String filename)
      Test if a file is a Java source file.
      static boolean isUTF8​(byte[] bytes)
      Test if starts with UTF-8 BOM.
      static boolean isWindows()
      Tests if the OS is Windows.
      static <T> java.lang.Object[] iteratorToArray​(java.util.Iterator<T> it, java.lang.Class<T> clazz)
      Transform an iterator to an array.
      static <T> java.util.List<T> iteratorToList​(java.util.Iterator<T> it)
      Transform an iterator to a list.
      static <T> java.util.List<T> iteratorToList​(java.util.Iterator<T> it, java.util.List<T> ret)
      Transform an iterator to a list.
      static <T> T[] joinArbitraryArrays​(java.lang.Object[] as)
      Joins any arrays of (possibly) different type.
      static java.lang.Object joinArrays​(java.lang.Object... arrays)
      Joins two arrays of the same type.
      static java.lang.String loadBinary​(java.lang.String file)
      Load a binary file as base 64 string, e.g.
      protected static LRU<java.lang.String,​Tuple2<java.lang.Long,​java.lang.String>> loadHashCache()
      Load the stored hashes.
      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 main​(java.lang.String[] args)  
      static java.lang.String makeConform​(java.lang.String input)
      Convert an output to html/wml conform presentation.
      static java.lang.String makeConform​(java.lang.String input, int flag)
      Convert an output to html/wml conform presentation.
      static java.lang.String makeEnglishConform​(java.lang.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 moveFile​(java.io.File source, java.io.File target)
      Moves a file to a target location.
      static void noEx​(SUtil.NoExRunnable r)
      Run code ignoring exceptions.
      static java.lang.Object noExRet​(SUtil.NoExSupplier r)
      Run code ignoring exceptions.
      static <T> java.util.Collection<T> notNull​(java.util.Collection<T> coll)
      Helper method to allow iterating over possibly null collections.
      static <T> java.util.List<T> notNull​(java.util.List<T> list)
      Helper method to allow iterating over possibly null lists.
      static <K,​E>
      java.util.Map<K,​E>
      notNull​(java.util.Map<K,​E> map)
      Helper method to allow iterating over possibly null maps.
      static <T> java.util.Set<T> notNull​(java.util.Set<T> set)
      Helper method to allow iterating over possibly null sets.
      static byte[] readFile​(java.io.File file)
      Reads a file into memory (byte array).
      static java.lang.String readFile​(java.lang.String filename)
      Read a file to string.
      static java.lang.String readFile​(java.lang.String filename, java.lang.ClassLoader cl)
      Read a file to string.
      static void readStream​(byte[] buf, int off, int len, java.io.InputStream is)
      Reads part of an input stream into a buffer.
      static void readStream​(byte[] buf, int off, int len, java.io.InputStream is, long skip)
      Reads part of an input stream into a buffer.
      static void readStream​(byte[] buf, java.io.InputStream is)
      Fills buffer from an input stream.
      static byte[] readStream​(java.io.InputStream is)
      Reads an input stream into memory (byte array).
      static java.lang.String[] readStreamLines​(java.io.InputStream is)
      Reads a (text) stream line-wise and returns lines as array.
      static java.lang.String[] readStreamLines​(java.io.InputStream is, java.nio.charset.Charset encoding)
      Reads a (text) stream line-wise and returns lines as array.
      static java.lang.String removeBOM​(java.lang.String text)
      Remove BOM from UTF text.
      static java.lang.String removeExtension​(java.lang.String fn)
      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 java.net.URL[] removeSystemUrls​(java.net.URL[] urls)
      Removes the (.jar) URLs contained in directories associated with the JVM.
      static void replace​(java.lang.String source, java.lang.StringBuffer dest, java.lang.String old, java.lang.String newstring)
      Parse a source string replacing occurrences and storing the result in the given string buffer.
      static java.lang.String replace​(java.lang.String source, java.lang.String old, java.lang.String newstring)
      Parse a source string replacing occurrences and returning the result.
      static java.lang.String replaceLast​(java.lang.String string, java.lang.String toreplace, java.lang.String replacement)
      Replace the last occurrence of a substring.
      static void rethrowAsUnchecked​(java.lang.Throwable e)
      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 void sleep​(long millis)
      Sleep the current thread, ignore exceptions.
      static java.lang.String snakeToCamelCase​(java.lang.String snake)
      Convert snake_case to CamelCase.
      static java.lang.String[] splitCommandline​(java.lang.String line)
      Taken from ant.
      static java.util.List<byte[]> splitData​(byte[] data)
      Primitive encoding approach: Splits a byte array that was encoded with mergeData().
      static java.util.List<byte[]> splitData​(byte[] data, int offset, int length)
      Primitive encoding approach: Splits a byte array that was encoded with mergeData().
      static java.lang.String stripTags​(java.lang.String source)
      Strip tags (e.g.
      static java.lang.Object substractArrays​(java.lang.Object a1, java.lang.Object a2)
      First array minus second array.
      protected static void testIntByteConversion()  
      static java.lang.RuntimeException throwUnchecked​(java.lang.Throwable t)
      Convert a throwable to an unchecked exception (i.e.
      static java.io.File toFile​(java.net.URL url)
      Converts a file URL to a File, returns null if invalid.
      static java.io.File toFile0​(java.net.URL url)
      Converts a file URL to a File, returns null if invalid.
      static java.net.URI toURI​(java.lang.String transporturi)
      Convert stringified URI (as used in transports for some weird reason) to URI.
      static java.net.URI toURI​(java.lang.String scheme, java.net.InetAddress address, int port)
      Convert a scheme, InetAdress and port to a valid URI or throw.
      static java.net.URI toURI​(java.net.URL url)
      Convert a URL to a URI but ignore exceptions
      static java.net.URI toURI0​(java.net.URL url)
      Convert a URL to a URI but ignore exceptions
      static java.net.URL toURL​(java.lang.Object url)
      Convert a file/string/url.
      static java.net.URL toURL0​(java.net.URI uri)
      Convert a URI to a URL but ignore exceptions
      static java.net.URL[] toURLs​(java.lang.Object[] urls)
      Convert a file/string/url array.
      static java.lang.String toUTF8​(byte[] bytes)
      Returns a UTF8 byte array as string.
      static java.lang.String unescapeLineBreaks​(java.lang.String escapedstring)
      Unescapes all line breaks from strings similar to Java string literals.
      static void unzip​(java.util.zip.ZipFile zip, java.io.File dir)
      Unzip a file into a specific dir.
      static java.io.File urlToFile​(java.lang.String url)
      Convert an URL to a file.
      static java.lang.String wrapText​(java.lang.String text)
      Wrap a text at a given line length.
      static java.lang.String wrapText​(java.lang.String text, int wrap)
      Wrap a text at a given line length.
      static void writeDirectory​(java.io.File dir, java.io.OutputStream out)
      Write a directory as jar to an output stream.
      protected static void writeDirectory​(java.lang.String prefix, java.io.File dir, java.util.zip.ZipOutputStream zos, byte[] buf)
      Write a directory as jar to an output stream.
      static void writeFile​(java.lang.String val, java.lang.String filename)
      Write a string to a file.
      static void writeFile​(java.lang.String val, java.lang.String filename, java.lang.String charset)
      Write a string to a file.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • JADEXDIR

        public static final java.lang.String JADEXDIR
        Directory were jadex stores files generated during runtime, to be used for later runs.
        See Also:
        Constant Field Values
      • LF

        public static final java.lang.String LF
        Line separator.
      • BYTE_UNITS

        public static final java.lang.String[] BYTE_UNITS
        Units for representing byte values.
      • BYTEFORMATTER1

        public static final java.text.DecimalFormat BYTEFORMATTER1
        The byte formatter for one predecimal digit.
      • BYTEFORMATTER2

        public static final java.text.DecimalFormat BYTEFORMATTER2
        The byte formatter for two predecimal digits.
      • BYTEFORMATTER3

        public static final java.text.DecimalFormat BYTEFORMATTER3
        The byte formatter for three predecimal digits.
      • CONVERT_ALL

        public static final int CONVERT_ALL
        Constant that indicates a conversion of all known characters.
        See Also:
        Constant Field Values
      • CONVERT_ALL_EXCEPT_AMP

        public static final int CONVERT_ALL_EXCEPT_AMP
        Constant that indicates a conversion of all known characters except &.
        See Also:
        Constant Field Values
      • CONVERT_NONE

        public static final int CONVERT_NONE
        Constant that indicates a conversion of no characters.
        See Also:
        Constant Field Values
      • ASCII

        public static final java.nio.charset.Charset ASCII
        ASCII charset.
      • UTF8

        public static final java.nio.charset.Charset UTF8
        UTF-8 charset.
      • ISO8859_1

        public static final java.nio.charset.Charset ISO8859_1
        ISO-8859-1 charset.
      • FAST_RANDOM

        public static final java.util.Random FAST_RANDOM
        Access to non-secure fast random source.
      • SECURE_RANDOM

        public static volatile java.security.SecureRandom SECURE_RANDOM
        Access to secure random source.
      • MIMETYPES

        protected static volatile java.util.Map<java.lang.String,​java.lang.String> MIMETYPES
        The mime types.
      • SDF

        public static final java.lang.ThreadLocal<java.text.DateFormat> SDF
        Simple date format.
      • SDF2

        public static final java.lang.ThreadLocal<java.text.DateFormat> SDF2
      • SDF3

        public static final java.lang.ThreadLocal<java.text.DateFormat> SDF3
      • ISO8601UTCFALLBACKS

        public static final java.lang.String[] ISO8601UTCFALLBACKS
        ISO8601 fallbacks assuming UTC.
      • ISO8601ZONEDFALLBACKS

        public static final java.lang.String[] ISO8601ZONEDFALLBACKS
        ISO8601 fallbacks with included timezone.
      • appdir

        protected static volatile java.io.File appdir
        Application directory, current working dir under normal Java, special with Android.
      • htmlwraps

        protected static final java.util.Map<java.lang.String,​java.lang.String> htmlwraps
        Mapping from single characters to encoded version for displaying on xml-style interfaces.
      • seps

        protected static final java.lang.String seps
        Holds the single characters.
      • EMPTY_ENUMERATION

        public static final java.util.Enumeration EMPTY_ENUMERATION
        An empty enumeration.
      • EMPTY_STRING_ARRAY

        public static final java.lang.String[] EMPTY_STRING_ARRAY
        An empty string array.
      • EMPTY_CLASS_ARRAY

        public static final java.lang.Class[] EMPTY_CLASS_ARRAY
        An empty class array.
      • EMPTY_OBJECT_ARRAY

        public static final java.lang.Object[] EMPTY_OBJECT_ARRAY
        An empty class array.
      • DEFTIMEOUT

        public static final long DEFTIMEOUT
        Default timeout e.g. from environment.
      • convidcnt

        protected static java.util.concurrent.atomic.AtomicLong convidcnt
        The counter for conversation ids.
      • OUT_FOR_SYSTEM_IN

        protected static java.io.OutputStream OUT_FOR_SYSTEM_IN
      • NIS

        protected static volatile java.util.List<java.net.NetworkInterface> NIS
        The cached network interfaces.
      • NISTIME

        protected static long NISTIME
        The time of the last caching of network interfaces.
      • macs

        public static volatile java.lang.String[] macs
        Cached for speed.
      • HASHES

        protected static LRU<java.lang.String,​Tuple2<java.lang.Long,​java.lang.String>> HASHES
        LRU for hashes.
      • LASTMODS

        protected static LRU<java.lang.String,​java.lang.Long> LASTMODS
        LRU for directory modification dates.
      • ID_CHARS

        protected static final char[] ID_CHARS
        Lookup table used for unique strings.
    • Constructor Detail

      • SUtil

        public SUtil()
    • Method Detail

      • getSecureRandom

        public static final java.security.SecureRandom getSecureRandom()
        Gets the global secure random.
        Returns:
        The secure random.
      • getStringArray

        public static java.lang.String[] getStringArray​(java.lang.String key,
                                                        java.util.Properties props)
        Get a string array of properties that are separated by commas.
        Parameters:
        key - The key.
        props - The properties.
        Returns:
        The strings.
      • joinArrays

        public static java.lang.Object joinArrays​(java.lang.Object... arrays)
        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

        public static <T> T[] joinArbitraryArrays​(java.lang.Object[] as)
        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

        public static java.lang.Object cutArrays​(java.lang.Object a1,
                                                 java.lang.Object a2)
        Cut two arrays.
        Parameters:
        a1 - The first array.
        a2 - The second array.
        Returns:
        The cutted array.
      • substractArrays

        public static java.lang.Object substractArrays​(java.lang.Object a1,
                                                       java.lang.Object a2)
        First array minus second array.
        Parameters:
        a1 - The first array.
        a2 - The second array.
        Returns:
        The substracted array.
      • arrayToList

        public static <T> java.util.List<T> arrayToList​(java.lang.Object a)
        Transform an array to a vector.
        Parameters:
        a - The array.
        Returns:
        The vector for the array.
      • arrayToSet

        public static <T> java.util.Set<T> arrayToSet​(java.lang.Object a)
        Transform an array to a vector.
        Parameters:
        a - The array.
        Returns:
        The vector for the array.
      • iteratorToList

        public static <T> java.util.List<T> iteratorToList​(java.util.Iterator<T> it)
        Transform an iterator to a list.
      • iteratorToList

        public static <T> java.util.List<T> iteratorToList​(java.util.Iterator<T> it,
                                                           java.util.List<T> ret)
        Transform an iterator to a list.
      • iteratorToArray

        public static <T> java.lang.Object[] iteratorToArray​(java.util.Iterator<T> it,
                                                             java.lang.Class<T> clazz)
        Transform an iterator to an array.
      • arrayContains

        public static boolean arrayContains​(java.lang.Object array,
                                            java.lang.Object value)
        Check if an element is contained in an array.
        Parameters:
        array - The array.
        value - The value.
      • getArrayDimension

        public static int getArrayDimension​(java.lang.Object array)
        Get the array dimension.
        Parameters:
        array - The array.
        Returns:
        The number of dimensions.
      • equals

        public static boolean equals​(java.lang.Object val1,
                                     java.lang.Object val2)
      • arrayEmptyOrNull

        public static final boolean arrayEmptyOrNull​(java.lang.Object array)
        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

        public static boolean arrayEquals​(java.lang.Object array1,
                                          java.lang.Object array2)
        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

        public static int arrayHashCode​(java.lang.Object a)
        Calculate a hash code for an array.
      • arrayToString

        public static java.lang.String arrayToString​(java.lang.Object array)
        Get a string representation for an array.
        Parameters:
        array - The array.
        Returns:
        formatted string.
      • convertMapKeysToLowercase

        public static <T> java.util.Map<java.lang.String,​T> convertMapKeysToLowercase​(java.util.Map<java.lang.String,​T> map)
        Create a map copy with all keys in lowercase.
        Parameters:
        map - The original map.
        Returns:
        The converted map.
      • getSingular

        public static java.lang.String getSingular​(java.lang.String s)
        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

        public static java.lang.String getPlural​(java.lang.String s)
        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

        public static int compareTo​(java.lang.String a,
                                    java.lang.String b)
        Compares two strings, ignoring case.
        Parameters:
        a - The first string.
        b - The second string.
        Returns:
        a
      • isInRange

        public static boolean isInRange​(java.util.Date date,
                                        java.util.Date start,
                                        java.util.Date end)
        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

        public static java.lang.String removeExtension​(java.lang.String fn)
        Remove file extension.
        Parameters:
        fn - The filename..
        Returns:
        filename without extension.
      • wrapText

        public static java.lang.String wrapText​(java.lang.String text)
        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

        public static java.lang.String wrapText​(java.lang.String text,
                                                int wrap)
        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

        public static java.lang.String makeConform​(java.lang.String input)
        Convert an output to html/wml conform presentation.
        Parameters:
        input - The input string.
        Returns:
        The converted output string.
      • makeConform

        public static java.lang.String makeConform​(java.lang.String input,
                                                   int flag)
        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

        public static java.lang.String stripTags​(java.lang.String source)
        Strip tags (e.g. html) from a string, leaving only the text content.
      • makeEnglishConform

        public static java.lang.String makeEnglishConform​(java.lang.String input)
        Convert an output readable in english. Therefore remove all äs, ös, üs etc.
        Parameters:
        input - The input string.
        Returns:
        The converted output string.
      • camelToSnakeCase

        public static java.lang.String camelToSnakeCase​(java.lang.String camel)
        Convert CamelCase to snake_case.
      • snakeToCamelCase

        public static java.lang.String snakeToCamelCase​(java.lang.String snake)
        Convert snake_case to CamelCase.
      • replace

        public static void replace​(java.lang.String source,
                                   java.lang.StringBuffer dest,
                                   java.lang.String old,
                                   java.lang.String newstring)
        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

        public static java.lang.String replace​(java.lang.String source,
                                               java.lang.String old,
                                               java.lang.String newstring)
        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

        public static java.io.InputStream getResource​(java.lang.String name,
                                                      java.lang.ClassLoader classloader)
                                               throws java.io.IOException
        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:
        java.io.IOException - when the resource was not found.
      • getResource0

        public static java.io.InputStream getResource0​(java.lang.String name,
                                                       java.lang.ClassLoader classloader)
        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

        public static ResourceInfo getResourceInfo0​(java.lang.String name,
                                                    java.lang.ClassLoader classloader)
        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

        public static int copyStream​(java.io.InputStream is,
                                     java.io.OutputStream os)
        Copy all data from input to output stream.
      • getDurationHMS

        public static java.lang.String getDurationHMS​(long ms)
        Get a string representation for a duration.
        Parameters:
        ms - The duration in ms.
        Returns:
        The string representation.
      • convertPathToPackage

        public static java.lang.String convertPathToPackage​(java.lang.String path,
                                                            java.net.URL[] urls)
        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

        public static java.util.List<java.net.URL> getClasspathURLs​(java.lang.ClassLoader classloader,
                                                                    boolean includebootpath)
        Get the current classpath as a list of URLs
      • collectClasspathURLs

        public static java.util.Set<java.net.URL> collectClasspathURLs​(java.lang.ClassLoader baseloader)
        Get other contained (but not directly managed) urls from parent classloaders.
        Returns:
        The set of urls.
      • collectClasspathURLs

        protected static void collectClasspathURLs​(java.lang.ClassLoader classloader,
                                                   java.util.Set<java.net.URL> set,
                                                   java.util.Set<java.lang.String> jarnames)
        Collect all URLs belonging to a class loader.
      • getJarName

        public static java.lang.String getJarName​(java.lang.String filename)
        Get the name of a jar file without extension and version info.
      • collectManifestURLs

        public static void collectManifestURLs​(java.net.URL url,
                                               java.util.Set<java.net.URL> set,
                                               java.util.Set<java.lang.String> jarnames)
        Collect all URLs as specified in a manifest.
      • calculateCartesianProduct

        public static <T,​E> java.util.List<java.util.Map<T,​E>> calculateCartesianProduct​(T[] names,
                                                                                                     E[] values)
        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

        public static boolean isJavaSourceFilename​(java.lang.String filename)
        Test if a file is a Java source file.
        Parameters:
        filename - The filename.
        Returns:
        True, if it is a Java source file.
      • createHashMap

        public static <K,​T> java.util.Map<K,​T> createHashMap​(K[] keys,
                                                                         T[] values)
        Create a hash map from keys and values.
        Parameters:
        keys - The keys.
        values - The values.
        Returns:
        The map.
      • createHashSet

        public static <T> java.util.Set<T> createHashSet​(T[] values)
        Create a hash set from values.
        Parameters:
        values - The values.
        Returns:
        The map.
      • createArrayList

        public static <T> java.util.List<T> createArrayList​(T[] values)
        Create an array list from values.
        Parameters:
        values - The values.
        Returns:
        The map.
      • createUniqueId

        public static java.lang.String createUniqueId()
        Create a globally unique conversation id.
        Returns:
        The conversation id.
      • createUniqueId

        public static java.lang.String createUniqueId​(java.lang.String name)
        Create a globally unique conversation id.
        Returns:
        The conversation id.
      • createPlainRandomId

        public static java.lang.String createPlainRandomId​(java.lang.String name,
                                                           int length)
        Create a random id with only alphanumeric chars.
        Returns:
        The id.
      • testIntByteConversion

        protected static void testIntByteConversion()
      • convertPathToRelative

        public static java.lang.String convertPathToRelative​(java.lang.String absolute)
        Convert an absolute path to a relative path based on the current user directory.
      • toURLs

        public static java.net.URL[] toURLs​(java.lang.Object[] urls)
        Convert a file/string/url array.
        Parameters:
        urls - The url strings.
        Returns:
        The urls.
      • toURL

        public static java.net.URL toURL​(java.lang.Object url)
        Convert a file/string/url.
      • toURL0

        public static java.net.URL toURL0​(java.net.URI uri)
        Convert a URI to a URL but ignore exceptions
      • toURI0

        public static java.net.URI toURI0​(java.net.URL url)
        Convert a URL to a URI but ignore exceptions
      • toURI

        public static java.net.URI toURI​(java.net.URL url)
        Convert a URL to a URI but ignore exceptions
      • toURI

        public static java.net.URI toURI​(java.lang.String scheme,
                                         java.net.InetAddress address,
                                         int port)
        Convert a scheme, InetAdress and port to a valid URI or throw.
        Parameters:
        scheme -
        address -
        port -
        Returns:
        URI
      • toURI

        public static java.net.URI toURI​(java.lang.String transporturi)
        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

        public static final java.io.File toFile​(java.net.URL url)
        Converts a file URL to a File, returns null if invalid.
        Parameters:
        url - The URL.
        Returns:
        File or null if invalid.
      • toFile0

        public static final java.io.File toFile0​(java.net.URL url)
        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

        public static final java.lang.RuntimeException convertToRuntimeException​(java.lang.Throwable e)
        Converts an exception to RuntimeException, returns original if already a RuntimeException.
        Parameters:
        e - The throwable to be returned as RuntimeException
        Returns:
        RuntimeException.
      • rethrowAsUnchecked

        public static final void rethrowAsUnchecked​(java.lang.Throwable e)
        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

        public static void main​(java.lang.String[] args)
      • formatByteSize

        public static java.lang.String formatByteSize​(long bytes)
        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

        public static java.net.InetAddress getNetworkIp​(java.net.InetAddress addr,
                                                        short prefixlen)
        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

        public static java.lang.String bytesToString​(long bytes)
        Get bytes as human readable string.
      • getClassFileLocation

        public static java.lang.String getClassFileLocation​(java.lang.Class<?> clazz)
        Get the file location for a class (either filename or jar url).
      • convertURLToString

        public static java.lang.String convertURLToString​(java.net.URL url)
        Convert an URL to a local file name.
        Parameters:
        url - The url.
        Returns:
        The absolute path to the url resource.
      • indexOfFilename

        public static int indexOfFilename​(java.lang.String url,
                                          java.util.List<java.lang.String> urlstrings)
        Test if a file name is contained.
      • urlToFile

        public static java.io.File urlToFile​(java.lang.String url)
        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

        public static final java.lang.String intern​(java.lang.String string)
        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

        public static final java.net.URL[] removeSystemUrls​(java.net.URL[] urls)
        Removes the (.jar) URLs contained in directories associated with the JVM.
        Parameters:
        urls - The input URLs.
        Returns:
        URLs without the system path URLs.
      • dateToIso8601

        public static java.lang.String dateToIso8601​(java.util.Date date)
        Creates an ISO 8601-compliant string out of a java Date object.
        Parameters:
        date - The date object.
        Returns:
        ISO 8601-compliant string.
      • dateFromIso8601

        public static java.util.Date dateFromIso8601​(java.lang.String isostring)
        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

        public static void addSystemOutListener​(IChangeListener listener)
        Add a listener to System.out.
      • removeSystemOutListener

        public static void removeSystemOutListener​(IChangeListener listener)
        Remove a listener from System.out.
      • addSystemErrListener

        public static void addSystemErrListener​(IChangeListener listener)
        Add a listener to System.err.
      • removeSystemErrListener

        public static void removeSystemErrListener​(IChangeListener listener)
        Remove a listener from System.err.
      • getOutForSystemIn

        public static java.io.OutputStream getOutForSystemIn()
                                                      throws java.io.IOException
        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:
        java.io.IOException
      • getInet4Address

        public static java.net.InetAddress getInet4Address()
        Get a IPV4 address of the local host. Ignores loopback address and V6 addresses.
        Returns:
        First found IPV4 address.
      • getInet6Address

        public static java.net.InetAddress getInet6Address()
        Get a IPV4 address of the local host. Ignores loopback address and V4 addresses.
        Returns:
        First found IPV4 address.
      • getInetAddress

        public static java.net.InetAddress 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

        public static short getNetworkPrefixLength​(java.net.InetAddress iadr)
        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

        public static java.util.List<java.net.InetAddress> getNetworkIps()
        Get the network ips.
      • copyArray

        public static <T> T[] copyArray​(T[] original)
        Copy an array.
      • getCodeSource

        public static java.lang.String getCodeSource​(java.lang.String filename,
                                                     java.lang.String pck)
        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

        public static int countOccurrences​(java.lang.String string,
                                           char find)
        Count the occurrences of a char in a string.
        Parameters:
        string - The string.
        find - The char to find.
        Returns:
        The number of occurrences.
      • getNetworkInterfaces

        public static java.util.List<java.net.NetworkInterface> getNetworkInterfaces()
                                                                              throws java.net.SocketException
        Get the network interfaces. The result is cached for a short time period to speed things up.
        Throws:
        java.net.SocketException
      • getNetworkAddresses

        public static java.net.InetAddress[] getNetworkAddresses()
                                                          throws java.net.SocketException
        Get the addresses to be used for transports.
        Throws:
        java.net.SocketException
      • unzip

        public static void unzip​(java.util.zip.ZipFile zip,
                                 java.io.File dir)
        Unzip a file into a specific dir.
        Parameters:
        zip - The zip file.
        dir - The target dir.
      • deleteDirectory

        public static boolean deleteDirectory​(java.io.File dir)
        Delete a directory completely (including all subdirs and files).
        Parameters:
        dir - The dir to delete.
        Returns:
        True, if was successfully deleted.
      • getHomeDirectory

        public static java.io.File getHomeDirectory()
        Get the home directory.
      • getDefaultDirectory

        public static java.io.File getDefaultDirectory()
        Get the home directory.
      • getParentDirectory

        public static java.io.File getParentDirectory​(java.io.File file)
        Get the parent directory.
      • getFiles

        public static java.io.File[] getFiles​(java.io.File file,
                                              boolean hiding)
        Get the files of a directory.
      • getPrefixLength

        public static int getPrefixLength​(java.io.File file)
        Get the prefix length of a file.
      • isFloppyDrive

        public static boolean isFloppyDrive​(java.io.File file)
        Check if a file represents a floppy. Returns false on android.
      • getDisplayName

        public static java.lang.String getDisplayName​(java.io.File file)
        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

        public static java.lang.String escapeString​(java.lang.String str)
        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

        public static java.util.List<byte[]> splitData​(byte[] data)
        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

        public static java.util.List<byte[]> splitData​(byte[] data,
                                                       int offset,
                                                       int length)
        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 < 0.
        Returns:
        A list of byte arrays representing the original set.
      • hex

        public static java.lang.String hex​(char ch)
        Convert char to hex vavlue.
      • hex

        public static java.lang.String hex​(byte[] data)
        Convert a byte array to a string representation.
      • hex

        public static java.lang.String hex​(byte[] data,
                                           boolean uppercase)
        Convert a byte array to a string representation.
      • hex

        public static java.lang.String hex​(byte[] data,
                                           java.lang.String delim,
                                           int block)
        Convert a byte array to a string representation.
      • hex

        public static java.lang.String hex​(byte[] data,
                                           java.lang.String delim,
                                           int block,
                                           boolean uppercase)
        Convert a byte array to a string representation.
      • base16Encode

        public static java.lang.String base16Encode​(byte[] data)
        Encodes a set of data as a Base16 String (hex).
        Parameters:
        data - The data.
        Returns:
        Base16-encoded String.
      • base16Decode

        public static byte[] base16Decode​(java.lang.String data)
        Decodes a Base16-encoded String and returns the data.
        Parameters:
        data - The encoded data.
        Returns:
        The decoded data.
      • escapeLineBreaks

        public static java.lang.String escapeLineBreaks​(java.lang.String unescapedstring)
        Escapes all line breaks similar to Java string literals.
        Parameters:
        unescapedstring - Unescaped input string.
        Returns:
        Escaped string.
      • unescapeLineBreaks

        public static java.lang.String unescapeLineBreaks​(java.lang.String escapedstring)
        Unescapes all line breaks from strings similar to Java string literals.
        Parameters:
        escapedstring - Escaped input string.
        Returns:
        Unescaped string.
      • splitCommandline

        public static java.lang.String[] splitCommandline​(java.lang.String line)
        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

        public static java.io.File getFile​(java.net.URL url)
        Get the file from an URL.
        Parameters:
        url - The file URL.
        Returns:
        The file.
      • copyFile

        public static void copyFile​(java.io.File source,
                                    java.io.File target)
                             throws java.io.IOException
        Copy a file.
        Parameters:
        source - The source file.
        target - The target file or directory (will be deleted first).
        Throws:
        java.io.IOException
      • moveFile

        public static void moveFile​(java.io.File source,
                                    java.io.File target)
                             throws java.io.IOException
        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:
        java.io.IOException
      • internalMoveFile

        protected static void internalMoveFile​(java.io.File source,
                                               java.io.File target)
                                        throws java.io.IOException
        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:
        java.io.IOException
      • readFile

        public static byte[] readFile​(java.io.File file)
                               throws java.io.IOException
        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:
        java.io.IOException - Exception on IO errors.
      • readStream

        public static byte[] readStream​(java.io.InputStream is)
                                 throws java.io.IOException
        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:
        java.io.IOException - Exception on IO errors.
      • readStream

        public static void readStream​(byte[] buf,
                                      java.io.InputStream is)
        Fills buffer from an input stream. Note: This only works for sizes smaller than 2GiB.
        Parameters:
        buf - The buffer.
        is - The InputStream.
      • readStream

        public static void readStream​(byte[] buf,
                                      int off,
                                      int len,
                                      java.io.InputStream is)
        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

        public static void readStream​(byte[] buf,
                                      int off,
                                      int len,
                                      java.io.InputStream is,
                                      long skip)
        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, skip<=0 for no skip.
      • readStreamLines

        public static java.lang.String[] readStreamLines​(java.io.InputStream is)
        Reads a (text) stream line-wise and returns lines as array.
        Parameters:
        is - InputStream.
        Returns:
        Array of lines.
      • readStreamLines

        public static java.lang.String[] readStreamLines​(java.io.InputStream is,
                                                         java.nio.charset.Charset encoding)
        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

        public static void close​(java.net.Socket socket)
        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

        public static void noEx​(SUtil.NoExRunnable r)
        Run code ignoring exceptions.
        Parameters:
        r - Expression whose exceptions are ignored.
      • noExRet

        public static java.lang.Object noExRet​(SUtil.NoExSupplier r)
        Run code ignoring exceptions.
        Parameters:
        r - Expression whose exceptions are ignored.
      • close

        public static void close​(java.io.Closeable closeable)
        Attempt to close a Closeable (e.g. on error recovery) ignoring any error.
        Parameters:
        closeable - The closeable.
      • getStackTrace

        public static java.lang.String getStackTrace​(java.lang.Exception e)
        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

        public static byte[] computeFileHash​(java.lang.String filename)
        Compute a file hash.
        Parameters:
        filename - The filename.
        Returns:
        The hash.
      • computeFileHash

        public static byte[] computeFileHash​(java.lang.String filename,
                                             java.lang.String algorithm)
        Compute a file hash.
        Parameters:
        filename - The filename.
        algorithm - The hash algorithm.
        Returns:
        The hash.
      • firstToUpperCase

        public static java.lang.String firstToUpperCase​(java.lang.String str)
        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

        public static java.lang.String getMacAddress()
        Get the mac address.
        Returns:
        The mac address.
      • getMacAddresses

        public static java.lang.String[] getMacAddresses()
        Get the mac address.
        Returns:
        The mac address.
      • createRegexFromGlob

        public static java.util.regex.Pattern createRegexFromGlob​(java.lang.String glob)
        Create a regex from a normal bnf pattern.
      • readFile

        public static java.lang.String readFile​(java.lang.String filename)
        Read a file to string.
        Parameters:
        filename - The file name.
        Returns:
        The string.
      • readFile

        public static java.lang.String readFile​(java.lang.String filename,
                                                java.lang.ClassLoader cl)
        Read a file to string.
        Parameters:
        filename - The file name.
        Returns:
        The string.
      • writeFile

        public static void writeFile​(java.lang.String val,
                                     java.lang.String filename)
        Write a string to a file.
        Parameters:
        val - The string to write.
        filename - The file name.
      • writeFile

        public static void writeFile​(java.lang.String val,
                                     java.lang.String filename,
                                     java.lang.String charset)
        Write a string to a file.
        Parameters:
        val - The string to write.
        filename - The file name.
      • getAppDir

        public static java.io.File getAppDir()
        Gets the "application directory", normally the current working directory, except in Android.
        Returns:
        Application directory.
      • loadBinary

        public static java.lang.String loadBinary​(java.lang.String file)
        Load a binary file as base 64 string, e.g. for embedded html images.
      • removeBOM

        public static java.lang.String removeBOM​(java.lang.String text)
        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

        public static java.lang.String toUTF8​(byte[] bytes)
        Returns a UTF8 byte array as string.
        Parameters:
        bytes - The bytes.
        Returns:
        The string.
      • getExceptionStacktrace

        public static java.lang.String getExceptionStacktrace​(java.lang.Throwable e)
        Get the exception stacktrace.
        Parameters:
        e - The exception.
        Returns:
        The exception stacktrace.
      • throwUnchecked

        public static java.lang.RuntimeException throwUnchecked​(java.lang.Throwable t)
                                                         throws java.lang.Error,
                                                                java.lang.RuntimeException
        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:
        java.lang.Error
        java.lang.RuntimeException
      • guessContentTypeByFilename

        public static java.lang.String guessContentTypeByFilename​(java.lang.String name)
        Guess the mime type by the file name.
        Parameters:
        name - The filename
        Returns:
        The mime type.
      • guessContentTypeByBytes

        public static java.lang.String guessContentTypeByBytes​(byte[] data)
        Guess the mime type by the file name.
        Parameters:
        name - The file content in bytes.
        Returns:
        The mime type.
      • containsDigit

        public static boolean containsDigit​(java.lang.String s)
        Test if a string contains a digit.
        Parameters:
        s - The string.
        Returns:
        True, if the string contains a digit.
      • loadHashCache

        protected static LRU<java.lang.String,​Tuple2<java.lang.Long,​java.lang.String>> loadHashCache()
        Load the stored hashes.
      • getLastModified

        public static long getLastModified​(java.io.File f)
        Recursively get the newest last modified of a file or directory tree.
      • getLastModified

        public static long getLastModified​(java.io.File f,
                                           boolean nocache)
        Recursively get the newest last modified of a file or directory tree.
      • hashDirectory

        protected static void hashDirectory​(java.lang.String root,
                                            java.io.File dir,
                                            java.security.MessageDigest md)
                                     throws java.lang.Exception
        Get the hash code of a directory recursively.
        Throws:
        java.lang.Exception
      • hashStream

        protected static void hashStream​(java.io.InputStream is,
                                         java.security.MessageDigest md)
                                  throws java.lang.Exception
        Throws:
        java.lang.Exception
      • writeDirectory

        public static void writeDirectory​(java.io.File dir,
                                          java.io.OutputStream out)
        Write a directory as jar to an output stream.
      • writeDirectory

        protected static void writeDirectory​(java.lang.String prefix,
                                             java.io.File dir,
                                             java.util.zip.ZipOutputStream zos,
                                             byte[] buf)
                                      throws java.lang.Exception
        Write a directory as jar to an output stream.
        Throws:
        java.lang.Exception
      • notNull

        public static <T> java.util.List<T> notNull​(java.util.List<T> list)
        Helper method to allow iterating over possibly null lists.
      • notNull

        public static <T> java.util.Collection<T> notNull​(java.util.Collection<T> coll)
        Helper method to allow iterating over possibly null collections.
      • notNull

        public static <T> java.util.Set<T> notNull​(java.util.Set<T> set)
        Helper method to allow iterating over possibly null sets.
      • notNull

        public static <K,​E> java.util.Map<K,​E> notNull​(java.util.Map<K,​E> map)
        Helper method to allow iterating over possibly null maps.
      • findKeyForValue

        public static <K,​V> K findKeyForValue​(java.util.Map<K,​V> map,
                                                    V value)
        Helper to find first matching key (if any) for a value (identity check).
      • getStackTraceString

        public static final java.lang.String getStackTraceString​(java.lang.String topline,
                                                                 java.lang.StackTraceElement[] trace)
        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.
      • getOutputDirsExpression

        public static java.lang.String getOutputDirsExpression​(java.lang.String projectroot,
                                                               boolean includeTestClasses)
        Try to find the correct classpath root directories for current build tool chain. Tries bin (e.g. eclipse), build/classes/main (gradle), target/classes (maven) and uses the directory with the newest file.
        Returns:
        an expression string of the fpr 'new String[]{...}'.
      • findOutputDirs

        public static java.io.File[] findOutputDirs​(java.lang.String projectroot,
                                                    boolean includeTestClasses)
        Try to find the correct classpath root directories for current build tool chain. Tries bin and bin/main (e.g. eclipse), build/classes/main (gradle), target/classes (maven) and uses the directory with the newest file.
      • findDirForProject

        public static java.io.File findDirForProject​(java.lang.String project)
        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

        public static final int diffuseStringHash​(java.lang.String s)
        Generate a diffuse string hash.
        Parameters:
        s - The string.
        Returns:
        The hash.
      • inndexOfLastUpperCaseCharacter

        public static int inndexOfLastUpperCaseCharacter​(java.lang.String str)
        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

        public static java.lang.String replaceLast​(java.lang.String string,
                                                   java.lang.String toreplace,
                                                   java.lang.String replacement)
        Replace the last occurrence of a substring.
        Parameters:
        string - The string
        toreplace - The substring to replace.
        replacement - The new substring
        Returns:
        The new string.
      • getGeoIPLocation

        public static java.lang.String getGeoIPLocation()
        Determine the location of the local computer using some GeoIP web service.
        Returns:
        The location as [
      • 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

        public static java.lang.String getMacAddressAsString​(byte[] mac)
        Convert a mac address to a string.
        Parameters:
        mac - The address.
        Returns:
        The string.