Package org.infinispan.commons.util
Class Util
- java.lang.Object
-
- org.infinispan.commons.util.Util
-
public final class Util extends Object
General 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_ARRAY
static byte[][]
EMPTY_BYTE_ARRAY_ARRAY
static Object[]
EMPTY_OBJECT_ARRAY
static String[]
EMPTY_STRING_ARRAY
static String
GENERIC_JBOSS_MARSHALLING_CLASS
static int
HEX_DUMP_LIMIT
static String
JBOSS_USER_MARSHALLER_CLASS
-
Method Summary
All Methods Static Methods Concrete Methods Deprecated Methods Modifier and Type Method Description static void
addHexByte(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> 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(AutoCloseable cl)
static void
close(AutoCloseable... cls)
static void
close(Socket s)
static void
close(Context ctx)
static Runnable
composeWithExceptions(Runnable a, 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 Double
constructDouble(Class<?> type, Object o)
static long
currentMillisFromNanotime()
System.nanoTime()
is less expensive thanSystem.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(ObjectOutput o)
static void
flushAndCloseStream(OutputStream o)
static String
formatString(Object message, Object... params)
static ClassLoader[]
getClassLoaders(ClassLoader appClassLoader)
static <T> T
getInstance(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(String classname, ClassLoader cl)
Instantiates a class based on the class name provided.static <T> T
getInstanceStrict(Class<T> clazz)
Similar togetInstance(Class)
except that exceptions are propagated to the caller.static <T> T
getInstanceStrict(String classname, ClassLoader cl)
Similar togetInstance(String, ClassLoader)
except that exceptions are propagated to the caller.static <T> Supplier<T>
getInstanceSupplier(Class<T> klass)
static <T> Supplier<T>
getInstanceSupplier(String className, ClassLoader classLoader)
static Marshaller
getJBossMarshaller(ClassLoader classLoader, ClassWhiteList classWhiteList)
static int
getNormalizedHash(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 InputStream
getResourceAsStream(String resourcePath, ClassLoader userClassLoader)
static String
getResourceAsString(String resourcePath, ClassLoader userClassLoader)
static Throwable
getRootCause(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 String
hexDump(byte[] data)
static String
hexDump(byte[] buffer, int actualLength)
static String
hexDump(ByteBuffer buffer)
static String
hexIdHashCode(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(Class<?> type)
static boolean
isIBMJavaVendor()
static boolean
isOSGiContext()
Deprecated.Since 10.1, OSGi support is deprecated and will be removed in a future version.static String
join(List<String> strings, String separator)
static <T> Class<T>
loadClass(String classname, ClassLoader cl)
Loads the specified class using the passed classloader, or, if it isnull
the Infinispan classes' classloader.static <T> Class<T>
loadClassStrict(String classname, ClassLoader userClassLoader)
Loads the specified class using the passed classloader, or, if it isnull
the Infinispan classes' classloader.static void
longToBytes(long val, byte[] array, int offset)
static <T> T
newInstanceOrNull(Class<T> clazz, Class[] parameterTypes, Object... arguments)
Instantiates a class by invoking the constructor that matches the provided parameter types passing the given arguments.static Object[]
objectArray(int length)
static String
padString(String s, int minWidth)
static String
prettyPrintSubject(Subject subject)
PrintsSubject
's principals as a one-liner (as opposed to default Subject'stoString()
method, which prints every principal on separate line).static String
prettyPrintTime(long millis)
Prints a time for displaystatic String
prettyPrintTime(long time, TimeUnit unit)
static String
printArray(byte[] array)
static String
printArray(byte[] array, boolean withHash)
static String
read(InputStream is)
Reads the given InputStream fully, closes the stream and returns the result as a String.static byte[]
readStream(InputStream is)
Reads the given InputStream fully, closes the stream and returns the result as a byte array.static void
recursiveDirectoryCopy(Path source, Path target)
static void
recursiveFileRemove(File directory)
Deletes directory recursively.static void
recursiveFileRemove(String directoryName)
Deletes directory recursively.static void
renameTempFile(File tempFile, File lockFile, File dstFile)
static <T> T
requireNonNullElse(T obj, T defaultObj)
static CacheException
rewrapAsCacheException(Throwable t)
static boolean
safeEquals(Object a, Object b)
Null-safe equality test.static String[]
stringArray(int length)
static String
threadDump()
static UUID
threadLocalRandomUUID()
Uses aThreadLocalRandom
to generate a UUID.static char[]
toCharArray(String s)
static String
toHexString(byte[] input)
static String
toHexString(byte[] input, int limit)
static String
toHexString(byte[] input, int offset, int limit)
static String
toStr(Object o)
static <E> String
toStr(Collection<E> collection)
static String
unicodeEscapeString(String s)
static String
unicodeUnescapeString(String s)
static String
xmlify(String s)
-
-
-
Field Detail
-
HEX_DUMP_LIMIT
public static final int HEX_DUMP_LIMIT
-
EMPTY_OBJECT_ARRAY
public static final Object[] EMPTY_OBJECT_ARRAY
-
EMPTY_STRING_ARRAY
public static final 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 String GENERIC_JBOSS_MARSHALLING_CLASS
- See Also:
- Constant Field Values
-
JBOSS_USER_MARSHALLER_CLASS
public static final String JBOSS_USER_MARSHALLER_CLASS
- See Also:
- Constant Field Values
-
-
Method Detail
-
loadClass
public static <T> Class<T> loadClass(String classname, 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
orNoClassDefFoundError
is wrapped as aCacheConfigurationException
and 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
@Deprecated public static boolean isOSGiContext()
Deprecated.Since 10.1, OSGi support is deprecated and will be removed in a future version.Tries to determine if the code is running in an OSGi context.- Returns:
- true if an OSGi context is detected
-
getClassLoaders
public static ClassLoader[] getClassLoaders(ClassLoader appClassLoader)
-
loadClassStrict
public static <T> Class<T> loadClassStrict(String classname, ClassLoader userClassLoader) throws 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 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:
ClassNotFoundException
- if the class cannot be loaded
-
getResourceAsStream
public static InputStream getResourceAsStream(String resourcePath, ClassLoader userClassLoader)
-
getResourceAsString
public static String getResourceAsString(String resourcePath, ClassLoader userClassLoader) throws IOException
- Throws:
IOException
-
newInstanceOrNull
public static <T> T newInstanceOrNull(Class<T> clazz, Class[] parameterTypes, 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 aCacheConfigurationException
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(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 aCacheConfigurationException
and rethrown.- Parameters:
clazz
- class to instantiate- Returns:
- an instance of the class
-
getInstanceStrict
public static <T> T getInstanceStrict(Class<T> clazz) throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException
Similar togetInstance(Class)
except that exceptions are propagated to the caller.- Parameters:
clazz
- class to instantiate- Returns:
- an instance of the class
- Throws:
IllegalAccessException
InstantiationException
NoSuchMethodException
InvocationTargetException
-
getInstance
public static <T> T getInstance(String classname, 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(String classname, ClassLoader cl) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
Similar togetInstance(String, ClassLoader)
except that exceptions are propagated to the caller.- Parameters:
classname
- class to instantiate- Returns:
- an instance of classname
- Throws:
ClassNotFoundException
InstantiationException
IllegalAccessException
NoSuchMethodException
InvocationTargetException
-
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 Runnable composeWithExceptions(Runnable a, 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(Object a, 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.
-
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 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(InputStream is) throws 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:
IOException
- in case of stream read errors
-
read
public static String read(InputStream is) throws 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:
IOException
- in case of stream read errors
-
close
public static void close(AutoCloseable cl)
-
close
public static void close(Socket s)
-
close
public static void close(AutoCloseable... cls)
-
close
public static void close(Context ctx)
-
flushAndCloseStream
public static void flushAndCloseStream(OutputStream o)
-
flushAndCloseOutput
public static void flushAndCloseOutput(ObjectOutput o)
-
toStr
public static <E> String toStr(Collection<E> collection)
-
printArray
public static String printArray(byte[] array)
-
printArray
public static String printArray(byte[] array, boolean withHash)
-
toHexString
public static String toHexString(byte[] input)
-
toHexString
public static String toHexString(byte[] input, int limit)
-
toHexString
public static String toHexString(byte[] input, int offset, int limit)
-
threadDump
public static String threadDump()
-
rewrapAsCacheException
public static CacheException rewrapAsCacheException(Throwable t)
-
asSet
@SafeVarargs public static <T> Set<T> asSet(T... a)
-
hexIdHashCode
public static String hexIdHashCode(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 String hexDump(byte[] data)
-
hexDump
public static String hexDump(ByteBuffer buffer)
-
hexDump
public static String hexDump(byte[] buffer, int actualLength)
-
addHexByte
public static void addHexByte(StringBuilder buf, byte b)
-
getNormalizedHash
public static int getNormalizedHash(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()
-
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 String prettyPrintSubject(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 UUID threadLocalRandomUUID()
Uses aThreadLocalRandom
to generate a UUID. Faster, but not secure
-
getInstanceSupplier
public static <T> Supplier<T> getInstanceSupplier(String className, ClassLoader classLoader)
-
recursiveFileRemove
public static void recursiveFileRemove(String directoryName)
Deletes directory recursively.- Parameters:
directoryName
- Directory to be deleted
-
recursiveFileRemove
public static void recursiveFileRemove(File directory)
Deletes directory recursively.- Parameters:
directory
- Directory to be deleted
-
recursiveDirectoryCopy
public static void recursiveDirectoryCopy(Path source, Path target) throws IOException
- Throws:
IOException
-
isBasicType
public static boolean isBasicType(Class<?> type)
-
toCharArray
public static char[] toCharArray(String s)
-
objectArray
public static Object[] objectArray(int length)
-
stringArray
public static String[] stringArray(int length)
-
renameTempFile
public static void renameTempFile(File tempFile, File lockFile, File dstFile) throws IOException
- Throws:
IOException
-
getJBossMarshaller
public static Marshaller getJBossMarshaller(ClassLoader classLoader, ClassWhiteList classWhiteList)
-
requireNonNullElse
public static <T> T requireNonNullElse(T obj, T defaultObj)
-
longToBytes
public static void longToBytes(long val, byte[] array, int offset)
-
-