public class Util extends Object
| Modifier and Type | Class and Description |
|---|---|
static class |
Util.FoundOne
Exception used to interrupt a tree walk of any kind.
|
| Modifier and Type | Field and Description |
|---|---|
static String |
FILE_SEPARATOR
System-dependent file separator, for example, "/" or "\."
|
static String |
FILE_TIMESTAMP_FORMAT
Datetime format string for generating a timestamp string to be used as
part of a filename.
|
static String |
LINE_SEPARATOR
System-dependent newline character.
|
| Modifier and Type | Method and Description |
|---|---|
static <K,V> Map<K,V> |
asIndexMap(Collection<V> values,
com.google.common.base.Function<V,K> function)
Returns a map that is a view onto a collection of values, using the
provided function to convert a value to a key.
|
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 <T> String |
commaList(List<T> list)
Converts a list of a string, with commas between elements.
|
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 void |
debugCode(PrintStream out,
String code)
Prints the given code with line numbering.
|
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 boolean |
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>> |
enumConstants(Class<T> clazz)
Creates a map of the values of an enumeration by name.
|
static <T extends Enum<T>> |
enumVal(Class<T> clazz,
String name)
Returns the value of an enumeration with a particular name.
|
static <T> boolean |
equalShallow(List<? extends T> list0,
List<? extends T> list1)
Returns whether two lists are equal to each other using shallow
comparisons.
|
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 int |
findMatch(List<String> strings,
String seek,
boolean caseSensitive)
Looks for a string within a list of strings, using a given
case-sensitivity policy, and returns the position at which the first match
is found, or -1 if there are no matches.
|
static <T> T |
first(T t0,
T t1) |
static <E> int |
firstDuplicate(List<E> list)
Returns the ordinal of the first element in the list which is equal to a
previous element in the list.
|
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 |
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 int |
hashCode(double v)
Computes the hash code of a
double value. |
static String |
human(double d)
Converts a number into human-readable form, with 3 digits and a "K", "M"
or "G" multiplier for thousands, millions or billions.
|
static <E> boolean |
isDistinct(List<E> list)
Returns whether the elements of
list are distinct. |
static boolean |
isNullOrEmpty(String s) |
static <E> E |
last(List<E> list)
Returns the last element of a list.
|
static <E> List<E> |
last(List<E> list,
int n)
Returns the last
n elements of a list. |
static String |
lines(Iterable<String> strings)
Converts a list of strings to a string separated by newlines.
|
static <K,V> Map<K,V> |
mapOf(K key,
V value,
Object... keyValues)
Returns a hashmap with given contents.
|
static boolean |
matches(boolean caseSensitive,
String s0,
String s1)
Returns whether a name matches another according to a given
case-sensitivity policy.
|
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)
|
static <T> Iterable<T> |
orEmpty(Iterable<T> t0) |
static Locale |
parseLocale(String localeString)
Parses a locale string.
|
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 <E> List<E> |
quotientList(List<E> list,
int n,
int k)
Creates a list that returns every
nth element of a list,
starting at element k. |
static List<Integer> |
range(int end) |
static List<Integer> |
range(int start,
int end) |
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 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 <T> String |
sepList(List<T> list,
String sep)
Converts a list of a string, with a given separator between elements.
|
static <E> List<E> |
skip(List<E> list)
Returns all but the first element of a list.
|
static <E> List<E> |
skip(List<E> list,
int fromIndex)
Returns all but the first
n elements of a list. |
static <E> List<E> |
skipLast(List<E> list)
Returns every element of a list but its last element.
|
static <E> List<E> |
skipLast(List<E> list,
int n)
Returns every element of a list but its last
n elements. |
static void |
squelchConnection(Connection connection)
Closes a Connection, ignoring any SQL exception.
|
static void |
squelchJar(JarFile jar)
Closes a Jar, ignoring any I/O 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 <E> boolean |
startsWith(List<E> list0,
List<E> list1)
Returns whether one list is a prefix of another.
|
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 String |
toJavaId(String s,
int ordinal)
Converts an arbitrary string into a string suitable for use as a Java
identifier.
|
static String |
toLinux(String s) |
static <T> List<T> |
toList(Iterator<T> iter)
|
static Map<String,String> |
toMap(Properties properties)
Converts a
Properties object to a . |
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
exampleA 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
|
static <T> String |
toString(Iterable<T> iterable,
String start,
String sep,
String end)
Converts an iterable to a string.
|
static URL |
toURL(File file)
Creates a file-protocol URL for the given file.
|
static <E extends Enum<E>> |
unexpected(E value)
Returns an exception indicating that we didn't expect to find this
enumeration here.
|
public static final String LINE_SEPARATOR
In general, you should not use this in expected results of tests.
Expected results should be the expected result on Linux (or Mac OS) using
'\n'. Apply toLinux(String) to Windows actual results, if
necessary, to make them look like Linux actual.
public static final String FILE_SEPARATOR
public static final String FILE_TIMESTAMP_FORMAT
public static void discard(Object o)
public static void discard(int i)
public static boolean discard(boolean b)
public static void discard(double d)
public static void swallow(Throwable e, Logger logger)
e - Exceptionlogger - If not null, logs exception to this loggerpublic static <T> boolean equalShallow(List<? extends T> list0, List<? extends T> list1)
list0 - First listlist1 - Second list== (may be null).public static int hash(int i,
int j)
public static int hash(int h,
Object o)
public static int hashArray(int h,
Object[] a)
public static int hashCode(double v)
double value. Equivalent to
Double.hashCode(double), but that method was only
introduced in JDK 1.8.v - Valuepublic static <T> Set<T> minus(Set<T> set1, Set<T> set2)
set1 but not in
set2, without modifying either.public static double nLogN(double d)
public static void print(PrintWriter pw, Object o)
null;
arrays of objects and primitive values; for regular objects, we print all
public fields.public static void print(PrintWriter pw, Object o, int indent)
public static void printJavaString(PrintWriter pw, String s, boolean nullMeansNull)
printDoubleQuoted(w,"x\"y",false)
prints "x\"y".public static void println(PrintWriter pw, Object o)
public static String toScientificNotation(BigDecimal bd)
BigDecimal value to a string in scientific notation For
example1.234E-51.00E51E2If 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).
public static String replace(String s, String find, String replace)
find in s with
replace.public static URL toURL(File file) throws MalformedURLException
MalformedURLExceptionpublic static String getFileTimestamp()
public static String stripDoubleQuotes(String value)
"foo\"bar" becomes foo"bar.public static String toJavaId(String s, int ordinal)
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:toJavaId("foo") returns "foo"
toJavaId("foo bar") returns "foo_20_bar"
toJavaId("foo_bar") returns "foo__bar"
toJavaId("0bar") returns "_40_bar" (digits
are illegal as a prefix)
toJavaId("foo0bar") returns "foo0bar"
public static <T> List<T> toList(Iterator<T> iter)
iter - iterator to materializepublic static boolean isNullOrEmpty(String s)
public static <T> String commaList(List<T> list)
commaList(Arrays.asList({"a", "b"}))
returns "a, b".list - Listpublic static <T> String sepList(List<T> list, String sep)
public static Charset getDefaultCharset()
Charset object representing the value of
SaffronProperties.defaultCharsetIllegalCharsetNameException - If the given charset
name is illegalUnsupportedCharsetException - If no support for
the named charset is
available in this
instance of the Java
virtual machinepublic static Error newInternal()
public static String getMessages(Throwable t)
public static String getStackTrace(Throwable t)
t - Throwablepublic static void pre(boolean b,
String description)
For example,
/**
* @ pre x != 0
* /
void foo(int x) {
Util.pre(x != 0, "x != 0");
}b - Result of evaluating the pre-condition.description - Description of the pre-condition.public static void post(boolean b,
String description)
For example,
/**
* @ post return != 0
* /
void foo(int x) {
int res = bar(x);
Util.post(res != 0, "return != 0");
}b - Result of evaluating the pre-condition.description - Description of the pre-condition.public static void permAssert(boolean b,
String description)
This is similar to assert keyword, except that the
condition is always evaluated even if asserts are disabled.
public static RuntimeException needToImplement(Object o)
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); } }
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.UnsupportedOperationException.public static <T> T deprecated(T argument,
boolean fail)
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
but the usual usage is to pass in a descriptive string.int x = Util.deprecated(0, false);
deprecated to fail if a piece of
supposedly dead code is reachedvoid 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); } }
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();
}
argument - Arbitrary argument to the method.fail - Whether to throw an exception if this method is calledargument.public static boolean contains(String[] a, int length, String s)
length entries.a - Array of stringslength - Number of entries to searchs - String to seekpublic static String readAllAsString(Reader reader) throws IOException
Reader and returns
them as a string.reader - reader to read fromIOExceptionpublic static void squelchJar(JarFile jar)
jar - jar to closepublic static void squelchStream(InputStream stream)
stream - stream to closepublic static void squelchStream(OutputStream stream)
stream - stream to closepublic static void squelchReader(Reader reader)
reader - reader to closepublic static void squelchWriter(Writer writer)
writer - writer to closepublic static void squelchStmt(Statement stmt)
stmt - stmt to closepublic static void squelchConnection(Connection connection)
connection - connection to closepublic static String rtrim(String s)
s - string to be trimmedpublic static String rpad(String s, int len)
s - string to be paddedlen - desired lengthpublic static <T> String toString(Iterable<T> iterable, String start, String sep, String end)
public static String lines(Iterable<String> strings)
public static String toPosix(TimeZone tz, boolean verbose)
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:
[+|-]hh[:mm[:ss]] {h=0-23, m/s=0-59}For example:
(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.
tz - Timezoneverbose - Whether to include fields which can be omitted because
they have their default valuespublic static Locale parseLocale(String localeString)
The inverse operation of Locale.toString().
localeString - Locale string, e.g. "en" or "en_US"public static int runApplication(String[] cmdarray, Logger logger, Reader appInput, Writer appOutput) throws IOException, InterruptedException
cmdarray - command and arguments, see ProcessBuilderlogger - if not null, command and exit status will be loggedappInput - if not null, data will be copied to application's stdinappOutput - if not null, data will be captured from application's
stdout and stderrIOExceptionInterruptedExceptionpublic static ProcessBuilder newAppProcess(String[] cmdarray)
ProcessBuilder to run an external application.cmdarray - command and arguments.public static int runAppProcess(ProcessBuilder pb, Logger logger, Reader appInput, Writer appOutput) throws IOException, InterruptedException
pb - ProcessBuilder for the application; might be
returned by newAppProcess(java.lang.String[]).logger - if not null, command and exit status will be logged hereappInput - if not null, data will be copied to application's stdinappOutput - if not null, data will be captured from application's
stdout and stderrIOExceptionInterruptedExceptionpublic static <E> List<E> cast(List<? super E> list, Class<E> clazz)
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.
list - Backing list.clazz - Class to cast to.public static <E> Iterator<E> cast(Iterator<?> iter, Class<E> clazz)
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.
iter - Backing iterator.clazz - Class to cast to.public static <E> Iterable<E> cast(Iterable<? super E> iterable, Class<E> clazz)
Iterable whose members are automatically down-cast to
a given type.
All modifications are automatically written to the backing iterator. Not synchronized.
iterable - Backing iterableclazz - Class to cast topublic static <E> Iterable<E> filter(Iterable<? extends Object> iterable, Class<E> includeFilter)
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.iterable - IterableincludeFilter - Class whose instances to includepublic static <E> Collection<E> filter(Collection<?> collection, Class<E> includeFilter)
public static <E> List<E> filter(List<?> list, Class<E> includeFilter)
Modifications to the list are NOT written back to the source list.
list - List of objectsincludeFilter - Class to filter forpublic static Map<String,String> toMap(Properties properties)
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());
}
public static <K,V> Map<K,V> mapOf(K key, V value, Object... keyValues)
Use this method in initializers. Type parameters are inferred from context, and the contents are initialized declaratively. For example,
Map<String, Integer> population =
Olap4jUtil.mapOf(
"UK", 65000000,
"USA", 300000000);K - Key typeV - Value typekey - First keyvalue - First valuekeyValues - Second and sequent key/value pairspublic static <E extends Enum<E>> Error unexpected(E value)
value - Enumeration value which was not expectedpublic static <T extends Enum<T>> Map<String,T> enumConstants(Class<T> clazz)
clazz - Enumeration classpublic static <T extends Enum<T>> T enumVal(Class<T> clazz, String name)
Similar to Enum.valueOf(Class, String), but returns null rather than throwing IllegalArgumentException.
T - Enum class typeclazz - Enum classname - Name of enum constantpublic static <E> List<E> quotientList(List<E> list, int n, int k)
nth element of a list,
starting at element k.
It is OK if the list is empty or its size is not a multiple of
n.
For instance, quotientList(list, 2, 0) returns the even
elements of a list, and quotientList(list, 2, 1) returns the odd
elements. Those lists are the same length only if list has even size.
public static <T> T first(T t0,
T t1)
public static <E> E last(List<E> list)
IndexOutOfBoundsException - if the list is emptypublic static <E> List<E> skipLast(List<E> list)
public static <E> List<E> skipLast(List<E> list, int n)
n elements.public static <E> List<E> skip(List<E> list, int fromIndex)
n elements of a list.public static <E> boolean isDistinct(List<E> list)
list are distinct.public static <E> int firstDuplicate(List<E> list)
For example,
firstDuplicate(Arrays.asList("a", "b", "c", "b", "a"))
returns 3, the ordinal of the 2nd "b".
list - Listpublic static int findMatch(List<String> strings, String seek, boolean caseSensitive)
public static boolean matches(boolean caseSensitive,
String s0,
String s1)
public static <E> boolean startsWith(List<E> list0, List<E> list1)
public static String human(double d)
Examples: -2, 0, 1, 999, 1.00K, 1.99K, 3.45M, 4.56B.
public static <K,V> Map<K,V> asIndexMap(Collection<V> values, com.google.common.base.Function<V,K> function)
Unlike
Maps.uniqueIndex(Iterable, com.google.common.base.Function),
returns a view whose contents change as the collection of values changes.
K - Key typeV - Value typevalues - Collection of valuesfunction - Function to map value to keypublic static void debugCode(PrintStream out, String code)
Copyright © 2012–2015 The Apache Software Foundation. All rights reserved.