Package org.infinispan.commons.util
Class Util
java.lang.Object
org.infinispan.commons.util.Util
General utility methods used throughout the Infinispan code base.
- Since:
- 4.0
- Author:
- Brian Stansberry, Galder ZamarreƱo
-
Nested Class Summary
Nested Classes -
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic voidaddHexByte(StringBuilder buf, byte b) static booleanarraysEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) This method is to be replaced by Java 9 Arrays#equals with the same arguments.static <T> Set<T>asSet(T... a) static voidclose(AutoCloseable cl) static voidclose(AutoCloseable... cls) static voidstatic voidstatic RunnableGiven 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 byte[]concat(byte[] a, byte[] b) static longSystem.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 StringformatString(Object message, Object... params) static ObjectfromString(Class klass, String value) static ClassLoader[]getClassLoaders(ClassLoader appClassLoader) static <T> TgetInstance(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(String classname, ClassLoader cl) Instantiates a class based on the class name provided.static <T> TgetInstanceStrict(Class<T> clazz) Similar togetInstance(Class)except that exceptions are propagated to the caller.static <T> TgetInstanceStrict(String classname, ClassLoader cl) Similar togetInstance(String, ClassLoader)except that exceptions are propagated to the caller.static <T> Supplier<T>getInstanceSupplier(String className, ClassLoader classLoader) static MarshallergetJBossMarshaller(ClassLoader classLoader, ClassAllowList classAllowList) static intgetNormalizedHash(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 InputStreamgetResourceAsStream(String resourcePath, ClassLoader userClassLoader) static StringgetResourceAsString(String resourcePath, ClassLoader userClassLoader) static Throwablestatic 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 StringhexDump(byte[] data) static StringhexDump(byte[] buffer, int offset, int actualLength) static StringhexDump(ByteBuffer buffer) static StringhexDump(Util.ByteGetter byteGetter, int offset, int actualLength) static StringPrints the identity hash code of the object passed as parameter in an hexadecimal format in order to safe space.static Stringstatic <T> Class<T>loadClass(String classname, ClassLoader cl) Loads the specified class using the passed classloader, or, if it isnullthe Infinispan classes' classloader.static <T> Class<T>loadClassStrict(String classname, ClassLoader userClassLoader) Loads the specified class using the passed classloader, or, if it isnullthe Infinispan classes' classloader.static voidlongToBytes(long val, byte[] array, int offset) static <T> TnewInstanceOrNull(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 Stringstatic booleanparseBoolean(String value) static <T extends Enum<T>>
Tstatic StringprettyPrintSubject(Subject subject) PrintsSubject's principals as a one-liner (as opposed to default Subject'stoString()method, which prints every principal on separate line).static StringprettyPrintTime(long millis) Prints a time for displaystatic StringprettyPrintTime(long time, TimeUnit unit) static StringprintArray(byte[] array) static StringprintArray(byte[] array, boolean withHash) static Stringread(InputStream is) Reads the given InputStream fully, closes the stream and returns the result as a String.static voidrecursiveDirectoryCopy(Path source, Path target) static voidrecursiveFileRemove(File directory) Deletes directory recursively.static voidrecursiveFileRemove(String directoryName) Deletes directory recursively.static voidrecursiveFileRemove(Path path) static voidrenameTempFile(File tempFile, File lockFile, File dstFile) static <T> TrequireNonNullElse(T obj, T defaultObj) static CacheExceptionstatic booleansafeEquals(Object a, Object b) Null-safe equality test.static String[]stringArray(int length) static Stringstatic UUIDUses aThreadLocalRandomto generate a UUID.static Throwable[]throwableArray(int length) static char[]static StringtoHexString(byte[] input) static StringtoHexString(byte[] input, int limit) static StringtoHexString(byte[] input, int offset, int limit) static Stringstatic <E> StringtoStr(Collection<E> collection) static RuntimeExceptionstatic Stringstatic Stringstatic Stringstatic Stringstatic voidunwrapSuppressed(Throwable t, Throwable t1)
-
Field Details
-
HEX_DUMP_LIMIT
public static final int HEX_DUMP_LIMIT -
EMPTY_OBJECT_ARRAY
-
EMPTY_STRING_ARRAY
-
EMPTY_THROWABLE_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
- See Also:
-
JBOSS_USER_MARSHALLER_CLASS
- See Also:
-
-
Method Details
-
loadClass
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
-
getClassLoaders
-
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
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:
ClassNotFoundException- if the class cannot be loaded
-
getResourceAsStream
-
getResourceAsString
public static String getResourceAsString(String resourcePath, ClassLoader userClassLoader) throws IOException - Throws:
IOException
-
newInstanceOrNull
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
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(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:
IllegalAccessExceptionInstantiationExceptionNoSuchMethodExceptionInvocationTargetException
-
getInstance
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:
ClassNotFoundExceptionInstantiationExceptionIllegalAccessExceptionNoSuchMethodExceptionInvocationTargetException
-
composeWithExceptions
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
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
-
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
Prints a time for display- Parameters:
millis- time in millis- Returns:
- the time, represented as millis, seconds, minutes or hours as appropriate, with suffix
-
read
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
-
close
-
close
-
close
-
formatString
-
toStr
-
toStr
-
printArray
-
printArray
-
toHexString
-
toHexString
-
toHexString
-
padString
-
threadDump
-
rewrapAsCacheException
-
asSet
-
hexIdHashCode
Prints the identity hash code of the object passed as parameter in an hexadecimal format in order to safe space. -
hexDump
-
hexDump
-
hexDump
-
hexDump
-
addHexByte
-
getNormalizedHash
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
-
join
-
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
PrintsSubject's principals as a one-liner (as opposed to default Subject'stoString()method, which prints every principal on separate line). -
threadLocalRandomUUID
Uses aThreadLocalRandomto generate a UUID. Faster, but not secure -
unicodeEscapeString
-
unicodeUnescapeString
-
getInstanceSupplier
-
recursiveFileRemove
Deletes directory recursively.- Parameters:
directoryName- Directory to be deleted
-
recursiveFileRemove
-
recursiveFileRemove
Deletes directory recursively.- Parameters:
directory- Directory to be deleted
-
recursiveDirectoryCopy
- Throws:
IOException
-
toCharArray
-
objectArray
-
stringArray
-
throwableArray
-
renameTempFile
- Throws:
IOException
-
getRootCause
-
getJBossMarshaller
-
requireNonNullElse
public static <T> T requireNonNullElse(T obj, T defaultObj) -
longToBytes
public static void longToBytes(long val, byte[] array, int offset) -
unquote
-
fromString
-
parseBoolean
-
parseEnum
-
unwrapSuppressed
-
unwrapExceptionMessage
-
arraysEqual
public static boolean arraysEqual(byte[] a, int aFromIndex, int aToIndex, byte[] b, int bFromIndex, int bToIndex) This method is to be replaced by Java 9 Arrays#equals with the same arguments.- Parameters:
a- first array to test contentsaFromIndex- the offset into the first array to start comparisonaToIndex- the last element (exclusive) of the first array to compareb- second array to test contentsbFromIndex- the offset into the second array to start comparisonbToIndex- the last element (exclusive) of the second array to compare- Returns:
- if the bytes in the two array ranges are equal
-
concat
public static byte[] concat(byte[] a, byte[] b) -
unchecked
-