org.fuin.utils4j
Class Utils4J

java.lang.Object
  extended by org.fuin.utils4j.Utils4J

public final class Utils4J
extends Object

Common utility methods for use in Java applications and libraries.


Nested Class Summary
static interface Utils4J.UnzipInputStreamWrapper
          Wraps a given input stream into another one an returns it.
 
Method Summary
static void addToClasspath(String url)
          Adds an URL to the classpath.
static void addToClasspath(URL url)
          Adds an URL to the classpath.
static void checkNotEmpty(String name, String value)
          Checks if a variable is not empty and throws an IllegalNullArgumentException if this rule is violated.
static void checkNotNull(String name, Object value)
          Checks if a variable is not null and throws an IllegalNullArgumentException if this rule is violated.
static void checkValidDir(File dir)
          Check if the argument is an existing directory.
static void checkValidFile(File file)
          Check if the argument is an existing file.
static String concatPathAndFilename(String path, String filename, String separator)
          Concatenate a path and a filename taking null and empty string values into account.
static boolean containsURL(URL[] urls, URL url)
          Checks if the array or URLs contains the given URL.
static String createHash(File file)
          Deprecated. Use createHashMD5 instead.
static String createHash(File file, String algorithm)
          Creates a HEX encoded hash from a file.
static String createHash(InputStream inputStream, String algorithm)
          Creates a HEX encoded hash from a stream.
static String createHashMD5(File file)
          Creates an MD5 hash from a file.
static Object createInstance(String className)
          Create an instance with Class.forName(..) and wrap all exceptions into RuntimeExceptions.
static URL createUrl(URL baseUrl, String path, String filename)
          Creates an URL based on a directory a relative path and a filename.
static void createWindowsDesktopUrlLink(String baseUrl, String url, File workingDir, Integer showCommand, Integer iconIndex, File iconFile, Integer hotKey, String linkFilenameWithoutExtension, boolean overwrite, Date modified)
          Creates an URL Link on the Windows Desktop.
static String createWindowsDesktopUrlLinkContent(String baseUrl, String url, File workingDir, Integer showCommand, Integer iconIndex, File iconFile, Integer hotKey, Date modified)
          Creates the content of an URL Link file (.url) on the Windows Desktop.
static long dateToFileTime(Date date)
          Converts Date into a Windows FILETIME.
static byte[] decodeHex(String data)
          Converts an array of characters representing hexidecimal values into an array of bytes of those same values.
static byte[] decryptPasswordBased(String algorithm, byte[] encryptedData, char[] password, byte[] salt, int count)
          Decrypts some data based on a password.
static String encodeHex(byte[] data)
          Converts an array of bytes into an array of characters representing the hexidecimal values of each byte in order.
static byte[] encryptPasswordBased(String algorithm, byte[] data, char[] password, byte[] salt, int count)
          Encrypts some data based on a password.
static String getPackagePath(Class clasz)
          Returns the package path of a class.
static String getRelativePath(File baseDir, File dir)
          Returns a relative path based on a base directory.
static URL getResource(Class clasz, String name)
          Get the path to a resource located in the same package as a given class.
static File getTempDir()
          Returns the temporary directory and checks if it is valid and exists.
static File getUserHomeDir()
          Returns the user home directory and checks if it is valid and exists.
static Object invoke(Object obj, String methodName, Class[] argTypes, Object[] args)
          Calls a method with reflection and maps all errors into one exception.
static Properties loadProperties(Class clasz, String filename)
          Load properties from classpath.
static Properties loadProperties(File file)
          Load properties from a file.
static Properties loadProperties(String baseUrl, String filename)
          Load a file from an directory.
static Properties loadProperties(URL fileURL)
          Load a file from an URL.
static Properties loadProperties(URL baseUrl, String filename)
          Load a file from an directory.
static FileLock lockRandomAccessFile(RandomAccessFile file, int tryLockMax, long tryWaitMillis)
          Lock the file.
static String replaceVars(String str, Map vars)
          Replaces all variables inside a string with values from a map.
static void saveProperties(File file, Properties props, String comment)
          Save properties to a file.
static void unzip(File zipFile, File destDir)
          Unzips a file into a given directory.
static void unzip(File zipFile, File destDir, Utils4J.UnzipInputStreamWrapper wrapper, Cancelable cancelable)
          Unzips a file into a given directory.
static void zipDir(File srcDir, FileFilter filter, String destPath, File destFile)
          Creates a ZIP file and adds all files in a directory and all it's sub directories to the archive.
static void zipDir(File srcDir, String destPath, File destFile)
          Creates a ZIP file and adds all files in a directory and all it's sub directories to the archive.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Method Detail

getPackagePath

public static String getPackagePath(Class clasz)
Returns the package path of a class.

Parameters:
clasz - Class to determine the path for - Cannot be null.
Returns:
Package path for the class.

getResource

public static URL getResource(Class clasz,
                              String name)
Get the path to a resource located in the same package as a given class.

Parameters:
clasz - Class with the same package where the resource is located - Cannot be null.
name - Filename of the resource - Cannot be null.
Returns:
Resource URL.

loadProperties

public static Properties loadProperties(Class clasz,
                                        String filename)
Load properties from classpath.

Parameters:
clasz - Class in the same package as the properties file - Cannot be null.
filename - Name of the properties file (without path) - Cannot be null.
Returns:
Properties.

loadProperties

public static Properties loadProperties(File file)
Load properties from a file.

Parameters:
file - Properties file - Cannot be null and must be a valid file.
Returns:
Properties.

checkValidFile

public static void checkValidFile(File file)
Check if the argument is an existing file. If the check fails an IllegalArgumentException is thrown.

Parameters:
file - File to check - Cannot be null.

checkValidDir

public static void checkValidDir(File dir)
Check if the argument is an existing directory. If the check fails an IllegalArgumentException is thrown.

Parameters:
dir - Directory to check - Cannot be null.

saveProperties

public static void saveProperties(File file,
                                  Properties props,
                                  String comment)
Save properties to a file.

Parameters:
file - Destination file - Cannot be null and parent directory must exist.
props - Properties to save - Cannot be null.
comment - Comment for the file.

createInstance

public static Object createInstance(String className)
Create an instance with Class.forName(..) and wrap all exceptions into RuntimeExceptions.

Parameters:
className - Full qualified class name - Cannot be null.
Returns:
New instance of the class.

addToClasspath

public static void addToClasspath(String url)
Adds an URL to the classpath.

Parameters:
url - URL to add - Cannot be null.

containsURL

public static boolean containsURL(URL[] urls,
                                  URL url)
Checks if the array or URLs contains the given URL.

Parameters:
urls - Array of URLs - Cannot be null.
url - URL to find - Cannot be null.
Returns:
If the URL is in the array TRUE else FALSE.

createHash

public static String createHash(File file)
Deprecated. Use createHashMD5 instead.

Creates an MD5 hash from a file.

Parameters:
file - File to create an hash for - Cannot be null.
Returns:
Hash as text.

createHashMD5

public static String createHashMD5(File file)
Creates an MD5 hash from a file.

Parameters:
file - File to create an hash for - Cannot be null.
Returns:
Hash as text.

createHash

public static String createHash(File file,
                                String algorithm)
Creates a HEX encoded hash from a file.

Parameters:
file - File to create a hash for - Cannot be null.
algorithm - Hash algorithm like "MD5" or "SHA" - Cannot be null.
Returns:
HEX encoded hash.

createHash

public static String createHash(InputStream inputStream,
                                String algorithm)
Creates a HEX encoded hash from a stream.

Parameters:
inputStream - Stream to create a hash for - Cannot be null.
algorithm - Hash algorithm like "MD5" or "SHA" - Cannot be null.
Returns:
HEX encoded hash.

encryptPasswordBased

public static byte[] encryptPasswordBased(String algorithm,
                                          byte[] data,
                                          char[] password,
                                          byte[] salt,
                                          int count)
Encrypts some data based on a password.

Parameters:
algorithm - PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be null.
data - Data to encrypt - Cannot be null.
password - Password - Cannot be null.
salt - Salt usable with algorithm - Cannot be null.
count - Iterations.
Returns:
Encrypted data.

decryptPasswordBased

public static byte[] decryptPasswordBased(String algorithm,
                                          byte[] encryptedData,
                                          char[] password,
                                          byte[] salt,
                                          int count)
Decrypts some data based on a password.

Parameters:
algorithm - PBE algorithm like "PBEWithMD5AndDES" or "PBEWithMD5AndTripleDES" - Cannot be null.
encryptedData - Data to decrypt - Cannot be null.
password - Password - Cannot be null.
salt - Salt usable with algorithm - Cannot be null.
count - Iterations.
Returns:
Encrypted data.

createUrl

public static URL createUrl(URL baseUrl,
                            String path,
                            String filename)
Creates an URL based on a directory a relative path and a filename.

Parameters:
baseUrl - Directory URL with or without slash ("/") at the end of the string - Cannot be null.
path - Relative path inside the base URL (with or without slash ("/") at the end of the string) - Can be null or an empty string.
filename - Filename without path - Cannot be null.
Returns:
URL.

getRelativePath

public static String getRelativePath(File baseDir,
                                     File dir)
Returns a relative path based on a base directory. If the dir is not inside baseDir an IllegalArgumentException is thrown.

Parameters:
baseDir - Base directory the path is relative to - Cannot be null.
dir - Directory inside the base directory - Cannot be null.
Returns:
Path of dir relative to baseDir. If both are equal an empty string is returned.

loadProperties

public static Properties loadProperties(URL baseUrl,
                                        String filename)
Load a file from an directory.

Parameters:
baseUrl - Directory URL - Cannot be null.
filename - Filename without path - Cannot be null.
Returns:
Properties.

loadProperties

public static Properties loadProperties(URL fileURL)
Load a file from an URL.

Parameters:
fileURL - Property file URL - Cannot be null.
Returns:
Properties.

loadProperties

public static Properties loadProperties(String baseUrl,
                                        String filename)
Load a file from an directory. Wraps a possible MalformedURLException exception into a RuntimeException.

Parameters:
baseUrl - Directory URL as String - Cannot be null.
filename - Filename without path - Cannot be null.
Returns:
Properties.

addToClasspath

public static void addToClasspath(URL url)
Adds an URL to the classpath.

Parameters:
url - URL to add - Cannot be null.

checkNotNull

public static void checkNotNull(String name,
                                Object value)
Checks if a variable is not null and throws an IllegalNullArgumentException if this rule is violated.

Parameters:
name - Name of the variable to be displayed in an error message.
value - Value to check for null.

checkNotEmpty

public static void checkNotEmpty(String name,
                                 String value)
Checks if a variable is not empty and throws an IllegalNullArgumentException if this rule is violated. A String with spaces is NOT considered empty!

Parameters:
name - Name of the variable to be displayed in an error message.
value - Value to check for an empty String - Cannot be null.

invoke

public static Object invoke(Object obj,
                            String methodName,
                            Class[] argTypes,
                            Object[] args)
                     throws InvokeMethodFailedException
Calls a method with reflection and maps all errors into one exception.

Parameters:
obj - The object the underlying method is invoked from - Cannot be null.
methodName - Name of the Method - Cannot be null.
argTypes - The list of parameters - May be null.
args - Arguments the arguments used for the method call - May be null if "argTypes" is also null.
Returns:
The result of dispatching the method represented by this object on obj with parameters args.
Throws:
InvokeMethodFailedException - Invoking the method failed for some reason.

unzip

public static void unzip(File zipFile,
                         File destDir)
                  throws IOException
Unzips a file into a given directory. WARNING: Only relative path entries are allowed inside the archive!

Parameters:
zipFile - Source ZIP file - Cannot be null and must be a valid ZIP file.
destDir - Destination directory - Cannot be null and must exist.
Throws:
IOException - Error unzipping the file.

unzip

public static void unzip(File zipFile,
                         File destDir,
                         Utils4J.UnzipInputStreamWrapper wrapper,
                         Cancelable cancelable)
                  throws IOException
Unzips a file into a given directory. WARNING: Only relative path entries are allowed inside the archive!

Parameters:
zipFile - Source ZIP file - Cannot be null and must be a valid ZIP file.
destDir - Destination directory - Cannot be null and must exist.
wrapper - Callback interface to give the caller the chance to wrap the ZIP input stream into another one. This is useful for example to display a progress bar - Can be null if no wrapping is required.
cancelable - Signals if the unzip should be canceled - Can be null if no cancel option is required.
Throws:
IOException - Error unzipping the file.

getUserHomeDir

public static File getUserHomeDir()
Returns the user home directory and checks if it is valid and exists. If not a IllegalStateException is thrown.

Returns:
Directory.

getTempDir

public static File getTempDir()
Returns the temporary directory and checks if it is valid and exists. If not a IllegalStateException is thrown.

Returns:
Directory.

replaceVars

public static String replaceVars(String str,
                                 Map vars)
Replaces all variables inside a string with values from a map.

Parameters:
str - Text with variables (Format: ${key} ) - May be null or empty.
vars - Map with key/values (both of type String - Cannot be null.
Returns:
String with replaced variables. Unknown variables will remain unchanged.

dateToFileTime

public static long dateToFileTime(Date date)
Converts Date into a Windows FILETIME. The Windows FILETIME structure holds a date and time associated with a file. The structure identifies a 64-bit integer specifying the number of 100-nanosecond intervals which have passed since January 1, 1601. This code is copied from the org.apache.poi.hpsf.Util class.

Parameters:
date - The date to be converted - Cannot be null.
Returns:
The file time

createWindowsDesktopUrlLink

public static void createWindowsDesktopUrlLink(String baseUrl,
                                               String url,
                                               File workingDir,
                                               Integer showCommand,
                                               Integer iconIndex,
                                               File iconFile,
                                               Integer hotKey,
                                               String linkFilenameWithoutExtension,
                                               boolean overwrite,
                                               Date modified)
                                        throws IOException
Creates an URL Link on the Windows Desktop. This is done by creating a file (URL File Format) with an ".url" extension. For a description see http://www.cyanwerks.com/file-format-url.html .

Parameters:
baseUrl - Base URL for the link - Cannot be null or empty.
url - Target URL - Cannot be null or empty.
workingDir - It's the "working folder" that your URL file uses. The working folder is possibly the folder to be set as the current folder for the application that would open the file. However Internet Explorer does not seem to be affected by this field - Can be null.
showCommand - Normal=null, Minimized=7, Maximized=3
iconIndex - The Icon Index within the icon library specified by IconFile. In an icon library, which can be generally be either a ICO, DLL or EXE file, the icons are indexed with numbers. The first icon index starts at 0 - Can be null if the file is not indexed.
iconFile - Specifies the path of the icon library file. Generally the icon library can be an ICO, DLL or EXE file. The default icon library used tends to be the URL.DLL library on the system's Windows\System directory - Can be null if no icon is required.
hotKey - The HotKey field specifies what is the shortcut key used to automatically launch the Internet shortcut. The field uses a number to specify what hotkey is used. To get the appropriate code simply create a shortcut with MSIE and examine the file's content.
linkFilenameWithoutExtension - Name for the link file (displayed as text) - Cannot be null or empty.
overwrite - Overwrite an existing ".url" file.
modified - Timestamp.
Throws:
IOException - Error writing the file.

createWindowsDesktopUrlLinkContent

public static String createWindowsDesktopUrlLinkContent(String baseUrl,
                                                        String url,
                                                        File workingDir,
                                                        Integer showCommand,
                                                        Integer iconIndex,
                                                        File iconFile,
                                                        Integer hotKey,
                                                        Date modified)
Creates the content of an URL Link file (.url) on the Windows Desktop. For a description see http://www.cyanwerks.com/file-format-url.html .

Parameters:
baseUrl - Base URL for the link - Cannot be null or empty.
url - Target URL - Cannot be null or empty.
workingDir - It's the "working folder" that your URL file uses. The working folder is possibly the folder to be set as the current folder for the application that would open the file. However Internet Explorer does not seem to be affected by this field - Can be null.
showCommand - Normal=null, Minimized=7, Maximized=3
iconIndex - The Icon Index within the icon library specified by IconFile. In an icon library, which can be generally be either a ICO, DLL or EXE file, the icons are indexed with numbers. The first icon index starts at 0 - Can be null if the file is not indexed.
iconFile - Specifies the path of the icon library file. Generally the icon library can be an ICO, DLL or EXE file. The default icon library used tends to be the URL.DLL library on the system's Windows\System directory - Can be null if no icon is required.
hotKey - The HotKey field specifies what is the shortcut key used to automatically launch the Internet shortcut. The field uses a number to specify what hotkey is used. To get the appropriate code simply create a shortcut with MSIE and examine the file's content.
modified - Timestamp.
Returns:
INI file text.

concatPathAndFilename

public static String concatPathAndFilename(String path,
                                           String filename,
                                           String separator)
Concatenate a path and a filename taking null and empty string values into account.

Parameters:
path - Path - Can be null or an empty string.
filename - Filename - Cannot be null.
separator - Separator for directories - Can be null or an empty string.
Returns:
Path and filename divided by the separator.

encodeHex

public static String encodeHex(byte[] data)
Converts an array of bytes into an array of characters representing the hexidecimal values of each byte in order. The returned array will be double the length of the passed array, as it takes two characters to represent any given byte. Author: Apache Software Foundation See: org.apache.commons.codec.binary.Hex

Parameters:
data - A byte[] to convert to Hex characters - Cannot be null.
Returns:
A string containing hexidecimal characters

decodeHex

public static byte[] decodeHex(String data)
Converts an array of characters representing hexidecimal values into an array of bytes of those same values. The returned array will be half the length of the passed array, as it takes two characters to represent any given byte. An exception is thrown if the passed char array has an odd number of elements.

Parameters:
data - An array of characters containing hexidecimal digits - Cannot be null.
Returns:
A byte array containing binary data decoded from the supplied char array. Author: Apache Software Foundation See: org.apache.commons.codec.binary.Hex

lockRandomAccessFile

public static FileLock lockRandomAccessFile(RandomAccessFile file,
                                            int tryLockMax,
                                            long tryWaitMillis)
                                     throws LockingFailedException
Lock the file.

Parameters:
file - File to lock - Cannot be null.
tryLockMax - Number of tries to lock before throwing an exception.
tryWaitMillis - Milliseconds to sleep between retries.
Returns:
FileLock.
Throws:
LockingFailedException - Locking the file failed.

zipDir

public static void zipDir(File srcDir,
                          FileFilter filter,
                          String destPath,
                          File destFile)
                   throws IOException
Creates a ZIP file and adds all files in a directory and all it's sub directories to the archive. Only entries are added that comply to the file filter.

Parameters:
srcDir - Directory to add - Cannot be null and must be a valid directory.
filter - Filter or null for all files/directories.
destPath - Path to use for the ZIP archive - May be null or an empyt string.
destFile - Target ZIP file - Cannot be null.
Throws:
IOException - Error writing to the output stream.

zipDir

public static void zipDir(File srcDir,
                          String destPath,
                          File destFile)
                   throws IOException
Creates a ZIP file and adds all files in a directory and all it's sub directories to the archive.

Parameters:
srcDir - Directory to add - Cannot be null and must be a valid directory.
destPath - Path to use for the ZIP archive - May be null or an empyt string.
destFile - Target ZIP file - Cannot be null.
Throws:
IOException - Error writing to the output stream.


Copyright © 2011 Future Invent Informationsmanagement GmbH. All Rights Reserved.