org.eigenbase.util
Class Util

java.lang.Object
  extended by openjava.mop.Toolbox
      extended by org.eigenbase.util.Util

public class Util
extends Toolbox

Miscellaneous utility functions.

Version:
$Id: //open/dev/farrago/src/org/eigenbase/util/Util.java#51 $
Author:
jhyde

Nested Class Summary
private static class Util.BacktrackVisitor<R>
           
static class Util.FoundOne
          Exception used to interrupt a tree walk of any kind.
static class Util.SqlNodeDescriptor
          Describes a node, its parent and if and where in the parent a node lives.
 
Field Summary
private static Toolkit awtToolkit
           
static String awtWorkaroundProperty
          Name of the system property that controls whether the AWT work-around is enabled.
private static boolean driversLoaded
           
static Object[] emptyObjectArray
           
static SqlMoniker[] emptySqlMonikerArray
           
static String[] emptyStringArray
           
static String fileSeparator
          System-dependent file separator, for example, "/" or "\."
static String fileTimestampFormat
          Datetime format string for generating a timestamp string to be used as part of a filename.
private static Pattern javaIdPattern
          Regular expression for a valid java identifier which contains no underscores and can therefore be returned intact by toJavaId(java.lang.String, int).
static String lineSeparator
          System-dependent newline character.
private static Map<Class,Map<String,? extends Enum>> mapClazzToMapNameToEnum
          Maps classes to the map of their enum values.
 
Constructor Summary
Util()
           
 
Method Summary
private static void appendPosixDaylightTransition(TimeZone tz, StringBuilder buf, int mode, int day, int month, int dayOfWeek, int time, int timeMode, boolean verbose, boolean isEnd)
          Writes a daylight savings time transition to a POSIX timezone description.
private static void appendPosixTime(StringBuilder buf, int millis)
          Given a time expressed in milliseconds, append the time formatted as "hh[:mm[:ss]]".
static
<E> Iterable<E>
cast(Iterable<? super E> iterable, Class<E> clazz)
          Converts an Iterable whose members are automatically down-cast to a given type.
static
<E> Iterator<E>
cast(Iterator<?> iter, Class<E> clazz)
          Converts a iterator whose members are automatically down-cast to a given type.
static
<E> List<E>
cast(List<? super E> list, Class<E> clazz)
          Converts a list whose members are automatically down-cast to a given type.
static Expression clone(Expression exp)
           
static Expression[] clone(Expression[] a)
           
static int[] clone(int[] a)
           
static StatementList clone(StatementList e)
           
static String[] clone(String[] a)
           
static boolean contains(String[] a, int length, String s)
          Returns whether an array of strings contains a given string among the first length entries.
static
<T> T
deprecated(T argument, boolean fail)
          Deprecated. If a piece of code calls this method, it indicates that the code needs to be cleaned up.
static void discard(boolean b)
          Does nothing with its argument.
static void discard(double d)
          Does nothing with its argument.
static void discard(int i)
          Does nothing with its argument.
static void discard(Object o)
          Does nothing with its argument.
static
<T extends Enum<T>>
Map<String,T>
enumConstants(Class<T> clazz)
          Creates a map of the values of an enumeration by name.
static
<T extends Enum<T>>
T
enumVal(Class<T> clazz, String name)
          Returns the value of an enumeration with a particular name.
static boolean equal(Object[] s0, Object[] s1)
          Returns whether two arrays are equal or are both null.
static boolean equal(Object s0, Object s1)
          Returns whether two objects are equal or are both null.
static
<E> Collection<E>
filter(Collection<?> collection, Class<E> includeFilter)
           
static
<E> Iterable<E>
filter(Iterable<? extends Object> iterable, Class<E> includeFilter)
          Makes a collection of untyped elements appear as a list of strictly typed elements, by filtering out those which are not of the correct type.
static
<E> List<E>
filter(List<?> list, Class<E> includeFilter)
          Returns a subset of a list containing only elements of a given type.
static Util.SqlNodeDescriptor findIdentifier(SqlNode node)
          Searches recursively for a SqlIdentifier.
static String flatArrayToString(Object[] a)
          Prints a flat array of objects as [e1,e2,...]
static Charset getDefaultCharset()
          Returns the Charset object representing the value of SaffronProperties.defaultCharset
static String getFileTimestamp()
          Gets a timestamp string for use in file names.
static String getMessages(Throwable t)
          Retrieves messages in a exception and writes them to a string.
static String getSalesConnectString()
          Returns the connect string with which to connect to the 'Sales' test database.
static String getStackTrace(Throwable t)
          Returns the stack trace of a throwable.
static int hash(int i, int j)
          Combines two integers into a hash code.
static int hash(int h, Object o)
          Computes a hash code from an existing hash code and an object (which may be null).
static int hashArray(int h, Object[] a)
          Computes a hash code from an existing hash code and an array of objects (which may be null).
static boolean isNullOrEmpty(String s)
           
(package private) static boolean isStatic(Member member)
           
private static void loadDrivers()
           
static void loadLibrary(String libName)
          Uses System.loadLibrary(String) to load a native library correctly under mingw (Windows/Cygwin) and Linux environments.
static
<T> Set<T>
minus(Set<T> set1, Set<T> set2)
          Returns a set of the elements which are in set1 but not in set2, without modifying either.
static RuntimeException needToImplement(Object o)
          Returns a RuntimeException indicating that a particular feature has not been implemented, but should be.
static ProcessBuilder newAppProcess(String[] cmdarray)
          Constructs a ProcessBuilder to run an external application.
static Error newInternal()
           
static Error newInternal(String s)
           
static Error newInternal(Throwable e)
           
static Error newInternal(Throwable e, String s)
           
static double nLogN(double d)
          Computes nlogn(n) using the natural logarithm (or n if n<Math.E, so the result is never negative.
static void permAssert(boolean b, String description)
          Checks an invariant.
static void post(boolean b, String description)
          Checks a post-condition.
static void pre(boolean b, String description)
          Checks a pre-condition.
static void print(PrintWriter pw, Object o)
          Prints an object using reflection.
static void print(PrintWriter pw, Object o, int indent)
           
static void printJavaString(PrintWriter pw, String s, boolean nullMeansNull)
          Prints a string, enclosing in double quotes (") and escaping if necessary.
static void println(PrintWriter pw, Object o)
           
static String readAllAsString(Reader reader)
          Reads all remaining contents from a Reader and returns them as a string.
static String replace(String s, String find, String replace)
          Replaces every occurrence of find in s with replace.
static void restartIterator(Iterator iterator)
           
static String rpad(String s, int len)
          Pads a string with spaces up to a given length.
static String rtrim(String s)
          Trims trailing spaces from a string.
static int runApplication(String[] cmdarray, Logger logger, Reader appInput, Writer appOutput)
          Runs an external application.
static int runAppProcess(ProcessBuilder pb, Logger logger, Reader appInput, Writer appOutput)
          Runs an external application process.
static void squelchConnection(Connection connection)
          Closes a Connection, ignoring any SQL exception.
static void squelchReader(Reader reader)
          Closes a Reader, ignoring any I/O exception.
static void squelchStmt(Statement stmt)
          Closes a Statement, ignoring any SQL exception.
static void squelchStream(InputStream stream)
          Closes an InputStream, ignoring any I/O exception.
static void squelchStream(OutputStream stream)
          Closes an OutputStream, ignoring any I/O exception.
static void squelchWriter(Writer writer)
          Closes a Writer, ignoring any I/O exception.
static String stripDoubleQuotes(String value)
          Converts double-quoted Java strings to their contents.
static void swallow(Throwable e, Logger logger)
          Records that an exception has been caught but will not be re-thrown.
static Object[] toArray(Vector v)
          Deprecated. use Vector.toArray() on Java2
static Object[] toArray(Vector v, Object[] a)
          Equivalent to Vector.toArray(Object[]).
static String toJavaId(String s, int ordinal)
          Converts an arbitrary string into a string suitable for use as a Java identifier.
static
<T> List<T>
toList(Iterator<T> iter)
          Materializes the results of a Iterator as a List.
static Map<String,String> toMap(Properties properties)
          Converts a Properties object to a Map<String, String>.
static String toPosix(TimeZone tz, boolean verbose)
          Converts a Java timezone to POSIX format, so that the boost C++ library can instantiate timezone objects.
static String toScientificNotation(BigDecimal bd)
          Formats a BigDecimal value to a string in scientific notation For example
A value of 0.00001234 would be formated as 1.234E-5 A value of 100000.00 would be formated as 1.00E5 A value of 100 (scale zero) would be formated as 1E2
If bd has a precision higher than 20, this method will truncate the output string to have a precision of 20 (no rounding will be done, just a truncate).
static URL toURL(File file)
          Creates a file-protocol URL for the given file.
static
<E extends Enum<E>>
Error
unexpected(E value)
          Returns an exception indicating that we didn't expect to find this enumeration here.
static String uniqueFieldName(String[] names, int length, String s)
          Generates a unique name
 
Methods inherited from class openjava.mop.Toolbox
append, append, append, append, arrayForNames, forNameAnyway, generateParameters, generateParameters, isAcceptable, isAdaptableTo, isSame, nameForJavaClassName, nameToJavaClassName, overridesOn, overridesOn, overridesOn, pickupAcceptableConstructor, pickupAcceptableConstructors, pickupAcceptableMethod, pickupAcceptableMethods, pickupAcceptableMethodsByParameterTypes, pickupConstructor, pickupField, pickupMethod, pickupMethodByParameterTypes, pickupMethodsByName, pickupMostSpecified, pickupMostSpecified, removeTheDefaults, removeTheDefaults, removeTheDefaults, removeTheDefaults, removeTheNonPublics, removeTheNonPublics, removeTheNonPublics, removeTheNonPublics, removeThePrivates, removeThePrivates, removeThePrivates, removeThePrivates, TNsForOJClasses
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

awtWorkaroundProperty

public static final String awtWorkaroundProperty
Name of the system property that controls whether the AWT work-around is enabled. This workaround allows Farrago to load its native libraries despite a conflict with AWT and allows applications that use AWT to function normally.

See Also:
loadLibrary(String), Constant Field Values

lineSeparator

public static final String lineSeparator
System-dependent newline character.


fileSeparator

public static final String fileSeparator
System-dependent file separator, for example, "/" or "\."


fileTimestampFormat

public static final String fileTimestampFormat
Datetime format string for generating a timestamp string to be used as part of a filename. Conforms to SimpleDateFormat conventions.

See Also:
Constant Field Values

emptyObjectArray

public static final Object[] emptyObjectArray

emptyStringArray

public static final String[] emptyStringArray

emptySqlMonikerArray

public static final SqlMoniker[] emptySqlMonikerArray

driversLoaded

private static boolean driversLoaded

javaIdPattern

private static final Pattern javaIdPattern
Regular expression for a valid java identifier which contains no underscores and can therefore be returned intact by toJavaId(java.lang.String, int).


awtToolkit

private static Toolkit awtToolkit
See Also:
loadLibrary(String)

mapClazzToMapNameToEnum

private static final Map<Class,Map<String,? extends Enum>> mapClazzToMapNameToEnum
Maps classes to the map of their enum values. Uses a weak map so that classes are not prevented from being unloaded.

Constructor Detail

Util

public Util()
Method Detail

discard

public static final void discard(Object o)
Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it.


discard

public static final void discard(int i)
Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it.


discard

public static final void discard(boolean b)
Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it.


discard

public static final void discard(double d)
Does nothing with its argument. Call this method when you have a value you are not interested in, but you don't want the compiler to warn that you are not using it.


swallow

public static final void swallow(Throwable e,
                                 Logger logger)
Records that an exception has been caught but will not be re-thrown. If the tracer is not null, logs the exception to the tracer.

Parameters:
e - Exception
logger - If not null, logs exception to this logger

equal

public static final boolean equal(Object s0,
                                  Object s1)
Returns whether two objects are equal or are both null.


equal

public static final boolean equal(Object[] s0,
                                  Object[] s1)
Returns whether two arrays are equal or are both null.


clone

public static StatementList clone(StatementList e)

clone

public static String[] clone(String[] a)

clone

public static int[] clone(int[] a)

hash

public static int hash(int i,
                       int j)
Combines two integers into a hash code.


hash

public static int hash(int h,
                       Object o)
Computes a hash code from an existing hash code and an object (which may be null).


hashArray

public static int hashArray(int h,
                            Object[] a)
Computes a hash code from an existing hash code and an array of objects (which may be null).


minus

public static <T> Set<T> minus(Set<T> set1,
                               Set<T> set2)
Returns a set of the elements which are in set1 but not in set2, without modifying either.


nLogN

public static double nLogN(double d)
Computes nlogn(n) using the natural logarithm (or n if n<Math.E, so the result is never negative.


print

public static void print(PrintWriter pw,
                         Object o)
Prints an object using reflection. We can handle null; arrays of objects and primitive values; for regular objects, we print all public fields.


print

public static void print(PrintWriter pw,
                         Object o,
                         int indent)

printJavaString

public static final void printJavaString(PrintWriter pw,
                                         String s,
                                         boolean nullMeansNull)
Prints a string, enclosing in double quotes (") and escaping if necessary. For examples, printDoubleQuoted(w,"x\"y",false) prints "x\"y".


println

public static void println(PrintWriter pw,
                           Object o)

flatArrayToString

public static String flatArrayToString(Object[] a)
Prints a flat array of objects as [e1,e2,...]


toScientificNotation

public static String toScientificNotation(BigDecimal bd)
Formats a BigDecimal value to a string in scientific notation For example

replace

public static final String replace(String s,
                                   String find,
                                   String replace)
Replaces every occurrence of find in s with replace.


toURL

public static URL toURL(File file)
                 throws MalformedURLException
Creates a file-protocol URL for the given file.

Throws:
MalformedURLException

getFileTimestamp

public static String getFileTimestamp()
Gets a timestamp string for use in file names. The generated timestamp string reflects the current time.


clone

public static Expression clone(Expression exp)

clone

public static Expression[] clone(Expression[] a)

stripDoubleQuotes

public static String stripDoubleQuotes(String value)
Converts double-quoted Java strings to their contents. For example, "foo\"bar" becomes foo"bar.


toJavaId

public static String toJavaId(String s,
                              int ordinal)
Converts an arbitrary string into a string suitable for use as a Java identifier.

The mapping is one-to-one (that is, distinct strings will produce distinct java identifiers). The mapping is also reversible, but the inverse mapping is not implemented.

A valid Java identifier must start with a Unicode letter, underscore, or dollar sign ($). The other characters, if any, can be a Unicode letter, underscore, dollar sign, or digit.

This method uses an algorithm similar to URL encoding. Valid characters are unchanged; invalid characters are converted to an underscore followed by the hex code of the character; and underscores are doubled.

Examples:

"JUnit testcase:"

toList

public static <T> List<T> toList(Iterator<T> iter)
Materializes the results of a Iterator as a List.

Parameters:
iter - iterator to materialize
Returns:
materialized list

toArray

public static Object[] toArray(Vector v)
Deprecated. use Vector.toArray() on Java2


toArray

public static Object[] toArray(Vector v,
                               Object[] a)
Equivalent to Vector.toArray(Object[]).


isStatic

static boolean isStatic(Member member)

isNullOrEmpty

public static boolean isNullOrEmpty(String s)
Returns:
true if s==null or if s.length()==0

getSalesConnectString

public static String getSalesConnectString()
Returns the connect string with which to connect to the 'Sales' test database. In the process, it loads the necessary drivers.


loadDrivers

private static void loadDrivers()

getDefaultCharset

public static Charset getDefaultCharset()
Returns the Charset object representing the value of SaffronProperties.defaultCharset

Throws:
IllegalCharsetNameException - If the given charset name is illegal
UnsupportedCharsetException - If no support for the named charset is available in this instance of the Java virtual machine

newInternal

public static Error newInternal()

newInternal

public static Error newInternal(String s)

newInternal

public static Error newInternal(Throwable e)

newInternal

public static Error newInternal(Throwable e,
                                String s)

getMessages

public static String getMessages(Throwable t)
Retrieves messages in a exception and writes them to a string. In the string returned, each message will appear on a different line.

Returns:
a non-null string containing all messages of the exception

getStackTrace

public static String getStackTrace(Throwable t)
Returns the stack trace of a throwable. Called from native code.

Parameters:
t - Throwable
Returns:
Stack trace

pre

public static void pre(boolean b,
                       String description)
Checks a pre-condition.

For example,

 /**
   * @ pre x != 0
   * /
 void foo(int x) {
     Util.pre(x != 0, "x != 0");
 }

Parameters:
b - Result of evaluating the pre-condition.
description - Description of the pre-condition.

post

public static void post(boolean b,
                        String description)
Checks a post-condition.

For example,

 /**
   * @ post return != 0
   * /
 void foo(int x) {
     int res = bar(x);
     Util.post(res != 0, "return != 0");
 }

Parameters:
b - Result of evaluating the pre-condition.
description - Description of the pre-condition.

permAssert

public static void permAssert(boolean b,
                              String description)
Checks an invariant.

This is similar to assert keyword, except that the condition is always evaluated even if asserts are disabled.


needToImplement

public static RuntimeException needToImplement(Object o)
Returns a RuntimeException indicating that a particular feature has not been implemented, but should be.

If every 'hole' in our functionality uses this method, it will be easier for us to identity the holes. Throwing a UnsupportedOperationException isn't as good, because sometimes we actually want to partially implement an API.

Example usage:

class MyVisitor extends BaseVisitor {
     void accept(Foo foo) {
         // Exception will identify which subclass forgot to override
         // this method
         throw Util.needToImplement(this);
     }
 }

Parameters:
o - The object which was the target of the call, or null. Passing the object gives crucial information if a method needs to be overridden and a subclass forgot to do so.
Returns:
an UnsupportedOperationException.

deprecated

public static <T> T deprecated(T argument,
                               boolean fail)
Deprecated. If a piece of code calls this method, it indicates that the code needs to be cleaned up.

Flags a piece of code as needing to be cleaned up before you check in.

Introduce a call to this method to indicate that a piece of code, or a javadoc comment, needs work before you check in. If you have an IDE which can easily trace references, this is an easy way to maintain a to-do list.

Checked-in code must never call this method: you must remove all calls/references to this method before you check in.

The argument has generic type and determines the type of the result. This allows you to use the method inside an expression, for example

int x = Util.deprecated(0, false);
but the usual usage is to pass in a descriptive string.

Examples

Example #1: Using deprecated to fail if a piece of supposedly dead code is reached

void foo(int x) {
     if (x < 0) {
         // If this code is executed, an error will be thrown.
         Util.deprecated("no longer need to handle negative numbers", true);
         bar(x);
     } else {
         baz(x);
     }
 }

Example #2: Using deprecated to comment out dead code

if (Util.deprecated(false, false)) {
     // This code will not be executed, but an error will not be thrown.
     baz();
 }

Parameters:
argument - Arbitrary argument to the method.
fail - Whether to throw an exception if this method is called
Returns:
The value of the argument.

loadLibrary

public static void loadLibrary(String libName)
Uses System.loadLibrary(String) to load a native library correctly under mingw (Windows/Cygwin) and Linux environments.

This method also implements a work-around for applications that wish to load AWT. AWT conflicts with some native libraries in a way that requires AWT to be loaded first. This method checks the system property named awtWorkaroundProperty and if it is set to "on" (default; case-insensitive) it pre-loads AWT to avoid the conflict.

Parameters:
libName - the name of the library to load, as in System.loadLibrary(String).

restartIterator

public static void restartIterator(Iterator iterator)

findIdentifier

public static Util.SqlNodeDescriptor findIdentifier(SqlNode node)
Searches recursively for a SqlIdentifier.

Parameters:
node - in which to look in
Returns:
null if no Identifier was found.

uniqueFieldName

public static String uniqueFieldName(String[] names,
                                     int length,
                                     String s)
Generates a unique name

Parameters:
names - Array of existing names
length - Number of existing names
s - Suggested name
Returns:
Name which does not match any of the names in the first length positions of the names array.

contains

public static boolean contains(String[] a,
                               int length,
                               String s)
Returns whether an array of strings contains a given string among the first length entries.

Parameters:
a - Array of strings
length - Number of entries to search
s - String to seek
Returns:
Whether array contains the name

readAllAsString

public static String readAllAsString(Reader reader)
                              throws IOException
Reads all remaining contents from a Reader and returns them as a string.

Parameters:
reader - reader to read from
Returns:
reader contents as string
Throws:
IOException

squelchStream

public static void squelchStream(InputStream stream)
Closes an InputStream, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.

Parameters:
stream - stream to close

squelchStream

public static void squelchStream(OutputStream stream)
Closes an OutputStream, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception. If you want to make sure that data has been successfully flushed, do NOT use this anywhere else; use stream.close() instead.

Parameters:
stream - stream to close

squelchReader

public static void squelchReader(Reader reader)
Closes a Reader, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.

Parameters:
reader - reader to close

squelchWriter

public static void squelchWriter(Writer writer)
Closes a Writer, ignoring any I/O exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception. If you want to make sure that data has been successfully flushed, do NOT use this anywhere else; use writer.close() instead.

Parameters:
writer - writer to close

squelchStmt

public static void squelchStmt(Statement stmt)
Closes a Statement, ignoring any SQL exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.

Parameters:
stmt - stmt to close

squelchConnection

public static void squelchConnection(Connection connection)
Closes a Connection, ignoring any SQL exception. This should only be used in finally blocks when it's necessary to avoid throwing an exception which might mask a real exception.

Parameters:
connection - connection to close

rtrim

public static String rtrim(String s)
Trims trailing spaces from a string.

Parameters:
s - string to be trimmed
Returns:
trimmed string

rpad

public static String rpad(String s,
                          int len)
Pads a string with spaces up to a given length.

Parameters:
s - string to be padded
len - desired length
Returns:
padded string

toPosix

public static String toPosix(TimeZone tz,
                             boolean verbose)
Converts a Java timezone to POSIX format, so that the boost C++ library can instantiate timezone objects.

POSIX IEEE 1003.1 defines a format for timezone specifications.

The boost C++ library can read these specifications and instantiate posix_time_zone objects from them. The purpose of this method, therefore, is to allow the C++ code such as the fennel calculator to use the same notion of timezone as Java code.

The format is as follows:

"std offset dst [offset],start[/time],end[/time]"
where:
  • 'std' specifies the abbrev of the time zone.
  • 'offset' is the offset from UTC, and takes the form [+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}
  • 'dst' specifies the abbrev of the time zone during daylight savings time
  • The second offset is how many hours changed during DST. Default=1
  • 'start' & 'end' are the dates when DST goes into (and out of) effect. They can each be one of three forms:
    1. Mm.w.d {month=1-12, week=1-5 (5 is always last), day=0-6}
    2. Jn {n=1-365 Feb29 is never counted}
    3. n {n=0-365 Feb29 is counted in leap years}
  • 'time' has the same format as 'offset', and defaults to 02:00:00

    For example:

    • "PST-8PDT01:00:00,M4.1.0/02:00:00,M10.1.0/02:00:00"; or more tersely
    • "PST-8PDT,M4.1.0,M10.1.0"

    (Real format strings do not contain spaces; they are in the above template only for readability.)

    Boost apparently diverges from the POSIX standard in how it treats the sign of timezone offsets. The POSIX standard states 'If preceded by a '-', the timezone shall be east of the Prime Meridian; otherwise, it shall be west', yet boost requires the opposite. For instance, PST has offset '-8' above. This method generates timezone strings consistent with boost's expectations.

    Parameters:
    tz - Timezone
    verbose - Whether to include fields which can be omitted because they have their default values
    Returns:
    Timezone in POSIX format (offset sign reversed, per boost's idiosyncracies)

appendPosixDaylightTransition

private static void appendPosixDaylightTransition(TimeZone tz,
                                                  StringBuilder buf,
                                                  int mode,
                                                  int day,
                                                  int month,
                                                  int dayOfWeek,
                                                  int time,
                                                  int timeMode,
                                                  boolean verbose,
                                                  boolean isEnd)
Writes a daylight savings time transition to a POSIX timezone description.

Parameters:
tz - Timezone
buf - Buffer to append to
mode - Transition mode
day - Day of transition
month - Month of transition
dayOfWeek - Day of week of transition
time - Time of transition in millis
timeMode - Mode of time transition
verbose - Verbose
isEnd - Whether this transition is leaving DST

appendPosixTime

private static void appendPosixTime(StringBuilder buf,
                                    int millis)
Given a time expressed in milliseconds, append the time formatted as "hh[:mm[:ss]]".

Parameters:
buf - Buffer to append to
millis - Milliseconds

runApplication

public static int runApplication(String[] cmdarray,
                                 Logger logger,
                                 Reader appInput,
                                 Writer appOutput)
                          throws IOException,
                                 InterruptedException
Runs an external application.

Parameters:
cmdarray - command and arguments, see ProcessBuilder
logger - if not null, command and exit status will be logged
appInput - if not null, data will be copied to application's stdin
appOutput - if not null, data will be captured from application's stdout and stderr
Returns:
application process exit value
Throws:
IOException
InterruptedException

newAppProcess

public static ProcessBuilder newAppProcess(String[] cmdarray)
Constructs a ProcessBuilder to run an external application.

Parameters:
cmdarray - command and arguments.
Returns:
a ProcessBuilder.

runAppProcess

public static int runAppProcess(ProcessBuilder pb,
                                Logger logger,
                                Reader appInput,
                                Writer appOutput)
                         throws IOException,
                                InterruptedException
Runs an external application process.

Parameters:
pb - ProcessBuilder for the application; might be returned by newAppProcess(java.lang.String[]).
logger - if not null, command and exit status will be logged here
appInput - if not null, data will be copied to application's stdin
appOutput - if not null, data will be captured from application's stdout and stderr
Returns:
application process exit value
Throws:
IOException
InterruptedException

cast

public static <E> List<E> cast(List<? super E> list,
                               Class<E> clazz)
Converts a list whose members are automatically down-cast to a given type.

If a member of the backing list is not an instanceof E, the accessing method (such as List.get(int)) will throw a ClassCastException.

All modifications are automatically written to the backing list. Not synchronized.

Parameters:
list - Backing list.
clazz - Class to cast to.
Returns:
A list whose members are of the desired type.

cast

public static <E> Iterator<E> cast(Iterator<?> iter,
                                   Class<E> clazz)
Converts a iterator whose members are automatically down-cast to a given type.

If a member of the backing iterator is not an instanceof E, Iterator.next()) will throw a ClassCastException.

All modifications are automatically written to the backing iterator. Not synchronized.

Parameters:
iter - Backing iterator.
clazz - Class to cast to.
Returns:
An iterator whose members are of the desired type.

cast

public static <E> Iterable<E> cast(Iterable<? super E> iterable,
                                   Class<E> clazz)
Converts an Iterable whose members are automatically down-cast to a given type.

All modifications are automatically written to the backing iterator. Not synchronized.

Parameters:
iterable - Backing iterable
clazz - Class to cast to
Returns:
An iterable whose members are of the desired type.

filter

public static <E> Iterable<E> filter(Iterable<? extends Object> iterable,
                                     Class<E> includeFilter)
Makes a collection of untyped elements appear as a list of strictly typed elements, by filtering out those which are not of the correct type.

The returned object is an Iterable, which makes it ideal for use with the 'foreach' construct. For example,

List<Number> numbers = Arrays.asList(1, 2, 3.14, 4, null, 6E23);
for (int myInt : filter(numbers, Integer.class)) {
    print(i);
}
will print 1, 2, 4.

Parameters:
iterable -
includeFilter -

filter

public static <E> Collection<E> filter(Collection<?> collection,
                                       Class<E> includeFilter)

filter

public static <E> List<E> filter(List<?> list,
                                 Class<E> includeFilter)
Returns a subset of a list containing only elements of a given type.

Modifications to the list are NOT written back to the source list.

Parameters:
list - List of objects
includeFilter - Class to filter for
Returns:
List of objects of given class (or a subtype)

toMap

public static Map<String,String> toMap(Properties properties)
Converts a Properties object to a Map<String, String>.

This is necessary because Properties is a dinosaur class. It ought to extend Map<String,String>, but instead extends Hashtable<Object,Object>.

Typical usage, to iterate over a Properties:

Properties properties;
for (Map.Entry<String, String> entry = Util.toMap(properties).entrySet()) {
println("key=" + entry.getKey() + ", value=" + entry.getValue());
}


unexpected

public static <E extends Enum<E>> Error unexpected(E value)
Returns an exception indicating that we didn't expect to find this enumeration here.

Parameters:
value - Enumeration value which was not expected
Returns:
an error, to be thrown

enumConstants

public static <T extends Enum<T>> Map<String,T> enumConstants(Class<T> clazz)
Creates a map of the values of an enumeration by name.

Parameters:
clazz - Enumeration class
Returns:
map of values

enumVal

public static <T extends Enum<T>> T enumVal(Class<T> clazz,
                                            String name)
Returns the value of an enumeration with a particular name.

Similar to Enum.valueOf(Class, String), but returns null rather than throwing IllegalArgumentException.

Type Parameters:
T - Enum class type
Parameters:
clazz - Enum class
name - Name of enum constant
Returns:
Enum constant or null