Holger's
Java API

com.antelmann.util
Class Misc

java.lang.Object
  extended by com.antelmann.util.Misc

public final class Misc
extends Object

just some miscellaneous stuff for convenience that doesn't fit anywhere else

Author:
Holger Antelmann

Method Summary
static void addToSystemClassLoader(URL url)
          'hacks' the given URL into the system class loader
static
<T> ListRetriever<T>
asListRetriever(ValueRetriever<T> vr, String desc)
           
static Properties asProperties(ResourceBundle bundle)
           
static Runnable asRunnable(Task<?> task)
           
static Task<RuntimeException> asTask(Runnable r)
           
static int calculateEANChecksum(String codeWithoutCheckDigit)
          takes both: UPC and EAN codes; must be numeric only
static boolean checkEAN(String code)
          takes both: UPC and EAN codes; must be numeric only
static void clearClipboard()
           
static int compare(Object o1, Object o2)
           
static void copyToClipboard(Object obj)
           
static void copyToClipboard(Transferable tf)
           
static
<T> T
create(boolean enforceAccessability, Class<T> type, Object... params)
           
static
<T> T
create(Class<T> type, Object... params)
          calls create(boolean, Class, Object...) w/ true as the first parameter
static KeyPair generateKeyPair()
           
static KeyPair generateKeyPair(int keySize)
           
static KeyPair generateKeyPair(String algorithm, int keySize)
           
static String getConsoleInput()
          reads a line from the console and returns the keyboard input as a string after 'Enter' was pressed
static String getConsoleInput(String question)
          prints the given question and returns getConsoleInput()
static
<T> T[]
getConstants(Class<?> declaringType, Class<T> constantType)
           
static
<T extends Enum<T>>
PatternExtractor<Object,T>
getEnumExtractor(Class<T> type)
           
static String getMacAddress()
          returns the first MAC address found in a non-virtual network interface.
static String getMacAddress(InetAddress adr)
          returns the MAC address supported since java version 1.6
static Method getMainMethod(Class<?> c)
           
static
<T> Comparator<T>
getMethodComparator(Class<T> type, String methodName)
           
static
<T> Comparator<T>
getMethodComparator(Method method)
           
static PatternExtractor<Object,Object> getMethodExtractor(String methodName)
           
static
<T> PatternExtractor<Object,T>
getMethodExtractor(String methodName, Class<T> returnType)
           
static HashMap<String,Object> getMethodValues(Object obj)
          maps public non-static method names with no parameters and a non-void return value to their respective return values
static String getOption(String optionKey, String[] args)
          looks for the given option from a list of command line arguments.
static String getSimpleTypeName(Class<?> type)
           
static Object invoke(Object obj, boolean enforceAccessibility, String methodName, Object... params)
          attempts to invoke the given method with the given parameters on the given object via reflection.
static Object invoke(Object obj, String methodName, Object... params)
          calls invoke(obj, false, methodName, params)
static void invokeMain(Class<?> c, String... args)
           
static boolean isClassAvailable(String className)
          allows to test for the availability of the given class name w/o throwing an exception
static boolean isObjectIn(Object obj, Object... listOfObjects)
          uses same(Object, Object) to see whether the first parameter is equal to any of the other given
static URLClassLoader loadClasses(File... dirOrJar)
          preloads all classes found in the given directories and/or Jar files
static URLClassLoader loadClasses(Monitor monitor, File... dirOrJar)
          preloads all classes found in the given directories and/or Jar files
static URLClassLoader loadFromClassPath(Monitor mon, String path)
          preloads all classes found in the given path
static URLClassLoader loadFromClassPath(String path)
          preloads all classes found in the given path
static String macString(byte... bytes)
           
static String makeURLString(File file)
          generates a URL-like String of the form "file:///..
static void open(File file)
           
static void open(URL url)
           
static Object pasteFromClipboard()
           
static Object pasteFromClipboard(DataFlavor flavor)
           
static String pasteStringFromClipboard()
           
static void pause(long millisec)
          just simplifies a call to Thread.sleep()
static
<T> Filter<T>
reverseFilter(Filter<T> filter)
          returns an inversed filter to the given one
static void run(Task<?> task, boolean asynchronously)
          runs the given task (either within this or a new thread) while converting Exceptions to RuntimeExceptions if they happen
static boolean same(Object s1, Object s2)
          returns true only if the the both objects are equal or both null, false otherwise.
static Object setValue(Object obj, String fieldName, Object value)
           
static Process start(File workingDir, String... params)
          starts a given file and other parameters with the platform specific application.startCommand in the settings.
static Process start(String... params)
           
static boolean start(URL url)
          Deprecated. as of JDK 1.6, java.awt.Desktop can be used instead.
static
<I> I
synchronizeAccess(I instance, Class<I> type, Object semaphore)
          allows to synchronize all access to the given instance based on the given semaphore object.
static
<T> T
unsaveCast(Object t)
          allows to delegate an 'unsave' cast to this method so that the remainder of a calling method remains 'save' - provided that you know what your're doing here
static
<T> T
unwrap(Object obj, Class<T> targetType)
          employs the Wrapped interface to extract the given type from the given object if applicable
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

getConstants

public static <T> T[] getConstants(Class<?> declaringType,
                                   Class<T> constantType)

getEnumExtractor

public static <T extends Enum<T>> PatternExtractor<Object,T> getEnumExtractor(Class<T> type)

asTask

public static Task<RuntimeException> asTask(Runnable r)

asRunnable

public static Runnable asRunnable(Task<?> task)

run

public static void run(Task<?> task,
                       boolean asynchronously)
runs the given task (either within this or a new thread) while converting Exceptions to RuntimeExceptions if they happen

Parameters:
task - the task to be run; may be null
asynchronously - if true, the method returns immediately, while the task is performed on a new thread; if false, the task is performed directly before the method returns

asListRetriever

public static <T> ListRetriever<T> asListRetriever(ValueRetriever<T> vr,
                                                   String desc)

unwrap

public static <T> T unwrap(Object obj,
                           Class<T> targetType)
employs the Wrapped interface to extract the given type from the given object if applicable

See Also:
Wrapped, InterfaceWrapper.wrap(ClassLoader, Object, Object, Class)

unsaveCast

@Warning(value="you\'d better have a darn good reason to use this method")
public static <T> T unsaveCast(Object t)
                    throws ClassCastException
allows to delegate an 'unsave' cast to this method so that the remainder of a calling method remains 'save' - provided that you know what your're doing here

Throws:
ClassCastException

getConsoleInput

public static String getConsoleInput()
reads a line from the console and returns the keyboard input as a string after 'Enter' was pressed


getConsoleInput

public static String getConsoleInput(String question)
prints the given question and returns getConsoleInput()


loadFromClassPath

public static URLClassLoader loadFromClassPath(String path)
                                        throws IOException
preloads all classes found in the given path

Returns:
the ClassLoader created to load the classes
Throws:
IOException

loadFromClassPath

public static URLClassLoader loadFromClassPath(Monitor mon,
                                               String path)
                                        throws IOException
preloads all classes found in the given path

Parameters:
mon - allows to individually monitor the loading process
path - the path to load the classes from
Returns:
the ClassLoader created to load the classes
Throws:
IOException

loadClasses

public static URLClassLoader loadClasses(File... dirOrJar)
                                  throws IOException
preloads all classes found in the given directories and/or Jar files

Parameters:
dirOrJar - Jar files or directories that are to be loaded
Returns:
the ClassLoader created to load the classes
Throws:
IOException

loadClasses

public static URLClassLoader loadClasses(Monitor monitor,
                                         File... dirOrJar)
                                  throws IOException
preloads all classes found in the given directories and/or Jar files

Parameters:
monitor - allows to individually monitor the loading process
dirOrJar - Jar files or directories that are to be loaded
Returns:
the ClassLoader created to load the classes
Throws:
IOException

makeURLString

public static String makeURLString(File file)
                            throws IOException
generates a URL-like String of the form "file:///.." using its canonical path and adds a slash at the end if the given file is a directory

Throws:
IOException

reverseFilter

public static <T> Filter<T> reverseFilter(Filter<T> filter)
returns an inversed filter to the given one

See Also:
ComboFilter.negate(Filter)

getMethodComparator

public static <T> Comparator<T> getMethodComparator(Class<T> type,
                                                    String methodName)
                                         throws IllegalArgumentException
Throws:
IllegalArgumentException

getMethodComparator

public static <T> Comparator<T> getMethodComparator(Method method)

compare

public static int compare(Object o1,
                          Object o2)
See Also:
UniversalComparator.getDefaultInstance()

start

@Deprecated
public static boolean start(URL url)
Deprecated. as of JDK 1.6, java.awt.Desktop can be used instead.

This method attempts to start the given url with the associated default application (most likely a web-browser) by calling start urlPath. If this doesn't work, nothing happens; errors are ignored. The method uses the parameter application.startCommand from the Properties obtained from Settings.getProperties() to start the url. Note that a successful call to this method is platform dependent; you may have to adjust the application.startCommand parameter to make this work for your platform. The different command parts of the application.startCommand are separated by a tab (\t). The default value for this parameter shipped with the antelmann.jar file works for Windows NT/2000/XP.

Returns:
true if no exceptions were thrown, false otherwise
See Also:
Settings.getProperties()

open

public static void open(File file)
                 throws IOException
Throws:
IOException

open

public static void open(URL url)
                 throws IOException
Throws:
IOException

start

public static Process start(String... params)
                     throws IOException
Throws:
IOException

start

public static Process start(File workingDir,
                            String... params)
                     throws IOException
starts a given file and other parameters with the platform specific application.startCommand in the settings. The different command parts of the application.startCommand are separated by a tab (\t) and the given params are added to the command list.

Throws:
IOException
See Also:
Settings.getProperties()

pause

public static void pause(long millisec)
just simplifies a call to Thread.sleep()


asProperties

public static Properties asProperties(ResourceBundle bundle)

generateKeyPair

public static KeyPair generateKeyPair()

generateKeyPair

public static KeyPair generateKeyPair(int keySize)

generateKeyPair

public static KeyPair generateKeyPair(String algorithm,
                                      int keySize)
                               throws NoSuchAlgorithmException
Throws:
NoSuchAlgorithmException

isObjectIn

public static boolean isObjectIn(Object obj,
                                 Object... listOfObjects)
uses same(Object, Object) to see whether the first parameter is equal to any of the other given


same

public static boolean same(Object s1,
                           Object s2)
returns true only if the the both objects are equal or both null, false otherwise. ClassCastExceptions thrown during equals()-calls are caught and false returned.


clearClipboard

public static void clearClipboard()

pasteStringFromClipboard

public static String pasteStringFromClipboard()

pasteFromClipboard

public static Object pasteFromClipboard()

pasteFromClipboard

public static Object pasteFromClipboard(DataFlavor flavor)

copyToClipboard

public static void copyToClipboard(Object obj)

copyToClipboard

public static void copyToClipboard(Transferable tf)

getMethodExtractor

public static PatternExtractor<Object,Object> getMethodExtractor(String methodName)

getMethodExtractor

public static <T> PatternExtractor<Object,T> getMethodExtractor(String methodName,
                                                                Class<T> returnType)

getMacAddress

public static String getMacAddress()
                            throws UnknownHostException,
                                   SocketException
returns the first MAC address found in a non-virtual network interface. Supported since java version 1.6.

Throws:
UnknownHostException
SocketException
See Also:
NetworkInterface.getHardwareAddress()

getMacAddress

public static String getMacAddress(InetAddress adr)
                            throws UnknownHostException,
                                   SocketException
returns the MAC address supported since java version 1.6

Throws:
UnknownHostException
SocketException
See Also:
InetAddress.getLocalHost(), NetworkInterface.getHardwareAddress()

macString

public static String macString(byte... bytes)

create

public static <T> T create(Class<T> type,
                           Object... params)
                throws InstantiationException,
                       IllegalAccessException,
                       InvocationTargetException,
                       NoSuchMethodException
calls create(boolean, Class, Object...) w/ true as the first parameter

Throws:
InstantiationException
IllegalAccessException
InvocationTargetException
NoSuchMethodException

create

@Warning(value="takes the first available constructor, which may not be the best due to overloading if no exact match was found at first")
public static <T> T create(boolean enforceAccessability,
                                        Class<T> type,
                                        Object... params)
                throws InstantiationException,
                       IllegalAccessException,
                       InvocationTargetException,
                       NoSuchMethodException
Throws:
InstantiationException
IllegalAccessException
InvocationTargetException
NoSuchMethodException

invoke

public static Object invoke(Object obj,
                            String methodName,
                            Object... params)
                     throws IllegalAccessException,
                            InvocationTargetException,
                            NoSuchMethodException
calls invoke(obj, false, methodName, params)

Throws:
IllegalAccessException
InvocationTargetException
NoSuchMethodException

invoke

@Warning(value="takes the first available method, which may not be the best due to overloading if no exact match was found at first")
public static Object invoke(Object obj,
                                         boolean enforceAccessibility,
                                         String methodName,
                                         Object... params)
                     throws IllegalAccessException,
                            InvocationTargetException,
                            NoSuchMethodException
attempts to invoke the given method with the given parameters on the given object via reflection.

Throws:
IllegalAccessException
InvocationTargetException
NoSuchMethodException

invokeMain

public static void invokeMain(Class<?> c,
                              String... args)
                       throws NoSuchMethodException,
                              InvocationTargetException,
                              IllegalAccessException
Throws:
NoSuchMethodException
InvocationTargetException
IllegalAccessException

getMainMethod

public static Method getMainMethod(Class<?> c)
                            throws NoSuchMethodException
Throws:
NoSuchMethodException

getMethodValues

public static HashMap<String,Object> getMethodValues(Object obj)
                                              throws IllegalAccessException,
                                                     InvocationTargetException
maps public non-static method names with no parameters and a non-void return value to their respective return values

Throws:
IllegalAccessException
InvocationTargetException

setValue

public static Object setValue(Object obj,
                              String fieldName,
                              Object value)
                       throws SecurityException,
                              NoSuchFieldException,
                              IllegalArgumentException,
                              IllegalAccessException
Throws:
SecurityException
NoSuchFieldException
IllegalArgumentException
IllegalAccessException

getSimpleTypeName

public static String getSimpleTypeName(Class<?> type)

synchronizeAccess

public static <I> I synchronizeAccess(I instance,
                                      Class<I> type,
                                      Object semaphore)
allows to synchronize all access to the given instance based on the given semaphore object.

Type Parameters:
I - the interface to be synchronized
Parameters:
instance - the object instance who's methods are to be synchronized
type - the interface type that is to be used
semaphore - the object used for synchronization
Returns:
the proxy that allows synchronized access

addToSystemClassLoader

public static void addToSystemClassLoader(URL url)
                                   throws Exception
'hacks' the given URL into the system class loader

Throws:
Exception

checkEAN

public static boolean checkEAN(String code)
                        throws IllegalArgumentException
takes both: UPC and EAN codes; must be numeric only

Throws:
IllegalArgumentException

calculateEANChecksum

public static int calculateEANChecksum(String codeWithoutCheckDigit)
                                throws IllegalArgumentException
takes both: UPC and EAN codes; must be numeric only

Throws:
IllegalArgumentException

getOption

public static String getOption(String optionKey,
                               String[] args)
looks for the given option from a list of command line arguments.

Parameters:
optionKey - the plain option key you look for, e.g. '-user'
args - the argument list
Returns:
the argument value if the key with a prefix is found

isClassAvailable

public static boolean isClassAvailable(String className)
allows to test for the availability of the given class name w/o throwing an exception

Returns:
true if the class is available; false otherwise
See Also:
Settings.getClassLoader()


(c) Holger Antelmann since 2001- all rights reserved (contact: info@antelmann.com)
see www.antelmann.com/developer for further details and available downloads