de.fu_berlin.ties.util
Class Util

java.lang.Object
  extended by de.fu_berlin.ties.util.Util

public final class Util
extends Object

A static class that provides general utility methods. No instances of this class can be created, only the static members should be used.

Version:
$Revision: 1.40 $, $Date: 2006/10/21 16:04:27 $, $Author: siefkes $
Author:
Christian Siefkes

Field Summary
static String CONFIG_LOGGER_LOG
          Configuration key: Only messages with this priority or higher are logged.
static String CONFIG_LOGGER_SHOW
          Configuration key: Only messages with this priority or higher are written to standard output (but only if covered by CONFIG_LOGGER_LOG).
static char FALSE_CHAR
          Character representing the boolean value false: '-'.
static org.apache.log.Logger LOG
          The logger used in the TIE system.
static String NAN
          String recognized as Not-a-Number when parsing floating-point numbers: "NaN" (ignoring case).
static char TRUE_CHAR
          Character representing the boolean value true: '+'.
 
Constructor Summary
Util()
          Util instances should NOT be constructed in standard programming.
 
Method Summary
static void appendPositiveNumber(StringBuilder appender, long number, int minDigits, String prefix, boolean appendAlways)
          Appends a non-negative number to a string buffer.
static boolean asBoolean(char character)
          Converts a character into a boolean primitive.
static boolean asBoolean(Object obj)
          Converts an object into a boolean primitive.
static char asChar(Object obj)
          Converts an object into a char primitive.
static double asDouble(Object obj)
          Converts an object into a double primitive.
static float asFloat(Object obj)
          Converts an object into a float primitive.
static int asInt(Object obj)
          Converts an object into an integer primitive.
static long asLong(Object obj)
          Converts an object into a long primitive.
static short asShort(Object obj)
          Converts an object into a short primitive.
static String asString(Object obj)
          Converts an object into a String.
static void configureLog(TiesConfiguration config)
          Reconfigures the logger from the CONFIG_LOGGER_LOG and CONFIG_LOGGER_SHOW values in the provided configuration.
static Object createObject(Class type, Object[] params, Class paramType)
          Creates an object of a specified type.
static Object createObject(Class type, Object[] params, Class[] paramTypes)
          Creates an object of a specified type.
static Object createObject(Class type, String[] params)
          Delegates to createObject(Class, Object[], Class), setting the paramType to the String class.
static Object createObject(String[] classDef)
          Delegates to createObject(Class, String[]), reading the class name from the first element in the array.
static void ensureNonNegative(double number, String identifier)
          Ensures that a number is positive or 0, throwing an exception if this condition is violated.
static void ensureNonNegative(long number, String identifier)
          Ensures that a number is positive or 0, throwing an exception if this condition is violated.
static String format(double number)
          Formats the given number, using at most 4 fraction digits.
static String format(double number, int maxFractDigits)
          Formats the given number, using at most the specified number of fraction digits.
static String formatDurationInMillisecs(long msecs)
          Formats a duration.
static String formatDurationInSeconds(double secs)
          Formats a duration.
static long longHash(String string)
          Returns a long hash code for a string.
static Random reproducibleRandom()
          Returns an instance of a pseudo-random number generator that uses a fixed seed, so the same sequence of calls to each object created by this method will yield the same sequence of pseudo-random numbers.
static String showDuration(long startTime)
          Calculated and prints the time passed since a given start time (in English).
static char toChar(boolean value)
          Converts a boolean value to a single character representing this value.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

LOG

public static final org.apache.log.Logger LOG
The logger used in the TIE system. The Avalon LogKit (bundled with Velocity) is used for logging. All log messages are written to a log file; message with priority INFO or higher are also written to standard out.


CONFIG_LOGGER_LOG

public static final String CONFIG_LOGGER_LOG
Configuration key: Only messages with this priority or higher are logged.

See Also:
Constant Field Values

CONFIG_LOGGER_SHOW

public static final String CONFIG_LOGGER_SHOW
Configuration key: Only messages with this priority or higher are written to standard output (but only if covered by CONFIG_LOGGER_LOG).

See Also:
Constant Field Values

NAN

public static final String NAN
String recognized as Not-a-Number when parsing floating-point numbers: "NaN" (ignoring case).

See Also:
Constant Field Values

TRUE_CHAR

public static final char TRUE_CHAR
Character representing the boolean value true: '+'.

See Also:
Constant Field Values

FALSE_CHAR

public static final char FALSE_CHAR
Character representing the boolean value false: '-'.

See Also:
Constant Field Values
Constructor Detail

Util

public Util()
Util instances should NOT be constructed in standard programming. Instead, the method of this class should be called in a static way. This constructor is public to permit tools that require a JavaBean instance to operate.

Method Detail

appendPositiveNumber

public static void appendPositiveNumber(StringBuilder appender,
                                        long number,
                                        int minDigits,
                                        String prefix,
                                        boolean appendAlways)
                                 throws IllegalArgumentException
Appends a non-negative number to a string buffer.

Parameters:
appender - the string buffer to append to
number - the number to append; must not be negative
minDigits - the minimum number of digits to print
prefix - a prefix to print in front of the number, if not null
appendAlways - if true, the number is always printed; otherwise only positive numbers are printed -- in this case the appender is not modified if the number is 0
Throws:
IllegalArgumentException - if number < 0

asBoolean

public static boolean asBoolean(char character)
                         throws IllegalArgumentException
Converts a character into a boolean primitive. TRUE_CHAR is converted to true; FALSE_CHAR is converted to false. An exception is thrown in all other cases.

Parameters:
character - the character to convert
Returns:
the converted boolean
Throws:
IllegalArgumentException - if the character cannot be converted into a boolean

asBoolean

public static boolean asBoolean(Object obj)
                         throws IllegalArgumentException
Converts an object into a boolean primitive. For a Boolean object, the contained boolean primitive is returned.

Otherwise the object's toString() output is parsed calling BooleanUtils.toBooleanObject(java.lang.String), i.e. The strings "true", "on", and "yes" are accepted for a true value; "false", "off", and "no" are accepted for false; case and surrounding whitespace are ignored. If the string contains a single character, the result of asBoolean(char) is returned. An exception is thrown for all other strings.

If the specified object is null, false is returned.

Parameters:
obj - the object to check
Returns:
the converted boolean
Throws:
IllegalArgumentException - if the object's toString() output cannot be parsed as a boolean

asChar

public static char asChar(Object obj)
                   throws IndexOutOfBoundsException
Converts an object into a char primitive. For a Character object, the contained char primitive is returned.

Otherwise the first non-whitespace character of the object's toString() output is returned. An exception is thrown if the string is empty or contains only whitespace.

If the specified object is null, Character.MIN_VALUE (the smallest character value) is returned.

Parameters:
obj - the object to check
Returns:
the converted char
Throws:
IndexOutOfBoundsException - if the object's toString() output is the empty string (after trimming outer whitespace)

asDouble

public static double asDouble(Object obj)
                       throws NumberFormatException
Converts an object into a double primitive. For a Number object, the contained number is converted to a double -- this may involve rounding.

Otherwise the object's toString() output is parsed using the Double.parseDouble(java.lang.String) method. If the string value to equal to NAN (ignoring case), Double.NaN is returned.

If the specified object is null, -1.0 is returned.

Parameters:
obj - the object to check
Returns:
the converted double
Throws:
NumberFormatException - if the object's toString() output does not contain a parsable double

asFloat

public static float asFloat(Object obj)
                     throws NumberFormatException
Converts an object into a float primitive. For a Number object, the contained number is converted to a float -- this may involve rounding.

Otherwise the object's toString() output is parsed using the Float.parseFloat(java.lang.String) method. If the string value to equal to NAN (ignoring case), Float.NaN is returned.

If the specified object is null, -1 is returned.

Parameters:
obj - the object to check
Returns:
the converted float
Throws:
NumberFormatException - if the object's toString() output does not contain a parsable float

asInt

public static int asInt(Object obj)
                 throws NumberFormatException
Converts an object into an integer primitive. For a Number object, the contained number is converted to a int -- this may involve rounding or truncation.

Otherwise the object's toString() output is parsed using the Integer.decode(java.lang.String) method.

If the specified object is null, -1 is returned.

Parameters:
obj - the object to check
Returns:
the converted int
Throws:
NumberFormatException - if the object's toString() output does not contain a parsable int

asLong

public static long asLong(Object obj)
                   throws NumberFormatException
Converts an object into a long primitive. For a Number object, the contained number is converted to a long -- this may involve rounding or truncation.

Otherwise the object's toString() output is parsed using the Long.decode(java.lang.String) method.

If the specified object is null, -1 is returned.

Parameters:
obj - the object to check
Returns:
the converted long
Throws:
NumberFormatException - if the object's toString() output does not contain a parsable long

asShort

public static short asShort(Object obj)
                     throws NumberFormatException
Converts an object into a short primitive. For a Number object, the contained number is converted to a short -- this may involve rounding or truncation.

Otherwise the object's toString() output is parsed using the Short.decode(java.lang.String) method.

If the specified object is null, -1 is returned.

Parameters:
obj - the object to check
Returns:
the converted short
Throws:
NumberFormatException - if the object's toString() output does not contain a parsable short

asString

public static String asString(Object obj)
Converts an object into a String. For arrays of objects (but not, currently, for array of primitives), the output of CollUtils.flatten(Object[]) is returned; for other non-null objects, the output of Object.toString() is returned; otherwise, null is returned.

Parameters:
obj - the object to check
Returns:
the output of the object's Object.toString(); or null if obj is null

configureLog

public static void configureLog(TiesConfiguration config)
Reconfigures the logger from the CONFIG_LOGGER_LOG and CONFIG_LOGGER_SHOW values in the provided configuration. This method should be used with care since it affects the global logging. It is called by Main.main(String[]) after configurations and command-line propertis have been read.

Parameters:
config - the configuration to use

createObject

public static Object createObject(String[] classDef)
                           throws IllegalArgumentException,
                                  ClassNotFoundException,
                                  InstantiationException,
                                  SecurityException
Delegates to createObject(Class, String[]), reading the class name from the first element in the array.

Parameters:
classDef - defines the class to create: the first element must be a string giving the fully qualified class name; any further elements are passed as constructor parameters
Returns:
the created object; the returned object will be an instance of the specified type
Throws:
IllegalArgumentException - if the class name is missing (array is empty)
ClassNotFoundException - if the class cannot be located
InstantiationException - if instantiation failed
SecurityException - if access to the required reflection information is denied

createObject

public static Object createObject(Class type,
                                  String[] params)
                           throws InstantiationException,
                                  SecurityException
Delegates to createObject(Class, Object[], Class), setting the paramType to the String class.

Parameters:
type - the class of the object to create
params - the objects in this array are passed to the constructor; if null or empty, the default constructor is used
Returns:
the created object; the returned object will be an instance of type
Throws:
InstantiationException - if instantiation failed
SecurityException - if access to the required reflection information is denied

createObject

public static Object createObject(Class type,
                                  Object[] params,
                                  Class paramType)
                           throws InstantiationException,
                                  SecurityException
Creates an object of a specified type. The object must have a public constructor that accepts params.length arguments of the specified paramType.

Parameters:
type - the class of the object to create
params - the objects in this array are passed to the constructor; if null or empty, the default constructor is used
paramType - the type of the elements stored in the params array
Returns:
the created object; the returned object will be an instance of type
Throws:
InstantiationException - if instantiation failed
SecurityException - if access to the required reflection information is denied

createObject

public static Object createObject(Class type,
                                  Object[] params,
                                  Class[] paramTypes)
                           throws IllegalArgumentException,
                                  InstantiationException,
                                  SecurityException
Creates an object of a specified type. The object must have a public constructor that accepts params.length arguments of the specified types.

Parameters:
type - the class of the object to create
params - the objects in this array are passed to the constructor; if null or empty, the default constructor is used
paramTypes - the types of the elements stored in the params list
Returns:
the created object; the returned object will be an instance of type
Throws:
IllegalArgumentException - if params and paramTypes are of different lengths
InstantiationException - if instantiation failed
SecurityException - if access to the required reflection information is denied

formatDurationInMillisecs

public static String formatDurationInMillisecs(long msecs)
Formats a duration. The generated string has the form "daysD+hours:minutes:secs.millisecs". Days and milliseconds are omitted if 0; the time fields are omitted if all of them are 0, but only if days are present (to avoid returning an empty string). Samples: 2D+03:02:43.666, 01:00:00, 1D, 00:05:00.123, 1D+04:19:03, 00:00:00.

Parameters:
msecs - the number of milliseconds
Returns:
a formatted representation as specified above

formatDurationInSeconds

public static String formatDurationInSeconds(double secs)
                                      throws IllegalArgumentException
Formats a duration. The generated string has the form "daysD+hours:minutes:secs.millisecs". Days and milliseconds are omitted if 0; the time fields are omitted if all of them are 0, but only if days are present (to avoid returning an empty string). Samples: 2D+03:02:43.666, 01:00:00, 1D, 00:05:00.123, 1D+04:19:03, 00:00:00.

Parameters:
secs - the number of seconds; must be nonnegative
Returns:
a formatted representation as specified above
Throws:
IllegalArgumentException - if secs < 0

ensureNonNegative

public static void ensureNonNegative(double number,
                                     String identifier)
                              throws IllegalArgumentException
Ensures that a number is positive or 0, throwing an exception if this condition is violated.

Parameters:
number - the number to check
identifier - string used to describe the number in the thrown exception
Throws:
IllegalArgumentException - if number < 0.0

ensureNonNegative

public static void ensureNonNegative(long number,
                                     String identifier)
                              throws IllegalArgumentException
Ensures that a number is positive or 0, throwing an exception if this condition is violated.

Parameters:
number - the number to check
identifier - string used to describe the number in the thrown exception
Throws:
IllegalArgumentException - if number < 0

format

public static String format(double number)
Formats the given number, using at most 4 fraction digits.

Parameters:
number - the number for format
Returns:
the formatted number

format

public static String format(double number,
                            int maxFractDigits)
Formats the given number, using at most the specified number of fraction digits.

Parameters:
number - the number for format
maxFractDigits - maximum number of digits allowed in the fraction portion of the number
Returns:
the formatted number

longHash

public static long longHash(String string)
Returns a long hash code for a string. This method is adapted from the String.hashCode() method, but returns a long (64 bit) value instead of an integer (32 bit). The hash code for a is computed as
 s[0]*313^(n-1) + s[1]*313^(n-2) + ... + s[n-1]
 
using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

Parameters:
string - the string to hash
Returns:
a long hash code value for the string

reproducibleRandom

public static Random reproducibleRandom()
Returns an instance of a pseudo-random number generator that uses a fixed seed, so the same sequence of calls to each object created by this method will yield the same sequence of pseudo-random numbers.

Returns:
a new source of pseudo-randomness that will return reproducable pseudo-random numbers

showDuration

public static String showDuration(long startTime)
Calculated and prints the time passed since a given start time (in English).

Parameters:
startTime - the start time in milliseconds
Returns:
a formatted string containing the time difference between the start time and the current time

toChar

public static char toChar(boolean value)
Converts a boolean value to a single character representing this value.

Parameters:
value - the boolean value to convert
Returns:
TRUE_CHAR if the value is true; FALSE_CHAR otherwise


Copyright © 2003-2007 Christian Siefkes. All Rights Reserved.