package org.cumulus4j.testutil; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Random; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.zip.ZipOutputStream; /** * This is a collection of utility functions. All methods * of this class are static. * @author Alex Bieber, Marc Klinger, Marco Schulze, Niklas Schiffler * @version 1.4 ;-) */ public abstract class Util { /** * Specifies usage of the MD5 algorithm in {@link #hash(byte[], String)} (or one of the other hash methods). */ public static final String HASH_ALGORITHM_MD5 = "MD5"; /** * Specifies usage of the SHA algorithm in {@link #hash(byte[], String)} (or one of the other hash methods). */ public static final String HASH_ALGORITHM_SHA = "SHA"; // private static final Logger logger = Logger.getLogger(Util.class); /** * Check two objects for equality. *
* This method is a convenience reducing code:
* obj0 == obj1 || (obj0 != null && obj0.equals(obj1))
* will be replaced by Utils.equals(obj0, obj1)
* and you do not need to worry about null
anymore.
*
* Additionally if you pass two arrays to this method
* (whose equals method only checks for equality [TODO doesn't this mean "identity" instead of "equality"?])
* this method will consult {@link Arrays#equals(Object[], Object[])}
* for equality of the parameters instead, of course after a null
check.
*
* @param obj0 One object to check for equality
* @param obj1 The other object to check for equality
* @return true
if both objects are null
or
* if they are equal or if both objects are Object arrays
* and equal according to {@link Arrays#equals(Object[], Object[])} -
* false
otherwise
*/
public static boolean equals(Object obj0, Object obj1)
{
if (obj0 instanceof Object[] && obj1 instanceof Object[])
return obj0 == obj1 || Arrays.equals((Object[])obj0, (Object[])obj1);
return obj0 == obj1 || (obj0 != null && obj0.equals(obj1));
}
/**
* Check two long
s for equality.
*
* In order to provide the same API for Object
and long
* which both are often used as IDs, it is recommended to use this method
* instead of writing id0 == id1
.
*
* To write id0 == id1
is considered more error-prone if refactorings happen:
* Imagine, you create an object with a long unique id. Later on, you decide that a String id
* is better. You won't recognize that some old code id0 == id1
is broken.
* When using this method instead, the compiler will automatically switch to {@link #equals(Object, Object)}
* and a correct result will be calculated.
*
* Even though Java 5 (and higher) implicitely converts simple datatypes to their corresponding object
* (e.g. long
to java.lang.Long
), it's unnecessary to perform this conversion
* and better to have this method instead.
*
l0 == l1
.
* @see #equals(Object, Object)
*/
public static boolean equals(long l0, long l1)
{
return l0 == l1;
}
/**
* Check two int
s for equality.
*
* This method does the same for int
s as {@link #equals(long, long)}
* does for long
s.
*
i0 == i1
.
* @see #equals(long, long)
*/
public static boolean equals(int i0, int i1)
{
return i0 == i1;
}
/**
* @param l The long number for which to calculate the hashcode.
* @return the same as new Long(l).hashCode() would do, but
* without the overhead of creating a Long instance.
*/
public static int hashCode(long l)
{
return (int)(l ^ (l >>> 32));
}
/**
* Get a hash code for an object. This method also handles
* null
-Objects.
* @param obj An object or null
* @return 0
if obj == null
-
* obj.hashCode()
otherwise
*/
public static int hashCode(Object obj)
{
return obj == null ? 0 : obj.hashCode();
}
/**
* Returns a String with zeros prefixing
* the given base. The returned String will
* have at least a length of the given strLength.
*
* This method calls {@link #addLeadingChars(String, int, char)} with '0' as
* fillChar
.
*
fillChar
* to the front of the string s
until the total length
* of the string reaches length
. If the given string
* s
is longer or exactly as long as defined by
* length
, no characters will be added.
*
* @param s The string to which characters are appended (before).
* @param length The minimum length of the result.
* @param fillChar The character that will be added.
* @return the resulting string with as many fillChar
characters added to it as necessary.
*/
public static String addLeadingChars(String s, int length, char fillChar)
{
if (s != null && s.length() >= length)
return s;
StringBuilder sb = new StringBuilder(length);
int l = s == null ? length : length - s.length();
while (sb.length() < l)
sb.append(fillChar);
if (s != null)
sb.append(s);
return sb.toString();
}
/**
* This method adds the character passed as fillChar
* to the end of the string s
until the total length
* of the string reaches length
. If the given string
* s
is longer or exactly as long as defined by
* length
, no characters will be added.
*
* @param s The string to which characters are appended (after).
* @param length The minimum length of the result.
* @param fillChar The character that will be added.
* @return the resulting string with as many fillChar
characters added to it as necessary.
*/
public static String addTrailingChars(String s, int length, char fillChar)
{
if (s != null && s.length() >= length)
return s;
StringBuilder sb = new StringBuilder(length);
if (s != null)
sb.append(s);
while (sb.length() < length)
sb.append(fillChar);
return sb.toString();
}
/**
* Returns a String with spaces prefixing
* the given base. The returned String will
* have at least a length of the given strLength.
*
* This method calls {@link #addLeadingChars(String, int, char)} with spaces (' ') as
* fillChar
.
*
* This is a convenience method for encodeHexStr(buf, 0, buf.length)
*
* @param buf The byte array to translate into human readable text.
* @return a human readable string like "fa3d70" for a byte array with 3 bytes and these values.
* @see #encodeHexStr(byte[], int, int)
* @see #decodeHexStr(String)
*/
public static String encodeHexStr(byte[] buf)
{
return encodeHexStr(buf, 0, buf.length);
}
/**
* Encode a byte array into a human readable hex string. For each byte,
* two hex digits are produced. They are concatted without any separators.
*
* @param buf The byte array to translate into human readable text.
* @param pos The start position (0-based).
* @param len The number of bytes that shall be processed beginning at the position specified by pos
.
* @return a human readable string like "fa3d70" for a byte array with 3 bytes and these values.
* @see #encodeHexStr(byte[])
* @see #decodeHexStr(String)
*/
public static String encodeHexStr(byte[] buf, int pos, int len)
{
StringBuffer hex = new StringBuffer();
while (len-- > 0) {
byte ch = buf[pos++];
int d = (ch >> 4) & 0xf;
hex.append((char)(d >= 10 ? 'a' - 10 + d : '0' + d));
d = ch & 0xf;
hex.append((char)(d >= 10 ? 'a' - 10 + d : '0' + d));
}
return hex.toString();
}
/**
* Decode a string containing two hex digits for each byte.
* @param hex The hex encoded string
* @return The byte array represented by the given hex string
* @see #encodeHexStr(byte[])
* @see #encodeHexStr(byte[], int, int)
*/
public static byte[] decodeHexStr(String hex)
{
if (hex.length() % 2 != 0)
throw new IllegalArgumentException("The hex string must have an even number of characters!");
byte[] res = new byte[hex.length() / 2];
int m = 0;
for (int i = 0; i < hex.length(); i += 2) {
res[m++] = (byte) Integer.parseInt(hex.substring(i, i + 2), 16);
}
return res;
}
/**
* Get a 32 character MD5 hash in hex notation for the given input string.
* @param clear The input string to build the hash on
* @return The MD5 encoded hex string.
* @throws NoSuchAlgorithmException
*/
public static String getMD5HexString(String clear)
throws NoSuchAlgorithmException
{
byte[] enc = MessageDigest.getInstance("MD5").digest(clear.getBytes());
// System.out.println(new String(enc));
return encodeHexStr(enc, 0, enc.length);
}
/**
* Hash a byte array with the given algorithm.
*
* @param data The data to hash
* @param algorithm The name of the hash alogorithm (e.g. MD5, SHA) as supported by {@link MessageDigest}. If using one of these
* algorithms, you should use the appropriate constant: {@link #HASH_ALGORITHM_MD5} or {@link #HASH_ALGORITHM_SHA}.
* @return the array of bytes for the resulting hash value.
* @throws NoSuchAlgorithmException if the algorithm is not available in the caller's environment.
*
* @see #hash(File, String)
* @see #hash(InputStream, long, String)
* @see #encodeHexStr(byte[])
*/
public static byte[] hash(byte[] data, String algorithm) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(data);
return md.digest();
}
/**
* Hash an {@link InputStream} with the given algorithm.
*
* @param in The {@link InputStream} which will be read. This stream is not closed, but read until its end or until the number of bytes specified
* in bytesToRead
has been read.
* @param bytesToRead If -1, the {@link InputStream} in
will be read till its end is reached. Otherwise, the amount of bytes specified by
* this parameter is read. If the {@link InputStream} ends before having read the specified amount of bytes, an {@link IOException} will be thrown.
* @param algorithm The name of the hash alogorithm (e.g. MD5, SHA) as supported by {@link MessageDigest}. If using one of these
* algorithms, you should use the appropriate constant: {@link #HASH_ALGORITHM_MD5} or {@link #HASH_ALGORITHM_SHA}.
* @return the array of bytes for the resulting hash value.
* @throws NoSuchAlgorithmException if the algorithm is not available in the caller's environment.
* @throws IOException if reading from the {@link InputStream} fails.
*
* @see #hash(byte[], String)
* @see #encodeHexStr(byte[])
*/
public static byte[] hash(InputStream in, long bytesToRead, String algorithm)
throws NoSuchAlgorithmException, IOException
{
if (bytesToRead < 0 && bytesToRead != -1)
throw new IllegalArgumentException("bytesToRead < 0 && bytesToRead != -1");
long bytesReadTotal = 0;
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] data = new byte[10240];
while (true) {
int len;
if(bytesToRead < 0)
len = data.length;
else {
len = (int)Math.min(data.length, bytesToRead - bytesReadTotal);
if (len < 1)
break;
}
int bytesRead = in.read(data, 0, len);
if (bytesRead < 0) {
if (bytesToRead >= 0)
throw new IOException("Unexpected EndOfStream! bytesToRead==" + bytesToRead + " but only " + bytesReadTotal + " bytes could be read from InputStream!");
break;
}
bytesReadTotal += bytesRead;
if (bytesRead > 0)
md.update(data, 0, bytesRead);
}
return md.digest();
}
/**
* This methods reads a given file and calls {@link #hash(InputStream, long, String)}.
*
* @param file The file to read an hash.
* @param algorithm The algorithm to use.
* @return The result of {@link #hash(InputStream, long, String)}.
* @throws NoSuchAlgorithmException if the algorithm is not available in the caller's environment.
* @throws IOException if reading the file
fails.
*
* @see #hash(byte[], String)
* @see #encodeHexStr(byte[])
*/
public static byte[] hash(File file, String algorithm)
throws NoSuchAlgorithmException, IOException
{
FileInputStream in = new FileInputStream(file);
try {
return hash(in, -1, algorithm);
} finally {
in.close();
}
}
// public static void main(String[] args)
// {
// File f = new File("/home/marco/workspaces/jfire/JFireTrade/dist/JFireTrade.jar");
// try {
// System.out.println(byteArrayToHexString(hash(f, HASH_ALGORITHM_MD5)));
//
// byte[] data = new byte[(int)f.length()];
// RandomAccessFile raf = new RandomAccessFile(f, "r");
// raf.read(data);
// System.out.println(byteArrayToHexString(hash(data, HASH_ALGORITHM_MD5)));
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
/**
* Truncates a double value at the given decimal position.
* E.g. d
= 9.45935436363463 and numDigits
= 2
* will return 9.45.
*
* @param d the double to shorten
* @param numDigits the number of decimal places after the decimal separator.
* @return the shorted double
*/
public static double truncateDouble(double d, int numDigits)
{
double multiplier = Math.pow(10, numDigits);
return ((int) (d * multiplier)) / multiplier;
}
/**
* Makes a Double out of Integer. The parameter numDigits
* determines where the decimal separator should be, seen from the end.
* E.g. value
= 135 and numDigits
= 2 will
* return 1.35.
*
* @param value the integer to transform into a double
* @param numDigits determines where the decimal separator should be,
* seen from the end
* @return the transformed double
*/
public static double getDouble(int value, int numDigits)
{
double multiplier = Math.pow(10, numDigits);
return (value) / multiplier;
}
public static
file
.
* @param file The file to point to.
* @return the path to file
relative to baseDir
or the absolute path,
* if a relative path cannot be formulated (i.e. they have no directory in common).
* @throws IOException In case of an error
* @deprecated Use {@link IOUtil#getRelativePath(File,String)} instead
*/
@Deprecated
public static String getRelativePath(File baseDir, String file)
throws IOException
{
return IOUtil.getRelativePath(baseDir, file);
}
/**
* This method removes double slashes, single-dot-directories and double-dot-directories
* from a path. This means, it does nearly the same as File.getCanonicalPath
, but
* it does not resolve symlinks. This is essential for the method getRelativePath
,
* because this method first tries it with a simplified path before using the canonical path
* (prevents problems with iteration through directories, where there are symlinks).
* * Please note that this method makes the given path absolute! * * @param path A path to simplify, e.g. "/../opt/java/jboss/../jboss/./bin/././../server/default/lib/." * @return the simplified string (absolute path), e.g. "/opt/java/jboss/server/default/lib" * @deprecated Use {@link IOUtil#simplifyPath(File)} instead */ @Deprecated public static String simplifyPath(File path) { return IOUtil.simplifyPath(path); } /** * Transfer all available data from an {@link InputStream} to an {@link OutputStream}. *
* This is a convenience method for transferStreamData(in, out, 0, -1)
* @param in The stream to read from
* @param out The stream to write to
* @return The number of bytes transferred
* @throws IOException In case of an error
* @deprecated Use {@link IOUtil#transferStreamData(InputStream, OutputStream)} instead
*/
@Deprecated
public static long transferStreamData(java.io.InputStream in, java.io.OutputStream out)
throws java.io.IOException
{
return IOUtil.transferStreamData(in, out, 0, -1);
}
/**
* This method deletes the given directory recursively. If the given parameter
* specifies a file and no directory, it will be deleted anyway. If one or more
* files or subdirectories cannot be deleted, the method still continues and tries
* to delete as many files/subdirectories as possible.
*
* @param dir The directory or file to delete
* @return True, if the file or directory does not exist anymore. This means it either
* was not existing already before or it has been successfully deleted. False, if the
* directory could not be deleted.
* @deprecated Use {@link IOUtil#deleteDirectoryRecursively(String)} instead
*/
@Deprecated
public static boolean deleteDirectoryRecursively(String dir)
{
return IOUtil.deleteDirectoryRecursively(dir);
}
/**
* This method deletes the given directory recursively. If the given parameter
* specifies a file and no directory, it will be deleted anyway. If one or more
* files or subdirectories cannot be deleted, the method still continues and tries
* to delete as many files/subdirectories as possible.
*
* @param dir The directory or file to delete
* @return true
if the file or directory does not exist anymore.
* This means it either was not existing already before or it has been
* successfully deleted. false
if the directory could not be
* deleted.
* @deprecated Use {@link IOUtil#deleteDirectoryRecursively(File)} instead
*/
@Deprecated
public static boolean deleteDirectoryRecursively(File dir)
{
return IOUtil.deleteDirectoryRecursively(dir);
}
/**
* Tries to find a unique, not existing folder name under the given root folder with a random
* number (in hex format) added to the given prefix. When found, the directory will be created.
*
* This is a convenience method for {@link IOUtil#createUniqueRandomFolder(File, String, long, long)} * and calls it with 10000 as maxIterations and 10000 as number range. *
* Note that this method might throw a {@link IOException} * if it will not find a unique name within 10000 iterations. *
* Note that the creation of the directory is not completely safe. This method is * synchronized, but other processes could "steal" the unique filename. * * @param rootFolder The rootFolder to find a unique subfolder for * @param prefix A prefix for the folder that has to be found. * @return A File pointing to an unique (non-existing) Folder under the given rootFolder and with the given prefix * @throws IOException in case of an error * @deprecated Use {@link IOUtil#createUniqueRandomFolder(File,String)} instead */ @Deprecated public static File createUniqueRandomFolder(File rootFolder, final String prefix) throws IOException { return IOUtil.createUniqueRandomFolder(rootFolder, prefix); } /** * Tries to find a unique, not existing folder name under the given root folder with a random * number (in hex format) added to the given prefix. When found, the directory will be created. *
* The method will try to find a name for maxIterations
number
* of itarations and use random numbers from 0 to uniqueOutOf
.
*
* Note that the creation of the directory is not completely safe. This method is * synchronized, but other processes could "steal" the unique filename. * * @param rootFolder The rootFolder to find a unique subfolder for * @param prefix A prefix for the folder that has to be found. * @param maxIterations The maximum number of itarations this method shoud do. * If after them still no unique folder could be found, a {@link IOException} * is thrown. * @param uniqueOutOf The range of random numbers to apply (0 - given value) * * @return A File pointing to an unique folder under the given rootFolder and with the given prefix * @throws IOException in case of an error * @deprecated Use {@link IOUtil#createUniqueRandomFolder(File,String,long,long)} instead */ @Deprecated public static synchronized File createUniqueRandomFolder(File rootFolder, final String prefix, long maxIterations, long uniqueOutOf) throws IOException { return IOUtil.createUniqueRandomFolder(rootFolder, prefix, maxIterations, uniqueOutOf); } /** * Tries to find a unique, not existing folder name under the given root folder * suffixed with a number. When found, the directory will be created. * It will start with 0 and make Integer.MAX_VALUE number * of iterations maximum. The first not existing foldername will be returned. * If no foldername could be found after the maximum iterations a {@link IOException} * will be thrown. *
* Note that the creation of the directory is not completely safe. This method is * synchronized, but other processes could "steal" the unique filename. * * @param rootFolder The rootFolder to find a unique subfolder for * @param prefix A prefix for the folder that has to be found. * @return A File pointing to an unique (not existing) Folder under the given rootFolder and with the given prefix * @throws IOException in case of an error * @deprecated Use {@link IOUtil#createUniqueIncrementalFolder(File,String)} instead */ @Deprecated public static synchronized File createUniqueIncrementalFolder(File rootFolder, final String prefix) throws IOException { return IOUtil.createUniqueIncrementalFolder(rootFolder, prefix); } /** * Transfer data between streams * @param in The input stream * @param out The output stream * @param inputOffset How many bytes to skip before transferring * @param inputLen How many bytes to transfer. -1 = all * @return The number of bytes transferred * @throws IOException if an error occurs. * @deprecated Use {@link IOUtil#transferStreamData(java.io.InputStream,java.io.OutputStream,long,long)} instead */ @Deprecated public static long transferStreamData(java.io.InputStream in, java.io.OutputStream out, long inputOffset, long inputLen) throws java.io.IOException { return IOUtil.transferStreamData(in, out, inputOffset, inputLen); } /** * Copy a resource loaded by the class loader of a given class to a file. *
* This is a convenience method for copyResource(sourceResClass, sourceResName, new File(destinationFilename))
.
* @param sourceResClass The class whose class loader to use. If the class
* was loaded using the bootstrap class loaderClassloader.getSystemResourceAsStream
* will be used. See {@link Class#getResourceAsStream(String)} for details.
* @param sourceResName The name of the resource
* @param destinationFilename Where to copy the contents of the resource
* @throws IOException in case of an error
* @deprecated Use {@link IOUtil#copyResource(Class,String,String)} instead
*/
@Deprecated
public static void copyResource(Class> sourceResClass, String sourceResName, String destinationFilename)
throws IOException
{
IOUtil.copyResource(sourceResClass, sourceResName, destinationFilename);
}
/**
* Copy a resource loaded by the class loader of a given class to a file.
* @param sourceResClass The class whose class loader to use. If the class
* was loaded using the bootstrap class loaderClassloader.getSystemResourceAsStream
* will be used. See {@link Class#getResourceAsStream(String)} for details.
* @param sourceResName The name of the resource
* @param destinationFile Where to copy the contents of the resource
* @throws IOException in case of an error
* @deprecated Use {@link IOUtil#copyResource(Class, String, File)} instead
*/
@Deprecated
public static void copyResource(Class> sourceResClass, String sourceResName, File destinationFile)
throws IOException
{
IOUtil.copyResource(sourceResClass, sourceResName, destinationFile);
}
/**
* Copy a file.
*
* This is a convenience method for copyFile(new File(sourceFilename), new File(destinationFilename))
* @param sourceFilename The source file to copy
* @param destinationFilename To which file to copy the source
* @throws IOException in case of an error
* @deprecated Use {@link IOUtil#copyFile(String,String)} instead
*/
@Deprecated
public static void copyFile(String sourceFilename, String destinationFilename)
throws IOException
{
IOUtil.copyFile(sourceFilename, destinationFilename);
}
/**
* Copy a file.
* @param sourceFile The source file to copy
* @param destinationFile To which file to copy the source
* @throws IOException in case of an error
* @deprecated Use {@link IOUtil#copyFile(File, File)} instead
*/
@Deprecated
public static void copyFile(File sourceFile, File destinationFile)
throws IOException
{
IOUtil.copyFile(sourceFile, destinationFile);
}
/**
* Copy a directory recursively.
* @param sourceDirectory The source directory
* @param destinationDirectory The destination directory
* @throws IOException in case of an error
* @deprecated Use {@link IOUtil#copyDirectory(File,File)} instead
*/
@Deprecated
public static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException
{
IOUtil.copyDirectory(sourceDirectory, destinationDirectory);
}
/**
* Get a file object from a base directory and a list of subdirectories or files.
* @param file The base directory
* @param subDirs The subdirectories or files
* @return The new file instance
* @deprecated Use {@link IOUtil#getFile(File,String...)} instead
*/
@Deprecated
public static File getFile(File file, String ... subDirs)
{
return IOUtil.getFile(file, subDirs);
}
/**
* Write text to a file using UTF-8 encoding.
* @param file The file to write the text to
* @param text The text to write
* @throws IOException in case of an io error
* @throws FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason
* @deprecated Use {@link IOUtil#writeTextFile(File,String)} instead
*/
@Deprecated
public static void writeTextFile(File file, String text)
throws IOException, FileNotFoundException, UnsupportedEncodingException
{
IOUtil.writeTextFile(file, text);
}
/**
* Write text to a file.
* @param file The file to write the text to
* @param text The text to write
* @param encoding The caracter set to use as file encoding (e.g. "UTF-8")
* @throws IOException in case of an io error
* @throws FileNotFoundException if the file exists but is a directory
* rather than a regular file, does not exist but cannot
* be created, or cannot be opened for any other reason
* @throws UnsupportedEncodingException If the named encoding is not supported
* @deprecated Use {@link IOUtil#writeTextFile(File,String,String)} instead
*/
@Deprecated
public static void writeTextFile(File file, String text, String encoding)
throws IOException, FileNotFoundException, UnsupportedEncodingException
{
IOUtil.writeTextFile(file, text, encoding);
}
/**
* Read a UTF-8 encoded text file and return the contents as string.
*
For other encodings, use {@link IOUtil#readTextFile(File, String)}. * @param f The file to read, maximum size 1 GB * @throws FileNotFoundException if the file was not found * @throws IOException in case of an io error * @return The contents of the text file * @deprecated Use {@link IOUtil#readTextFile(File)} instead */ @Deprecated public static String readTextFile(File f) throws FileNotFoundException, IOException { return IOUtil.readTextFile(f); } /** * Read a text file and return the contents as string. * @param f The file to read, maximum size 1 GB * @param encoding The file encoding, e.g. "UTF-8" * @throws FileNotFoundException if the file was not found * @throws IOException in case of an io error * @throws UnsupportedEncodingException If the named encoding is not supported * @return The contents of the text file * @deprecated Use {@link IOUtil#readTextFile(File,String)} instead */ @Deprecated public static String readTextFile(File f, String encoding) throws FileNotFoundException, IOException, UnsupportedEncodingException { return IOUtil.readTextFile(f, encoding); } /** * Read a text file from an {@link InputStream} using * UTF-8 encoding. *
* This method does NOT close the input stream! * @param in The stream to read from. It will not be closed by this operation. * @return The contents of the input stream file * @deprecated Use {@link IOUtil#readTextFile(InputStream)} instead */ @Deprecated public static String readTextFile(InputStream in) throws FileNotFoundException, IOException { return IOUtil.readTextFile(in); } /** * Read a text file from an {@link InputStream} using * the given encoding. *
* This method does NOT close the input stream!
* @param in The stream to read from. It will not be closed by this operation.
* @param encoding The charset used for decoding, e.g. "UTF-8"
* @return The contents of the input stream file
* @deprecated Use {@link IOUtil#readTextFile(InputStream,String)} instead
*/
@Deprecated
public static String readTextFile(InputStream in, String encoding)
throws FileNotFoundException, IOException
{
return IOUtil.readTextFile(in, encoding);
}
/**
* Get the extension of a filename.
* @param fileName A file name (might contain the full path) or null
.
* @return null
, if the given fileName
doesn't contain
* a dot (".") or if the given fileName
is null
. Otherwise,
* returns all AFTER the last dot.
* @deprecated Use {@link IOUtil#getFileExtension(String)} instead
*/
@Deprecated
public static String getFileExtension(String fileName)
{
return IOUtil.getFileExtension(fileName);
}
/**
* Get a filename without extension.
* @param fileName A file name (might contain the full path) or null
.
* @return all before the last dot (".") or the full fileName
if no dot exists.
* Returns null
, if the given fileName
is null
.
* @deprecated Use {@link IOUtil#getFileNameWithoutExtension(String)} instead
*/
@Deprecated
public static String getFileNameWithoutExtension(String fileName)
{
return IOUtil.getFileNameWithoutExtension(fileName);
}
/**
* Get the temporary directory.
*
* FIXME: it seems not to be a good practise to create
* a temp file just to get the directory. accessing
* the system temp dir property would work without
* hd access and without throwing an IOException.
* See File.getTempDir() (private) (Marc)
*
* @return The temporary directory.
* @throws IOException In case of an error
* @deprecated Use {@link IOUtil#getTempDir()} instead
*/
@Deprecated
public static File getTempDir()
throws IOException
{
return IOUtil.getTempDir();
}
/**
* Compares two InputStreams.
*
* @param in1 the first InputStream
* @param in2 the second InputStream
* @param length the length to read from each InputStream
* @return true if both InputStreams contain the identical data or false if not
* @throws IOException if an I/O error occurs while reading length
bytes
* from one of the input streams.
* @deprecated Use {@link IOUtil#compareInputStreams(InputStream,InputStream,int)} instead
*/
@Deprecated
public static boolean compareInputStreams(InputStream in1, InputStream in2, int length)
throws IOException
{
return IOUtil.compareInputStreams(in1, in2, length);
}
/**
* Recursively zips all entries of the given zipInputFolder to
* a zipFile defined by zipOutputFile.
*
* @param zipOutputFile The file to write to (will be deleted if existent).
* @param zipInputFolder The inputFolder to zip.
* @deprecated Use {@link IOUtil#zipFolder(File,File)} instead
*/
@Deprecated
public static void zipFolder(File zipOutputFile, File zipInputFolder)
throws IOException
{
IOUtil.zipFolder(zipOutputFile, zipInputFolder);
}
/**
* Recursively writes all found files as entries into the given ZipOutputStream.
*
* @param out The ZipOutputStream to write to.
* @param zipOutputFile the output zipFile. optional. if it is null, this method cannot check whether
* your current output file is located within the zipped directory tree. You must not locate
* your zip-output file within the source directory, if you leave this null
.
* @param files The files to zip (optional, defaults to all files recursively). It must not be null
,
* if entryRoot
is null
.
* @param entryRoot The root folder of all entries. Entries in subfolders will be
* added relative to this. If entryRoot==null
, all given files will be
* added without any path (directly into the zip's root). entryRoot
and files
must not
* both be null
at the same time.
* @throws IOException in case of an I/O error.
* @deprecated Use {@link IOUtil#zipFilesRecursively(ZipOutputStream,File,File[],File)} instead
*/
@Deprecated
public static void zipFilesRecursively(ZipOutputStream out, File zipOutputFile, File[] files, File entryRoot)
throws IOException
{
IOUtil.zipFilesRecursively(out, zipOutputFile, files, entryRoot);
}
/**
* Unzip the given archive into the given folder.
*
* @param zipArchive The zip file to unzip.
* @param unzipRootFolder The folder to unzip to.
* @throws IOException in case of an I/O error.
* @deprecated Use {@link IOUtil#unzipArchive(File,File)} instead
*/
@Deprecated
public static void unzipArchive(File zipArchive, File unzipRootFolder)
throws IOException
{
IOUtil.unzipArchive(zipArchive, unzipRootFolder);
}
/**
* Add a trailing file separator character to the
* given directory name if it does not already
* end with one.
* @see File#separator
* @param directory A directory name
* @return the directory name anding with a file seperator
* @deprecated Use {@link IOUtil#addFinalSlash(String)} instead
*/
@Deprecated
public static String addFinalSlash(String directory)
{
return IOUtil.addFinalSlash(directory);
}
/**
* Generate a file from a template. The template file can contain variables which are formatted "${variable}"
.
* All those variables will be replaced, for which a value has been passed in the map variables
.
*
* Example:
*
* *** * Dear ${receipient.fullName}, * this is a spam mail trying to sell you ${product.name} for a very cheap price. * Best regards, ${sender.fullName} * *** **
variables
needs to contain values for these keys:
* * If a key is missing in the map, the variable will not be replaced but instead written as-is into the destination file (a warning will be * logged). *
* * @param destinationFile The file (absolute!) that shall be created out of the template. * @param templateFile The template file to use. Must not benull
.
* @param variables This map defines what variable has to be replaced by what value. The
* key is the variable name (without '$' and brackets '{', '}'!) and the value is the
* value for the variable to replace. This must not be null
.
* @deprecated Use {@link IOUtil#replaceTemplateVariables(File, File, Map, String)} instead. This mehtod
* will delegate to that using {@link Charset#defaultCharset()}.
*/
@Deprecated
public static void replaceTemplateVariables(File destinationFile, File templateFile, MapcanReturnNull = true
.
*
* @param objects An array of objects - can be null
.
* @return an ArrayList
(or null
if objects == null
).
* @deprecated Use {@link CollectionUtil#array2ArrayList(T[])} instead
*/
@Deprecated
public static false
, the result will never be null
,
* but an empty list if objects
is null.
* @param objects An array of objects - can be null
.
* @return an ArrayList
- never null
.
* The ArrayList
is empty if objects
is null
and
* canReturnNull
is false
. If canReturnNull == true
* and objects == null
, the result will be null
.
* @deprecated Use {@link CollectionUtil#array2ArrayList(T[],boolean)} instead
*/
@Deprecated
public static canReturnNull = true
.
*
* @param objects An array of objects - can be null
.
* @return an ArrayList
(or null
, if objects == null
).
* @deprecated Use {@link CollectionUtil#array2HashSet(T[])} instead
*/
@Deprecated
public static false
, the result will never be null
,
* but an empty list if objects
is null.
* @param objects An array of objects - can be null
.
* @return an ArrayList
- never null
.
* The ArrayList
is empty if objects
is null
and
* canReturnNull
is false
. If canReturnNull == true
* and objects == null
, the result will be null
.
* @deprecated Use {@link CollectionUtil#array2HashSet(T[],boolean)} instead
*/
@Deprecated
public static canReturnNull = true
.
*
* @param c Either null
or a Collection
with instances of the type specified by clazz
(or descendants of it).
* @param clazz The type of the elements of the returned object-array (e.g. String.class
for the returned type String[]
).
* @return a typed object array (or null
, if c == null
).
* @deprecated Use {@link CollectionUtil#collection2TypedArray(Collectionnull
or a Collection
with instances of the type specified by clazz
(or descendants of it).
* @param clazz The type of the elements of the returned object-array (e.g. String.class
for the returned type String[]
).
* @param canReturnNull If false
, the result will never be null
,
* but an empty array if c == null
.
*
* @return a typed object array (or null
, if c == null && canReturnNull
).
* If canReturnNull
is false and c == null
, an empty array will be returned.
* @deprecated Use {@link CollectionUtil#collection2TypedArray(Collection* This method used upper-case "A"..."F" till version 1.2 of this class. From version 1.3 of this class on, * it uses "a"..."f" because it now delegates to {@link #encodeHexStr(byte[])}. *
* @param in The source byte array * @return the hex string. * @deprecated Use {@link #encodeHexStr(byte[])} instead. */ @Deprecated public static String byteArrayToHexString(byte in[]) { return encodeHexStr(in); } /** * Rotates value n bits left through the sign. * (source: http://mindprod.com/jgloss/rotate.html) * * @param value Value to rotated. * @param n how many bits to rotate left. * must be in range 0..31 * @return Value rotated. */ public static int rotateLeft ( int value, int n ) { return( value << n ) | ( value >>> (32 - n) ); } /** * Rotates value n bits right through the sign. * (source: http://mindprod.com/jgloss/rotate.html) * * @param value Value to rotated. * @param n how many bits to rotate night. * must be in range 0..31 * @return Value rotated. */ public static int rotateRight ( int value, int n ) { return( value >>> n ) | ( value << (32- n) ); } /** * Rotates value n bits left through the sign. * (source: http://mindprod.com/jgloss/rotate.html) * * @param value Value to rotated. * @param n how many bits to rotate left. * must be in range 0..63 * @return Value rotated. */ public static long rotateLeft ( long value, int n ) { return( value << n ) | ( value >>> (64 - n) ); } /** * Rotates value n bits right through the sign. * (source: http://mindprod.com/jgloss/rotate.html) * * @param value Value to rotated. * @param n how many bits to rotate night. * must be in range 0..63 * @return Value rotated. */ public static long rotateRight ( long value, int n ) { return( value >>> n ) | ( value << (64- n) ); } /** * Get the user name of the user who is currently authenticated at the operating system. * This method simply callsSystem.getProperty("user.name");
.
*
* @return the user name of the current operating system user.
*/
public static String getUserName()
{
return System.getProperty("user.name"); //$NON-NLS-1$
}
// /**
// * Get all system properties and encode the values cause they might contain illegal characters (in windows)
// * @return the encoded system properties.
// */
// public static java.util.Properties getEncodedSystemProperties(Set