Package jadex.common

Class SUtil

java.lang.Object
jadex.common.SUtil

public class SUtil extends Object
This class provides several useful static util methods.
  • Field Details

    • DEBUG

      public static boolean DEBUG
      Global Debug Flag for additional debug information on the console
    • JADEXDIR

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

      public static final String LF
      Line separator.
    • BYTE_UNITS

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

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

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

      public static final 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:
    • CONVERT_ALL_EXCEPT_AMP

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

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

      public static final String NULL
      A Null value.
      See Also:
    • ASCII

      public static final Charset ASCII
      ASCII charset.
    • UTF8

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

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

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

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

      protected static volatile Map<String,String> MIMETYPES
      The mime types.
    • SDF

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

      public static final ThreadLocal<DateFormat> SDF2
    • SDF3

      public static final ThreadLocal<DateFormat> SDF3
    • ISO8601UTCFALLBACKS

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

      public static final String[] ISO8601ZONEDFALLBACKS
      ISO8601 fallbacks with included timezone.
    • executor

      protected static volatile ExecutorService executor
      Shared executor service for all components.
    • appdir

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

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

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

      public static final Enumeration EMPTY_ENUMERATION
      An empty enumeration.
    • EMPTY_STRING_ARRAY

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

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

      public static final Object[] EMPTY_OBJECT_ARRAY
      An empty class array.
    • RESOURCEINFO_MAPPERS

      protected static final IResultCommand<ResourceInfo,URLConnection>[] RESOURCEINFO_MAPPERS
    • DEFTIMEOUT

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

      public static final long DEFTIMEOUT_DEFAULT
      See Also:
    • convidcnt

      protected static AtomicLong convidcnt
      The counter for conversation ids.
    • OUT_FOR_SYSTEM_IN

      protected static OutputStream OUT_FOR_SYSTEM_IN
    • NIS

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

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

      public static volatile String[] macs
      Cached for speed.
    • ID_CHARS

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

    • SUtil

      public SUtil()
  • Method Details

    • isVirtualExecutor

      public static final boolean isVirtualExecutor()
    • getExecutor

      public static final ExecutorService getExecutor()
      Returns the shared executor for starting new threads. Supports virtual threads if available.
      Returns:
      A shared executor.
    • getSecureRandom

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

      public static String[] getStringArray(String key, 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 Object joinArrays(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(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 Object cutArrays(Object a1, Object a2)
      Cut two arrays.
      Parameters:
      a1 - The first array.
      a2 - The second array.
      Returns:
      The cutted array.
    • substractArrays

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

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

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

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

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

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

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

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

      public static boolean equals(Object val1, Object val2)
    • arrayEmptyOrNull

      public static final boolean arrayEmptyOrNull(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(Object array1, 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(Object a)
      Calculate a hash code for an array.
    • arrayToString

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

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

      public static String getSingular(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 String getPlural(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(String a, String b)
      Compares two strings, ignoring case.
      Parameters:
      a - The first string.
      b - The second string.
      Returns:
      ainvalid input: '<'b => invalid input: '<'0
    • isInRange

      public static boolean isInRange(Date date, Date start, 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 String removeExtension(String fn)
      Remove file extension.
      Parameters:
      fn - The filename..
      Returns:
      filename without extension.
    • wrapText

      public static String wrapText(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 String wrapText(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 String makeConform(String input)
      Convert an output to html/wml conform presentation.
      Parameters:
      input - The input string.
      Returns:
      The converted output string.
    • makeConform

      public static String makeConform(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 String stripTags(String source)
      Strip tags (e.g. html) from a string, leaving only the text content.
    • makeEnglishConform

      public static String makeEnglishConform(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 String camelToSnakeCase(String camel)
      Convert CamelCase to snake_case.
    • snakeToCamelCase

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

      public 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. 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 String replace(String source, String old, 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 InputStream getResource(String name, ClassLoader classloader) throws 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:
      IOException - when the resource was not found.
    • getResource0

      public static InputStream getResource0(String name, 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(String name, 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(InputStream is, OutputStream os)
      Copy all data from input to output stream.
    • getDurationHMS

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

      public static String convertPathToPackage(String path, 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 List<URL> getClasspathURLs(ClassLoader classloader, boolean includebootpath)
      Get the current classpath as a list of URLs
    • collectClasspathURLs

      public static Set<URL> collectClasspathURLs(ClassLoader baseloader)
      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

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

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

      public static <T, E> List<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(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> 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> Set<T> createHashSet(T[] values)
      Create a hash set from values.
      Parameters:
      values - The values.
      Returns:
      The map.
    • createArrayList

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

      public static String createUniqueId()
      Create a securely generated, globally unique id with low collision probability.
      Returns:
      The id.
    • createUniqueId

      public static String createUniqueId(String name)
      Create a securely generated, globally unique id with low collision probability.
      Parameters:
      name - Name to include in the ID.
      Returns:
      The id.
    • createPlainRandomId

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

      protected static void testIntByteConversion()
    • convertPathToRelative

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

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

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

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

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

      public static URI toURI(URL url)
      Convert a URL to a URI but ignore exceptions
    • toURI

      public static URI toURI(String scheme, 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 URI toURI(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 File toFile(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 File toFile0(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 RuntimeException convertToRuntimeException(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(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(String[] args)
    • formatByteSize

      public static 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 InetAddress getNetworkIp(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 String bytesToString(long bytes)
      Get bytes as human readable string.
    • getClassFileLocation

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

      public static String convertURLToString(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(String url, List<String> urlstrings)
      Test if a file name is contained.
    • urlToFile

      public static File urlToFile(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 String intern(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 URL[] removeSystemUrls(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 String dateToIso8601(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 Date dateFromIso8601(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 OutputStream getOutForSystemIn() throws 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:
      IOException
    • getInet4Address

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

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

      public static 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(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 List<InetAddress> getNetworkIps()
      Get the network ips.
    • copyArray

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

      public static String getCodeSource(String filename, 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(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 List<NetworkInterface> getNetworkInterfaces() throws SocketException
      Get the network interfaces. The result is cached for a short time period to speed things up.
      Throws:
      SocketException
    • getNetworkAddresses

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

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

      public static boolean deleteDirectory(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 File getHomeDirectory()
      Get the home directory.
    • getDefaultDirectory

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

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

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

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

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

      public static String getDisplayName(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 String escapeString(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 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 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 invalid input: '<' 0.
      Returns:
      A list of byte arrays representing the original set.
    • hex

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

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

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

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

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

      public static 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(String data)
      Decodes a Base16-encoded String and returns the data.
      Parameters:
      data - The encoded data.
      Returns:
      The decoded data.
    • escapeLineBreaks

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

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

      public static String[] splitCommandline(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 File getFile(URL url)
      Get the file from an URL.
      Parameters:
      url - The file URL.
      Returns:
      The file.
    • copyFile

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

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

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

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

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

      public static void readStream(byte[] buf, 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, 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, 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, skipinvalid input: '<'=0 for no skip.
    • readStreamLines

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

      public static String[] readStreamLines(InputStream is, 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(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 Object noExRet(SUtil.NoExSupplier r)
      Run code ignoring exceptions.
      Parameters:
      r - Expression whose exceptions are ignored.
    • close

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

      public static String getStackTrace(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(String filename)
      Compute a file hash.
      Parameters:
      filename - The filename.
      Returns:
      The hash.
    • computeFileHash

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

      public static String firstToUpperCase(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 String getMacAddress()
      Get the mac address.
      Returns:
      The mac address.
    • getMacAddresses

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

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

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

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

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

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

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

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

      public static String removeBOM(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 String toUTF8(byte[] bytes)
      Returns a UTF8 byte array as string.
      Parameters:
      bytes - The bytes.
      Returns:
      The string.
    • getExceptionStacktrace

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

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

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

      public static 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(String s)
      Test if a string contains a digit.
      Parameters:
      s - The string.
      Returns:
      True, if the string contains a digit.
    • hashDirectory

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

      protected static void hashStream(InputStream is, MessageDigest md) throws Exception
      Throws:
      Exception
    • writeDirectory

      public static void writeDirectory(File dir, OutputStream out)
      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

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

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

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

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

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

      public static final String getStackTraceString(String topline, 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.
    • findDirForProject

      public static File findDirForProject(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(String s)
      Generate a diffuse string hash.
      Parameters:
      s - The string.
      Returns:
      The hash.
    • inndexOfLastUpperCaseCharacter

      public static int inndexOfLastUpperCaseCharacter(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 String replaceLast(String string, String toreplace, 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 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

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