Package org.infinispan.commons.util
Class Util
- java.lang.Object
-
- org.infinispan.commons.util.Util
-
public final class Util extends java.lang.ObjectGeneral utility methods used throughout the Infinispan code base.- Since:
- 4.0
- Author:
- Brian Stansberry, Galder ZamarreƱo
-
-
Field Summary
Fields Modifier and Type Field Description static byte[]EMPTY_BYTE_ARRAYstatic byte[][]EMPTY_BYTE_ARRAY_ARRAYstatic java.lang.Object[]EMPTY_OBJECT_ARRAYstatic java.lang.String[]EMPTY_STRING_ARRAYstatic java.lang.StringGENERIC_JBOSS_MARSHALLING_CLASSstatic java.lang.StringJBOSS_USER_MARSHALLER_CLASS
-
Method Summary
All Methods Static Methods Concrete Methods Modifier and Type Method Description static voidaddHexByte(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 elementsstatic <T> java.util.Set<T>asSet(T... a)static <T> TcloneWithMarshaller(Marshaller marshaller, T x)Clones parameter x of type T with a given Marshaller reference;static voidclose(java.lang.AutoCloseable cl)static voidclose(java.lang.AutoCloseable... cls)static voidclose(java.net.Socket s)static voidclose(javax.naming.Context ctx)static java.lang.RunnablecomposeWithExceptions(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.DoubleconstructDouble(java.lang.Class<?> type, java.lang.Object o)static longcurrentMillisFromNanotime()System.nanoTime()is less expensive thanSystem.currentTimeMillis()and better suited to measure time intervals.static intfindNextHighestPowerOfTwo(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 voidflushAndCloseOutput(java.io.ObjectOutput o)static voidflushAndCloseStream(java.io.OutputStream o)static java.lang.StringformatString(java.lang.Object message, java.lang.Object... params)static java.lang.ClassLoader[]getClassLoaders(java.lang.ClassLoader appClassLoader)static <T> TgetInstance(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> TgetInstance(java.lang.String classname, java.lang.ClassLoader cl)Instantiates a class based on the class name provided.static <T> TgetInstanceStrict(java.lang.Class<T> clazz)Similar togetInstance(Class)except that exceptions are propagated to the caller.static <T> TgetInstanceStrict(java.lang.String classname, java.lang.ClassLoader cl)Similar togetInstance(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 MarshallergetJBossMarshaller(java.lang.ClassLoader classLoader, ClassWhiteList classWhiteList)static intgetNormalizedHash(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.InputStreamgetResourceAsStream(java.lang.String resourcePath, java.lang.ClassLoader userClassLoader)static java.lang.StringgetResourceAsString(java.lang.String resourcePath, java.lang.ClassLoader userClassLoader)static java.lang.ThrowablegetRootCause(java.lang.Throwable re)static intgetSegmentSize(int numSegments)Returns the size of each segment, given a number of segments.static inthashCode(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.StringhexDump(byte[] buffer)static java.lang.StringhexDump(java.nio.ByteBuffer buffer)static java.lang.StringhexIdHashCode(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 booleanisBasicType(java.lang.Class<?> type)static booleanisIBMJavaVendor()static booleanisOSGiContext()Tries to determine if the code is running in an OSGi context.static java.lang.Stringjoin(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 isnullthe 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 isnullthe Infinispan classes' classloader.static <T> TnewInstanceOrNull(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.StringpadString(java.lang.String s, int minWidth)static java.lang.StringprettyPrintSubject(javax.security.auth.Subject subject)PrintsSubject's principals as a one-liner (as opposed to default Subject'stoString()method, which prints every principal on separate line).static java.lang.StringprettyPrintTime(long millis)Prints a time for displaystatic java.lang.StringprettyPrintTime(long time, java.util.concurrent.TimeUnit unit)static java.lang.StringprintArray(byte[] array)static java.lang.StringprintArray(byte[] array, boolean withHash)static java.lang.Stringread(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 voidrecursiveDirectoryCopy(java.nio.file.Path source, java.nio.file.Path target)static voidrecursiveFileRemove(java.io.File directory)Deletes directory recursively.static voidrecursiveFileRemove(java.lang.String directoryName)Deletes directory recursively.static voidrenameTempFile(java.io.File tempFile, java.io.File lockFile, java.io.File dstFile)static <T> TrequireNonNullElse(T obj, T defaultObj)static CacheExceptionrewrapAsCacheException(java.lang.Throwable t)static booleansafeEquals(java.lang.Object a, java.lang.Object b)Null-safe equality test.static java.lang.String[]stringArray(int length)static java.lang.StringthreadDump()static java.util.UUIDthreadLocalRandomUUID()Uses aThreadLocalRandomto generate a UUID.static char[]toCharArray(java.lang.String s)static java.lang.StringtoHexString(byte[] input)static java.lang.StringtoHexString(byte[] input, int limit)static java.lang.StringtoHexString(byte[] input, int offset, int limit)static java.lang.StringtoStr(java.lang.Object o)static <E> java.lang.StringtoStr(java.util.Collection<E> collection)static java.lang.StringunicodeEscapeString(java.lang.String s)static java.lang.StringunicodeUnescapeString(java.lang.String s)static java.lang.Stringxmlify(java.lang.String s)
-
-
-
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
nullthe 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
ClassNotFoundExceptionorNoClassDefFoundErroris wrapped as aCacheConfigurationExceptionand is re-thrown.- Parameters:
classname- name of the class to loadcl- 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.ClassNotFoundExceptionLoads the specified class using the passed classloader, or, if it is
nullthe 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 loaduserClassLoader- 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 aCacheConfigurationExceptionand 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 aCacheConfigurationExceptionand 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.InstantiationExceptionSimilar togetInstance(Class)except that exceptions are propagated to the caller.- Parameters:
clazz- class to instantiate- Returns:
- an instance of the class
- Throws:
java.lang.IllegalAccessExceptionjava.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 aCacheConfigurationException.- 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.IllegalAccessExceptionSimilar togetInstance(String, ClassLoader)except that exceptions are propagated to the caller.- Parameters:
classname- class to instantiate- Returns:
- an instance of classname
- Throws:
java.lang.ClassNotFoundExceptionjava.lang.InstantiationExceptionjava.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 compareb- 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 thanSystem.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.IOExceptionReads 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.IOExceptionReads 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 hashhashFct- 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)
PrintsSubject's principals as a one-liner (as opposed to default Subject'stoString()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 aThreadLocalRandomto 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)
-
requireNonNullElse
public static <T> T requireNonNullElse(T obj, T defaultObj)
-
-