public abstract class Misc extends Object
| Modifier and Type | Class and Description |
|---|---|
static class |
Misc.NullCheckResult
Represents null value returned by
findNull(Object...). |
| Modifier and Type | Field and Description |
|---|---|
static long |
DAY
Number of milleseconds in a given day
|
static String |
LINE_SEPARATOR
The line separator as defined by the property
line.separator. |
static Random |
RANDOM
A RANDOM instance.
|
static File |
TMP_DIR
The file that represents the temporary directory.
|
| Modifier and Type | Method and Description |
|---|---|
static void |
badStateIfEquals(Object a,
Object b,
String msg)
This method throw an IllegalStateException if the given parameters are
equals (using
Object.equals(Object) |
static void |
badStateIfFalse(boolean valueToCheck,
String msg)
This method throw an IllegalStateException if the given parameter is false
|
static void |
badStateIfNotNull(Object valueToCheck,
String msg)
This method throw an IllegalStateException if the given parameter is not
null
|
static void |
badStateIfNull(Object valueToCheck,
String msg)
This method throw an IllegalStateException if the given parameter is null
|
static void |
badStateIfTrue(boolean valueToCheck,
String msg)
This method throw an IllegalStateException if the given parameter is true
|
static void |
checkArgsNotNull(int offset,
Object... params)
Check that the given parameters are not null.
|
static void |
checkArgsNotNull(Object... params)
Check that the given parameters are not null.
|
static <T extends Serializable> |
checkReallySerializable(T object)
Check that the given object is actually serializable.
|
static Exception |
close(Closeable closeable)
Equivalent to
#reflectClose(closeable) |
static Exception |
close(XMLDecoder decoder)
Equivalent to {@link #reflectClose(decoder)
|
static Exception |
close(XMLEncoder encoder)
Equivalent to {@link #reflectClose(encoder)
|
static String |
componentsToString(Object[] args,
boolean deepToString)
Smart toString() implementation of arrays.
|
static LogRecord |
createLogRecord(Logger logger,
Level level,
String className,
String methodName,
String msg,
Object... args)
This method creates a
LogRecord and fills it with the given
parameters |
static File |
createTempFile(String prefix,
String suffix,
File directory)
Perform java.io.File.createTempFile with retries when it fail (limit of 10
retries) (Use to by-pass bug #6325169 on SUN JDK 1.5 on windows) Sames
parameter as
File.createTempFile method |
static String |
deepToString(Object o) |
static boolean |
deleteDir(File dir)
Delete a given directory and all its contents (whether they are file or
directory)
WARNING: this method unconditionally modifies the underlying filesystem by
erasing files and directories.
|
static Serializable |
deserialize(byte[] buf) |
static void |
dynamicLog(int offset,
Level level,
String msg,
Object... args)
Log a message through the logger of the caller at the given offset in the
stack trace.
|
static void |
fastDynamicLog(int offset,
Logger logger,
Level level,
String msg,
Object... args)
Log a message through the given logger for the caller at the given offset
in the stack trace.
|
static void |
fastDynamicLog(Logger logger,
Level level,
String msg,
Object... args)
Equivalent to
{@link Misc#fastDynamicLog(int, Logger, Level, String, Object...)
|
static Set<Class<?>> |
findAllInterfaces(Class<?> type)
Return the list of
Class objects representing all interfaces a
given class implements. |
static Set<Class<?>> |
findAllSuperTypes(Class<?> type)
Return the list of
Class objects representing all super type a
given class implements. |
static Set<Class<?>> |
findAllTypes(Class<?> type)
Return the list of
Class objects representing every types a
given class implements. |
static Class<?>[] |
findConstructorClassArgs(Class<?>[] subClasses,
Class<?> classToTest)
Return the
Class[] array representing the types a constructor
take as parameters. |
static Class<?>[] |
findMethodClassArgs(Class<?>[] subClasses,
Class<?> classToTest,
String methodName)
Return the
Class[] array representing the types a given method
take as parameters. |
static Misc.NullCheckResult |
findNull(Object... params)
Find null parameters in the given list.
|
static String |
formatDelay(double delay)
Equivalent to
formatDelay(long). |
static String |
formatDelay(long delay)
Format a delay.
|
static byte[] |
generateJar(Class<?>... classes) |
static byte[] |
generateJar(Map<String,byte[]> resources)
Generates Jar from resources
|
static byte[] |
getAllContentFrom(File file)
Equivalent to
getAllContentFrom(new
FileInputStream(file)); |
static byte[] |
getAllContentFrom(InputSource source)
Equivalent to
getAllContentFrom(source.getByteStream(source)); |
static byte[] |
getAllContentFrom(InputStream in)
Return the whole underlying stream content into a single String.
|
static byte[] |
getAllContentFrom(Reader in)
Return the whole underlying stream content into a single String.
|
static byte[] |
getAllContentFrom(URL url)
Return the whole underlying stream content into a single String.
|
static StackTraceElement |
getCaller(int offset)
Return the StackTraceElement at the given offset from this method
invocation.
|
static <T> T |
getChainOf(List<T> elements)
Return a proxy that forward void-method invocations to
each object specified in the list
elements. |
static String |
getCurrentThreadStackTrace() |
static Map<String,byte[]> |
getDirContentFrom(File dir)
Get all files in this directory.
|
static String |
getGenericFullName(Class<?> clazz)
Return the generic name of a given class.
|
static long |
getHumanReadableId()
Generates a human readable id as a long.
|
static String |
getHumanReadableId(String prefix)
Generates a human readable id prefixed by the given String.
|
static <T> T |
getLoggerProxyFor(T target,
Logger logger)
Return a proxy that log method invocations through the provided logger.
|
static <T> T |
getMBeanProxy(Class<T> mbeanInterface,
String jmxServiceUrl,
String jmxObjectName)
Return a proxy implementing all the interfaces specified that forward
method invocations to the specified MBean.
|
static int |
getPermissionsSize(Permissions permissions) |
static String |
getRandomString(int size)
Generate a RANDOM String of the given size.
|
static Map<String,byte[]> |
getResources(Class<?>... classes) |
static Map<String,byte[]> |
getResourcesFromZip(byte[] zipContent) |
static StringBuilder |
getStackTraceFrom(StackTraceElement[] stes) |
static String |
getStackTraceFrom(Throwable t) |
static List<String> |
getStringFrom(Misc.NullCheckResult nullCheckResult,
String... names)
Return strings mapped to null values in a given @{link
Misc.NullCheckResult. . |
static String |
getUniqueId(String prefix)
Generate a unique identifier prefixed by the given String.
|
static String |
identityToString(Object o)
Return an "identity string" for a given object.
|
static <T> T |
lookup(String name,
Properties environment) |
static String |
prefixAllLines(String message,
String prefix)
Return a new string based on the given message string where all lines are
prefixed by the given prefix.
|
static String |
primitiveComponentsToString(Object array)
Smart toString() implementation of an array of primitive types.
|
static int |
random(int min,
int max)
Returns a random number between min and max value
|
static Exception |
reflectClose(Object o)
Invoke the close() method on the given object.
|
static byte[] |
serialize(Serializable object) |
static void |
slowLog(Level level,
String msg,
Object... args)
Equivalent to {@link Misc#dynamicLog(int, Level, String, Object...)
|
static <E extends Enum<E>> |
stringToEnum(Class<E> c,
String s) |
static void |
unreachableStatement() |
static void |
unreachableStatement(String reason) |
static void |
warnIfEquals(Level level,
Object a,
Object b)
This method logs at the given level a "warning" if the given parameter are
equals
|
static void |
warnIfFalse(Level level,
boolean valueToCheck,
String variableName)
This method logs at the given level a "warning" if the given parameter is
false
|
static void |
warnIfNotEquals(Level level,
Object a,
Object b)
This method logs at the given level a "warning" if the given parameter are
not equals
|
static void |
warnIfNotNull(Level level,
Object valueToCheck,
String variableName)
This method logs at the given level a "warning" if the given parameter is
not null
|
static void |
warnIfNull(Level level,
Object valueToCheck,
String variableName)
This method logs at the given level a "warning message" if the given
parameter is null
|
static void |
warnIfTrue(Level level,
boolean valueToCheck,
String variableName)
This method logs at the given level a "warning" if the given parameter is
true
|
static void |
write(byte[] fileContent,
File file) |
static void |
write(String s,
File f)
Write the given String to the given file using the default encoding.
|
public static final Random RANDOM
public static final String LINE_SEPARATOR
line.separator.public static final File TMP_DIR
public static final long DAY
public static String getUniqueId(String prefix)
prefix - the prefix StringprefixUUIDpublic static String getHumanReadableId(String prefix)
prefix - the string prefiyprefix.public static long getHumanReadableId()
public static int random(int min,
int max)
min - a positive integermax - a positive integerIllegalArgumentException - if min >= maxpublic static String getRandomString(int size)
size - the size of the generated stringpublic static final String formatDelay(long delay)
Format a delay.
This method returns a human readable string for delay such as the one used in benchmarks. This method is thread safe.
delay - a long valueString valuepublic static final String formatDelay(double delay)
Equivalent to formatDelay(long).
delay - a double valueString valuepublic static Set<Class<?>> findAllTypes(Class<?> type)
Return the list of Class objects representing every types a
given class implements.
type - a Class valueSet valuepublic static String getGenericFullName(Class<?> clazz)
clazz - the classpublic static Set<Class<?>> findAllSuperTypes(Class<?> type)
Return the list of Class objects representing all super type a
given class implements.
type - a Class valueSet valuepublic static Set<Class<?>> findAllInterfaces(Class<?> type)
Return the list of Class objects representing all interfaces a
given class implements.
type - a Class valueList valuepublic static Class<?>[] findMethodClassArgs(Class<?>[] subClasses, Class<?> classToTest, String methodName) throws NoSuchMethodException
Return the Class[] array representing the types a given method
take as parameters.
subClasses - the classes which are to be subclasses of parametersclassToTest - the class which declares the given methodmethodName - the method nameNoSuchMethodException - if a method cannot be found.public static Class<?>[] findConstructorClassArgs(Class<?>[] subClasses, Class<?> classToTest) throws NoSuchMethodException
Return the Class[] array representing the types a constructor
take as parameters.
subClasses - the classes which are to be subclasses of parametersclassToTest - the class which declares the constructorNoSuchMethodException - if a constructor cannot be foundpublic static String identityToString(Object o)
Return an "identity string" for a given object.
The string returned is:
"null" if o == null
- Otherwize,
o.getClass().getName() + "#" + System.identityHashCode(o)
o - the object to return the identity string ofpublic static String componentsToString(Object[] args, boolean deepToString)
Smart toString() implementation of arrays.
args - the array to return a smart string of.public static String primitiveComponentsToString(Object array)
Smart toString() implementation of an array of primitive types.
array - the array to return a smart string of.public static byte[] getAllContentFrom(File file) throws IOException
getAllContentFrom(new
FileInputStream(file));file - the file to readIOException - If an I/O exception occuredpublic static Map<String,byte[]> getDirContentFrom(File dir) throws IOException
dir - IOExceptionpublic static byte[] getAllContentFrom(InputSource source) throws IOException
getAllContentFrom(source.getByteStream(source));file - the file to readIOException - If an I/O exception occuredpublic static byte[] getAllContentFrom(URL url) throws IOException
in - the stream to readIOException - if an I/O exception occuredpublic static byte[] getAllContentFrom(InputStream in) throws IOException
in - the stream to readIOException - if an I/O exception occuredpublic static byte[] getAllContentFrom(Reader in) throws IOException
in - the stream to readIOException - if an I/O exception occuredpublic static Exception close(XMLEncoder encoder)
public static Exception close(XMLDecoder decoder)
public static Exception reflectClose(Object o)
LOG and returned. If the parameter is null,
nothing is done and null is returned.o - the object to call the close() method on.public static int getPermissionsSize(Permissions permissions)
permissions - public static <T> T getMBeanProxy(Class<T> mbeanInterface, String jmxServiceUrl, String jmxObjectName) throws IOException, MalformedObjectNameException, InstanceNotFoundException, MBeanException, ReflectionException
T - mbeanInterface - the interface the proxy should implement (the MBean
should obviously also implement that interface).jmxServiceUrl - the JMX service URLjmxObjectName - the name the MBean has been registered toIOException - for any IO problemMalformedObjectNameException - for any JMX Naming problemMBeanException - for any MBean problemReflectionException - for any problem related to reflectionInstanceNotFoundExceptionpublic static <T> T getChainOf(List<T> elements)
elements.
The invocation order follows the given list order.T - the interface type of the returned proxy and of each elements.elements - the elements to forward method invocations toChainer,
InvocationHandler,
Proxypublic static <T> T getLoggerProxyFor(T target,
Logger logger)
T - the target object typetarget - the target object method invocations should be forwarded tologger - the logger to use for loggingLoggingInvocationHandler,
InvocationHandler,
Proxypublic static Misc.NullCheckResult findNull(Object... params)
Misc.NullCheckResult.params - the parameters to checkMisc.NullCheckResult representing null parameters.Misc.NullCheckResultpublic static void checkArgsNotNull(Object... params)
params - the parameters to checkan - IllegalArgumentException if at least one of the parameters is
nullpublic static void checkArgsNotNull(int offset,
Object... params)
offset - the offset to use in the stack trace to produce error messageparams - the parameters to checkan - IllegalArgumentException if at least one of the parameters is
nullpublic static StackTraceElement getCaller(int offset)
offset - public static List<String> getStringFrom(Misc.NullCheckResult nullCheckResult, String... names)
Misc.NullCheckResult. .
If the returned @{link List} of String is called l then, it
verifies: l.contains(names[i]) if and only if
nullCheckResult.isNull(i) returns true.
Note that the number of String names given should be of the same size that
the one used to get the given Misc.NullCheckResult using
findNull(Object...). An IllegalArgumentException is thrown
otherwise.nullCheckResult - the result as returned by
findNull(Object...)names - the strings that should be mapped to null valuesMisc.NullCheckResult.IllegalArgumentException - if the number of given names is different
that NullCheckResult#size()findNull(Object...),
Misc.NullCheckResultpublic static void badStateIfNull(Object valueToCheck, String msg)
valueToCheck - the value to checkmsg - the message for the thrown exceptionIllegalStateExceptionpublic static void badStateIfNotNull(Object valueToCheck, String msg)
valueToCheck - the value to checkmsg - the message for the thrown exceptionIllegalStateExceptionpublic static void badStateIfTrue(boolean valueToCheck,
String msg)
valueToCheck - the value to checkmsg - the message for the thrown exceptionIllegalStateExceptionpublic static void badStateIfFalse(boolean valueToCheck,
String msg)
valueToCheck - the value to checkmsg - the message for the thrown exceptionIllegalStateExceptionpublic static void badStateIfEquals(Object a, Object b, String msg)
Object.equals(Object)a - the first objectb - the second objectmsg - the message for the thrown exceptionIllegalStateExceptionpublic static void dynamicLog(int offset,
Level level,
String msg,
Object... args)
A.f() calls B.g() that finally calls
dynamicLog(1, msg) then, the msg will be logged with a code
similar to: Logger.getLogger(B.getClass().getName()).log(level, msg);dynamicLog(2, msg) then, the code would be
similar to:Logger.getLogger(A.getClass().getName()).log(level, msg);String.format(String, Object...) is done only when
Logger.isLoggable(Level) returns true for efficiency reasons, this
method tries to find the caller (in order to get the Logger) using
string comparisons in the caller stack trace.fastDynamicLog(int, Logger, Level, String, Object...) where the
Logger is given directly.offset - the offset in the stack trace where the caller should be
found (to get the Logger)level - the level to log the message tomsg - the string to use when calling
String.format(String, Object...) in order to create the
final messageargs - the parameters to use when calling
String.format(String, Object...) in order to create the
final messagepublic static void slowLog(Level level, String msg, Object... args)
Misc.dynamicLog(2, level, msg, args)public static LogRecord createLogRecord(Logger logger, Level level, String className, String methodName, String msg, Object... args)
LogRecord and fills it with the given
parameterslogger - the logger to set the LogRecord.setLoggerName(String)
to.level - the level to set the LogRecord.setLevel(Level) to.className - the class name to set the
LogRecord.setSourceClassName(String) to.methodName - the method name to set the
LogRecord.setSourceMethodName(String) to.msg - the string to use when calling
String.format(String, Object...) in order to create the
message passed to LogRecord.setMessage(String).args - the parameters to use when calling
String.format(String, Object...) in order to create the
message passed to LogRecord.setMessage(String).public static void fastDynamicLog(int offset,
Logger logger,
Level level,
String msg,
Object... args)
dynamicLog(int, Level, String, Object...) except that it does
not have to search for the Logger. Therefore, it can check directly
the result of Logger.isLoggable(Level) preventing the call to
getCaller(int) (used to get the class name and the method name
of the caller) and to String.format(String, Object...) (to create
the actual message) which may be time consuming.offset - the offset in the stack trace where the caller should be
foundlevel - the level to log the message tomsg - the string to use when calling
String.format(String, Object...) in order to create the
final messageargs - the parameters to use when calling
String.format(String, Object...) in order to create the
final messagepublic static void fastDynamicLog(Logger logger, Level level, String msg, Object... args)
Misc.fastDynamicLog(2, logger, level, msg, args)public static void warnIfNull(Level level, Object valueToCheck, String variableName)
level - a log levelvalueToCheck - the value to checkvariableName - the variable name holding valueToCheck. Can be null.public static void warnIfNotNull(Level level, Object valueToCheck, String variableName)
level - a log levelvalueToCheck - the value to checkvariableName - the variable name holding valueToCheck. Can be null.public static void warnIfTrue(Level level, boolean valueToCheck, String variableName)
level - a log levelvalueToCheck - the value to checkvariableName - the variable name holding valueToCheck. Can be null.public static void warnIfFalse(Level level, boolean valueToCheck, String variableName)
level - a log levelvalueToCheck - the value to checkvariableName - the variable name holding valueToCheck. Can be null.public static void warnIfEquals(Level level, Object a, Object b)
level - a log levela - an objectb - another objectpublic static void warnIfNotEquals(Level level, Object a, Object b)
level - a log levela - an objectb - another objectpublic static String getCurrentThreadStackTrace()
public static StringBuilder getStackTraceFrom(StackTraceElement[] stes)
public static boolean deleteDir(File dir)
dir - the directory to deletepublic static void unreachableStatement()
public static void unreachableStatement(String reason)
public static byte[] serialize(Serializable object) throws IOException, ClassNotFoundException
IOExceptionClassNotFoundExceptionpublic static Serializable deserialize(byte[] buf) throws IOException, ClassNotFoundException
IOExceptionClassNotFoundExceptionpublic static <T extends Serializable> Exception checkReallySerializable(T object)
final Exception error = checkReallySerializable(myObject);
if (error == null) {
// success
} else {
// failure, do something with error...
error.printStackTrace();
}
T - A type (usually extending Serializableobject - the object to checkpublic static void write(String s, File f) throws IOException
s - the string to be writtenf - the file to write the given string toIOException - if an IO error is encoutered (file not found, read-only
file, and so on).public static void write(byte[] fileContent,
File file)
throws IOException
IOExceptionpublic static File createTempFile(String prefix, String suffix, File directory) throws IOException
File.createTempFile methodprefix - Prefix of the filesuffix - Suffix of the filedirectory - Target directoryIOException - If a file could not be createdpublic static byte[] generateJar(Class<?>... classes) throws IOException
IOExceptionpublic static Map<String,byte[]> getResources(Class<?>... classes) throws IOException
IOExceptionpublic static byte[] generateJar(Map<String,byte[]> resources) throws IOException
resources: - map of resources: key is the file name, value the
content.IOExceptionpublic static Map<String,byte[]> getResourcesFromZip(byte[] zipContent) throws IOException
IOExceptionpublic static <T> T lookup(String name, Properties environment) throws NamingException
NamingExceptionCopyright © 2011 OW2 Consortium. All Rights Reserved.