Class Util


  • public final class Util
    extends java.lang.Object
    General utility methods used throughout the Infinispan code base.
    Since:
    4.0
    Author:
    Brian Stansberry, Galder ZamarreƱo
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static void addHexByte​(java.lang.StringBuilder buf, byte b)  
      static <T> T[] arrayConcat​(T[] first, T[]... rest)
      Concatenates an arbitrary number of arrays returning a new array containing all elements
      static <T> java.util.Set<T> asSet​(T... a)  
      static <T> T cloneWithMarshaller​(Marshaller marshaller, T x)
      Clones parameter x of type T with a given Marshaller reference;
      static void close​(java.lang.AutoCloseable cl)  
      static void close​(java.lang.AutoCloseable... cls)  
      static void close​(java.net.Socket s)  
      static void close​(javax.naming.Context ctx)  
      static java.lang.Runnable composeWithExceptions​(java.lang.Runnable a, java.lang.Runnable b)
      Given two Runnables, return a Runnable that executes both in sequence, even if the first throws an exception, and if both throw exceptions, add any exceptions thrown by the second as suppressed exceptions of the first.
      static java.lang.Double constructDouble​(java.lang.Class<?> type, java.lang.Object o)  
      static long currentMillisFromNanotime()
      System.nanoTime() is less expensive than System.currentTimeMillis() and better suited to measure time intervals.
      static int findNextHighestPowerOfTwo​(int num)
      Returns a number such that the number is a power of two that is equal to, or greater than, the number passed in as an argument.
      static void flushAndCloseOutput​(java.io.ObjectOutput o)  
      static void flushAndCloseStream​(java.io.OutputStream o)  
      static java.lang.String formatString​(java.lang.Object message, java.lang.Object... params)  
      static java.lang.ClassLoader[] getClassLoaders​(java.lang.ClassLoader appClassLoader)  
      static <T> T getInstance​(java.lang.Class<T> clazz)
      Instantiates a class by first attempting a static factory method named getInstance() on the class and then falling back to an empty constructor.
      static <T> T getInstance​(java.lang.String classname, java.lang.ClassLoader cl)
      Instantiates a class based on the class name provided.
      static <T> T getInstanceStrict​(java.lang.Class<T> clazz)
      Similar to getInstance(Class) except that exceptions are propagated to the caller.
      static <T> T getInstanceStrict​(java.lang.String classname, java.lang.ClassLoader cl)
      Similar to getInstance(String, ClassLoader) except that exceptions are propagated to the caller.
      static <T> java.util.function.Supplier<T> getInstanceSupplier​(java.lang.Class<T> klass)  
      static <T> java.util.function.Supplier<T> getInstanceSupplier​(java.lang.String className, java.lang.ClassLoader classLoader)  
      static Marshaller getJBossMarshaller​(java.lang.ClassLoader classLoader, ClassWhiteList classWhiteList)  
      static int getNormalizedHash​(java.lang.Object object, Hash hashFct)
      Applies the given hash function to the hash code of a given object, and then normalizes it to ensure a positive value is always returned.
      static java.io.InputStream getResourceAsStream​(java.lang.String resourcePath, java.lang.ClassLoader userClassLoader)  
      static java.lang.String getResourceAsString​(java.lang.String resourcePath, java.lang.ClassLoader userClassLoader)  
      static java.lang.Throwable getRootCause​(java.lang.Throwable re)  
      static int getSegmentSize​(int numSegments)
      Returns the size of each segment, given a number of segments.
      static int hashCode​(byte[] bytes, int size)
      A function that calculates hash code of a byte array based on its contents but using the given size parameter as deliminator for the content.
      static java.lang.String hexDump​(byte[] buffer)  
      static java.lang.String hexDump​(java.nio.ByteBuffer buffer)  
      static java.lang.String hexIdHashCode​(java.lang.Object o)
      Prints the identity hash code of the object passed as parameter in an hexadecimal format in order to safe space.
      static boolean isBasicType​(java.lang.Class<?> type)  
      static boolean isIBMJavaVendor()  
      static boolean isOSGiContext()
      Tries to determine if the code is running in an OSGi context.
      static java.lang.String join​(java.util.List<java.lang.String> strings, java.lang.String separator)  
      static <T> java.lang.Class<T> loadClass​(java.lang.String classname, java.lang.ClassLoader cl)
      Loads the specified class using the passed classloader, or, if it is null the Infinispan classes' classloader.
      static <T> java.lang.Class<T> loadClassStrict​(java.lang.String classname, java.lang.ClassLoader userClassLoader)
      Loads the specified class using the passed classloader, or, if it is null the Infinispan classes' classloader.
      static <T> T newInstanceOrNull​(java.lang.Class<T> clazz, java.lang.Class[] parameterTypes, java.lang.Object... arguments)
      Instantiates a class by invoking the constructor that matches the provided parameter types passing the given arguments.
      static java.lang.Object[] objectArray​(int length)  
      static java.lang.String padString​(java.lang.String s, int minWidth)  
      static java.lang.String prettyPrintSubject​(javax.security.auth.Subject subject)
      Prints Subject's principals as a one-liner (as opposed to default Subject's toString() method, which prints every principal on separate line).
      static java.lang.String prettyPrintTime​(long millis)
      Prints a time for display
      static java.lang.String prettyPrintTime​(long time, java.util.concurrent.TimeUnit unit)  
      static java.lang.String printArray​(byte[] array)  
      static java.lang.String printArray​(byte[] array, boolean withHash)  
      static java.lang.String read​(java.io.InputStream is)
      Reads the given InputStream fully, closes the stream and returns the result as a String.
      static byte[] readStream​(java.io.InputStream is)
      Reads the given InputStream fully, closes the stream and returns the result as a byte array.
      static void recursiveDirectoryCopy​(java.nio.file.Path source, java.nio.file.Path target)  
      static void recursiveFileRemove​(java.io.File directory)
      Deletes directory recursively.
      static void recursiveFileRemove​(java.lang.String directoryName)
      Deletes directory recursively.
      static void renameTempFile​(java.io.File tempFile, java.io.File lockFile, java.io.File dstFile)  
      static CacheException rewrapAsCacheException​(java.lang.Throwable t)  
      static boolean safeEquals​(java.lang.Object a, java.lang.Object b)
      Null-safe equality test.
      static java.lang.String[] stringArray​(int length)  
      static java.lang.String threadDump()  
      static java.util.UUID threadLocalRandomUUID()
      Uses a ThreadLocalRandom to generate a UUID.
      static char[] toCharArray​(java.lang.String s)  
      static java.lang.String toHexString​(byte[] input)  
      static java.lang.String toHexString​(byte[] input, int limit)  
      static java.lang.String toHexString​(byte[] input, int offset, int limit)  
      static java.lang.String toStr​(java.lang.Object o)  
      static <E> java.lang.String toStr​(java.util.Collection<E> collection)  
      static java.lang.String unicodeEscapeString​(java.lang.String s)  
      static java.lang.String unicodeUnescapeString​(java.lang.String s)  
      static java.lang.String xmlify​(java.lang.String s)  
      • Methods inherited from class java.lang.Object

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

      • EMPTY_OBJECT_ARRAY

        public static final java.lang.Object[] EMPTY_OBJECT_ARRAY
      • EMPTY_STRING_ARRAY

        public static final java.lang.String[] EMPTY_STRING_ARRAY
      • EMPTY_BYTE_ARRAY

        public static final byte[] EMPTY_BYTE_ARRAY
      • EMPTY_BYTE_ARRAY_ARRAY

        public static final byte[][] EMPTY_BYTE_ARRAY_ARRAY
      • GENERIC_JBOSS_MARSHALLING_CLASS

        public static final java.lang.String GENERIC_JBOSS_MARSHALLING_CLASS
        See Also:
        Constant Field Values
      • JBOSS_USER_MARSHALLER_CLASS

        public static final java.lang.String JBOSS_USER_MARSHALLER_CLASS
        See Also:
        Constant Field Values
    • Method Detail

      • loadClass

        public static <T> java.lang.Class<T> loadClass​(java.lang.String classname,
                                                       java.lang.ClassLoader cl)

        Loads the specified class using the passed classloader, or, if it is null the Infinispan classes' classloader.

        If loadtime instrumentation via GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap classloader.

        If the class is not found, the ClassNotFoundException or NoClassDefFoundError is wrapped as a CacheConfigurationException and is re-thrown.

        Parameters:
        classname - name of the class to load
        cl - the application classloader which should be used to load the class, or null if the class is always packaged with Infinispan
        Returns:
        the class
        Throws:
        CacheConfigurationException - if the class cannot be loaded
      • isOSGiContext

        public static boolean isOSGiContext()
        Tries to determine if the code is running in an OSGi context.
        Returns:
        true if an OSGi context is detected
      • getClassLoaders

        public static java.lang.ClassLoader[] getClassLoaders​(java.lang.ClassLoader appClassLoader)
      • loadClassStrict

        public static <T> java.lang.Class<T> loadClassStrict​(java.lang.String classname,
                                                             java.lang.ClassLoader userClassLoader)
                                                      throws java.lang.ClassNotFoundException

        Loads the specified class using the passed classloader, or, if it is null the Infinispan classes' classloader.

        If loadtime instrumentation via GenerateInstrumentedClassLoader is used, this class may be loaded by the bootstrap classloader.

        Parameters:
        classname - name of the class to load
        userClassLoader - the application classloader which should be used to load the class, or null if the class is always packaged with Infinispan
        Returns:
        the class
        Throws:
        java.lang.ClassNotFoundException - if the class cannot be loaded
      • getResourceAsStream

        public static java.io.InputStream getResourceAsStream​(java.lang.String resourcePath,
                                                              java.lang.ClassLoader userClassLoader)
      • getResourceAsString

        public static java.lang.String getResourceAsString​(java.lang.String resourcePath,
                                                           java.lang.ClassLoader userClassLoader)
                                                    throws java.io.IOException
        Throws:
        java.io.IOException
      • newInstanceOrNull

        public static <T> T newInstanceOrNull​(java.lang.Class<T> clazz,
                                              java.lang.Class[] parameterTypes,
                                              java.lang.Object... arguments)
        Instantiates a class by invoking the constructor that matches the provided parameter types passing the given arguments. If no matching constructor is found this will return null. Note that the constructor must be public.

        Any exceptions encountered are wrapped in a CacheConfigurationException and rethrown.

        Type Parameters:
        T - the instance type
        Parameters:
        clazz - class to instantiate
        Returns:
        the new instance if a matching constructor was found otherwise null
      • getInstance

        public static <T> T getInstance​(java.lang.Class<T> clazz)
        Instantiates a class by first attempting a static factory method named getInstance() on the class and then falling back to an empty constructor.

        Any exceptions encountered are wrapped in a CacheConfigurationException and rethrown.

        Parameters:
        clazz - class to instantiate
        Returns:
        an instance of the class
      • getInstanceStrict

        public static <T> T getInstanceStrict​(java.lang.Class<T> clazz)
                                       throws java.lang.IllegalAccessException,
                                              java.lang.InstantiationException
        Similar to getInstance(Class) except that exceptions are propagated to the caller.
        Parameters:
        clazz - class to instantiate
        Returns:
        an instance of the class
        Throws:
        java.lang.IllegalAccessException
        java.lang.InstantiationException
      • getInstance

        public static <T> T getInstance​(java.lang.String classname,
                                        java.lang.ClassLoader cl)
        Instantiates a class based on the class name provided. Instantiation is attempted via an appropriate, static factory method named getInstance() first, and failing the existence of an appropriate factory, falls back to an empty constructor.

        Any exceptions encountered loading and instantiating the class is wrapped in a CacheConfigurationException.

        Parameters:
        classname - class to instantiate
        Returns:
        an instance of classname
      • getInstanceStrict

        public static <T> T getInstanceStrict​(java.lang.String classname,
                                              java.lang.ClassLoader cl)
                                       throws java.lang.ClassNotFoundException,
                                              java.lang.InstantiationException,
                                              java.lang.IllegalAccessException
        Similar to getInstance(String, ClassLoader) except that exceptions are propagated to the caller.
        Parameters:
        classname - class to instantiate
        Returns:
        an instance of classname
        Throws:
        java.lang.ClassNotFoundException
        java.lang.InstantiationException
        java.lang.IllegalAccessException
      • cloneWithMarshaller

        public static <T> T cloneWithMarshaller​(Marshaller marshaller,
                                                T x)
        Clones parameter x of type T with a given Marshaller reference;
        Returns:
        a deep clone of an object parameter x
      • composeWithExceptions

        public static java.lang.Runnable composeWithExceptions​(java.lang.Runnable a,
                                                               java.lang.Runnable b)
        Given two Runnables, return a Runnable that executes both in sequence, even if the first throws an exception, and if both throw exceptions, add any exceptions thrown by the second as suppressed exceptions of the first.
      • safeEquals

        public static boolean safeEquals​(java.lang.Object a,
                                         java.lang.Object b)
        Null-safe equality test.
        Parameters:
        a - first object to compare
        b - second object to compare
        Returns:
        true if the objects are equals or both null, false otherwise.
      • prettyPrintTime

        public static java.lang.String prettyPrintTime​(long time,
                                                       java.util.concurrent.TimeUnit unit)
      • currentMillisFromNanotime

        public static long currentMillisFromNanotime()
        System.nanoTime() is less expensive than System.currentTimeMillis() and better suited to measure time intervals. It's NOT suited to know the current time, for example to be compared with the time of other nodes.
        Returns:
        the value of System.nanoTime(), but converted in Milliseconds.
      • prettyPrintTime

        public static java.lang.String prettyPrintTime​(long millis)
        Prints a time for display
        Parameters:
        millis - time in millis
        Returns:
        the time, represented as millis, seconds, minutes or hours as appropriate, with suffix
      • readStream

        public static byte[] readStream​(java.io.InputStream is)
                                 throws java.io.IOException
        Reads the given InputStream fully, closes the stream and returns the result as a byte array.
        Parameters:
        is - the stream to read
        Returns:
        the read bytes
        Throws:
        java.io.IOException - in case of stream read errors
      • read

        public static java.lang.String read​(java.io.InputStream is)
                                     throws java.io.IOException
        Reads the given InputStream fully, closes the stream and returns the result as a String.
        Parameters:
        is - the stream to read
        Returns:
        the UTF-8 string
        Throws:
        java.io.IOException - in case of stream read errors
      • close

        public static void close​(java.lang.AutoCloseable cl)
      • close

        public static void close​(java.net.Socket s)
      • close

        public static void close​(java.lang.AutoCloseable... cls)
      • close

        public static void close​(javax.naming.Context ctx)
      • flushAndCloseStream

        public static void flushAndCloseStream​(java.io.OutputStream o)
      • flushAndCloseOutput

        public static void flushAndCloseOutput​(java.io.ObjectOutput o)
      • formatString

        public static java.lang.String formatString​(java.lang.Object message,
                                                    java.lang.Object... params)
      • toStr

        public static java.lang.String toStr​(java.lang.Object o)
      • toStr

        public static <E> java.lang.String toStr​(java.util.Collection<E> collection)
      • printArray

        public static java.lang.String printArray​(byte[] array)
      • printArray

        public static java.lang.String printArray​(byte[] array,
                                                  boolean withHash)
      • toHexString

        public static java.lang.String toHexString​(byte[] input)
      • toHexString

        public static java.lang.String toHexString​(byte[] input,
                                                   int limit)
      • toHexString

        public static java.lang.String toHexString​(byte[] input,
                                                   int offset,
                                                   int limit)
      • padString

        public static java.lang.String padString​(java.lang.String s,
                                                 int minWidth)
      • threadDump

        public static java.lang.String threadDump()
      • rewrapAsCacheException

        public static CacheException rewrapAsCacheException​(java.lang.Throwable t)
      • asSet

        @SafeVarargs
        public static <T> java.util.Set<T> asSet​(T... a)
      • hexIdHashCode

        public static java.lang.String hexIdHashCode​(java.lang.Object o)
        Prints the identity hash code of the object passed as parameter in an hexadecimal format in order to safe space.
      • hexDump

        public static java.lang.String hexDump​(byte[] buffer)
      • hexDump

        public static java.lang.String hexDump​(java.nio.ByteBuffer buffer)
      • addHexByte

        public static void addHexByte​(java.lang.StringBuilder buf,
                                      byte b)
      • constructDouble

        public static java.lang.Double constructDouble​(java.lang.Class<?> type,
                                                       java.lang.Object o)
      • getNormalizedHash

        public static int getNormalizedHash​(java.lang.Object object,
                                            Hash hashFct)
        Applies the given hash function to the hash code of a given object, and then normalizes it to ensure a positive value is always returned.
        Parameters:
        object - to hash
        hashFct - hash function to apply
        Returns:
        a non-null, non-negative normalized hash code for a given object
      • getSegmentSize

        public static int getSegmentSize​(int numSegments)
        Returns the size of each segment, given a number of segments.
        Parameters:
        numSegments - number of segments required
        Returns:
        the size of each segment
      • isIBMJavaVendor

        public static boolean isIBMJavaVendor()
      • join

        public static java.lang.String join​(java.util.List<java.lang.String> strings,
                                            java.lang.String separator)
      • findNextHighestPowerOfTwo

        public static int findNextHighestPowerOfTwo​(int num)
        Returns a number such that the number is a power of two that is equal to, or greater than, the number passed in as an argument. The smallest number returned will be 1. Due to having to be a power of two, the highest int this can return is 231 since int is signed.
      • hashCode

        public static int hashCode​(byte[] bytes,
                                   int size)
        A function that calculates hash code of a byte array based on its contents but using the given size parameter as deliminator for the content.
      • prettyPrintSubject

        public static java.lang.String prettyPrintSubject​(javax.security.auth.Subject subject)
        Prints Subject's principals as a one-liner (as opposed to default Subject's toString() method, which prints every principal on separate line).
      • arrayConcat

        @SafeVarargs
        public static <T> T[] arrayConcat​(T[] first,
                                          T[]... rest)
        Concatenates an arbitrary number of arrays returning a new array containing all elements
      • threadLocalRandomUUID

        public static java.util.UUID threadLocalRandomUUID()
        Uses a ThreadLocalRandom to generate a UUID. Faster, but not secure
      • unicodeEscapeString

        public static java.lang.String unicodeEscapeString​(java.lang.String s)
      • unicodeUnescapeString

        public static java.lang.String unicodeUnescapeString​(java.lang.String s)
      • getInstanceSupplier

        public static <T> java.util.function.Supplier<T> getInstanceSupplier​(java.lang.Class<T> klass)
      • getInstanceSupplier

        public static <T> java.util.function.Supplier<T> getInstanceSupplier​(java.lang.String className,
                                                                             java.lang.ClassLoader classLoader)
      • recursiveFileRemove

        public static void recursiveFileRemove​(java.lang.String directoryName)
        Deletes directory recursively.
        Parameters:
        directoryName - Directory to be deleted
      • recursiveFileRemove

        public static void recursiveFileRemove​(java.io.File directory)
        Deletes directory recursively.
        Parameters:
        directory - Directory to be deleted
      • recursiveDirectoryCopy

        public static void recursiveDirectoryCopy​(java.nio.file.Path source,
                                                  java.nio.file.Path target)
                                           throws java.io.IOException
        Throws:
        java.io.IOException
      • isBasicType

        public static boolean isBasicType​(java.lang.Class<?> type)
      • xmlify

        public static java.lang.String xmlify​(java.lang.String s)
      • toCharArray

        public static char[] toCharArray​(java.lang.String s)
      • objectArray

        public static java.lang.Object[] objectArray​(int length)
      • stringArray

        public static java.lang.String[] stringArray​(int length)
      • renameTempFile

        public static void renameTempFile​(java.io.File tempFile,
                                          java.io.File lockFile,
                                          java.io.File dstFile)
                                   throws java.io.IOException
        Throws:
        java.io.IOException
      • getRootCause

        public static java.lang.Throwable getRootCause​(java.lang.Throwable re)
      • getJBossMarshaller

        public static Marshaller getJBossMarshaller​(java.lang.ClassLoader classLoader,
                                                    ClassWhiteList classWhiteList)