public class Util
extends org.eigenbase.xom.XOMUtil
Modifier and Type | Class and Description |
---|---|
static class |
Util.AbstractFlatList<T> |
static class |
Util.ByteMatcher
This class implements the Knuth-Morris-Pratt algorithm
to search within a byte array for a token byte array.
|
static class |
Util.ErrorCellValue |
protected static class |
Util.Flat2List<T>
List that stores its two elements in the two members of the class.
|
protected static class |
Util.Flat3List<T>
List that stores its three elements in the three members of the class.
|
static interface |
Util.Functor1<RT,PT> |
static class |
Util.GcIterator<T>
Garbage-collecting iterator.
|
static interface |
Util.MemoryInfo
Information about memory usage.
|
static class |
Util.PropertyList
PropertyList is an order-preserving list of key-value
pairs. |
static class |
Util.SqlNullSafeComparator
A
Comparator implementation which can deal
correctly with RolapUtil.sqlNullValue . |
Modifier and Type | Field and Description |
---|---|
static boolean |
DEBUG
Flag to control expensive debugging.
|
static Object |
EmptyValue
Placeholder which indicates an EMPTY value.
|
static boolean |
IBM_JVM
Whether this is an IBM JVM.
|
static int |
JdbcVersion
What version of JDBC?
Returns:
0x0401 in JDK 1.7 and higher
0x0400 in JDK 1.6
0x0300 otherwise
|
static UUID |
JVM_INSTANCE_UUID
Unique id for this JVM instance.
|
static String |
nl |
static Object |
nullValue
Placeholder which indicates a value NULL.
|
static boolean |
Retrowoven
Whether the code base has re-engineered using retroweaver.
|
Constructor and Description |
---|
Util() |
Modifier and Type | Method and Description |
---|---|
static void |
addDatabaseTime(long millis)
Deprecated.
Will be removed in 4.0.
|
static List<Member> |
addLevelCalculatedMembers(SchemaReader reader,
Level level,
List<Member> members) |
static <T> T[] |
append(T[] a,
T o)
Adds an object to the end of an array.
|
static <T> T[] |
appendArrays(T[] a0,
T[]... as)
Concatenates one or more arrays.
|
static <T> boolean |
areOccurencesEqual(Collection<T> collection)
Returns whether a collection contains precisely one distinct element.
|
static void |
assertPostcondition(boolean b)
Checks that a postcondition (declared using the javadoc
@post tag) is satisfied. |
static void |
assertPostcondition(boolean b,
String condition)
Checks that a postcondition (declared using the javadoc
@post tag) is satisfied. |
static void |
assertPrecondition(boolean b)
Checks that a precondition (declared using the javadoc
@pre
tag) is satisfied. |
static void |
assertPrecondition(boolean b,
String condition)
Checks that a precondition (declared using the javadoc
@pre
tag) is satisfied. |
static void |
assertTrue(boolean b)
Throws an internal error if condition is not true.
|
static void |
assertTrue(boolean b,
String message)
Throws an internal error with the given messagee if condition is not
true.
|
static <T extends Enum<T>> |
badValue(Enum<T> anEnum)
Returns an exception indicating that we didn't expect to find this value
here.
|
static <T extends Comparable<T>> |
binarySearch(T[] ts,
int start,
int end,
T t)
As Arrays#binarySearch(Object[], int, int, Object), but
available pre-JDK 1.6.
|
static BitSet |
bitSetBetween(int fromIndex,
int toIndex)
Creates a bitset with bits from
fromIndex (inclusive) to
specified toIndex (exclusive) set to true . |
static String |
camelToUpper(String s)
Converts a camel-case name to an upper-case name with underscores.
|
static <T> boolean |
canCast(Collection<?> collection,
Class<T> clazz)
Returns whether it is safe to cast a collection to a collection with a
given element type.
|
static void |
cancelStatement(Statement stmt)
Closes and cancels a
Statement using the correct methods
available on the current Java runtime. |
static int |
caseSensitiveCompareName(String s,
String t)
Compares two names.
|
static <T> List<T> |
cast(List<?> list)
Casts a List to a List with a different element type.
|
static <T> Set<T> |
cast(Set<?> set)
Casts a Set to a Set with a different element type.
|
static <T> Iterable<T> |
castToIterable(Object iterable)
Casts a collection to iterable.
|
static void |
checkCJResultLimit(long resultSize)
Check the resultSize against the result limit setting.
|
static SQLException |
close(ResultSet resultSet,
Statement statement,
Connection connection)
Closes a JDBC result set, statement, and connection, ignoring any errors.
|
static <T> String |
commaList(String s,
List<T> list)
Converts a list of a string.
|
static int |
compare(int i0,
int i1)
Compares integer values.
|
static int |
compareIntegers(int i0,
int i1)
Compares two integers using the same algorithm as
Integer.compareTo(Integer) . |
static int |
compareKey(Object k1,
Object k2)
Returns the result of ((Comparable) k1).compareTo(k2), with
special-casing for the fact that Boolean only became
comparable in JDK 1.5.
|
static int |
compareName(String s,
String t)
Compares two names.
|
static <T> T |
compileScript(Class<T> iface,
String script,
String engineName)
Compiles a script to yield a Java interface.
|
static Id.Segment |
convert(org.olap4j.mdx.IdentifierSegment olap4jSegment)
Converts an olap4j-style segment to a mondrian-style segment.
|
static List<Id.Segment> |
convert(List<org.olap4j.mdx.IdentifierSegment> olap4jSegmentList)
Converts a list of olap4j-style segments to a list of mondrian-style
segments.
|
static String |
convertOlap4jConnectStringToNativeMondrian(String url)
Converts an olap4j connect string into a legacy mondrian connect string.
|
static String[] |
convertStackToString(Throwable e)
Converts an error into an array of strings, the most recent error first.
|
static double[] |
copyOf(double[] original,
int newLength)
Like
, but
exists prior to JDK 1.6. |
static int[] |
copyOf(int[] original,
int newLength)
Like
, but
exists prior to JDK 1.6. |
static long[] |
copyOf(long[] original,
int newLength)
Like
, but
exists prior to JDK 1.6. |
static <T> T[] |
copyOf(T[] original,
int newLength)
Like
, but
exists prior to JDK 1.6. |
static <T,U> T[] |
copyOf(U[] original,
int newLength,
Class<? extends T[]> newType)
Copies the specified array.
|
static Exp |
createExpr(OlapElement element)
Converts an olap element (dimension, hierarchy, level or member) into
an expression representing a usage of that element in an MDX statement.
|
static Random |
createRandom(long seed)
Creates a random number generator.
|
static Role |
createRootRole(Schema schema)
Returns a role which has access to everything.
|
static Validator |
createSimpleValidator(FunTable funTable)
Creates a very simple implementation of
Validator . |
static UserDefinedFunction |
createUdf(Class<? extends UserDefinedFunction> udfClass,
String functionName)
Creates a new udf instance from the given udf class.
|
static long |
dbTimeMillis()
Deprecated.
Use
Monitor.getServer() and
ServerInfo.sqlStatementExecuteNanos ;
will be removed in 4.0. |
static <T> T |
deprecated(T reason)
Deprecated.
|
static <T> T |
deprecated(T reason,
boolean fail)
Deprecated.
|
static byte[] |
digestMd5(String value)
Creates an MD5 hash of a String.
|
static byte[] |
digestSha256(String value)
Parses a string and returns a SHA-256 checksum of it.
|
static boolean |
equal(String s,
String t,
boolean matchCase)
Tests two strings for equality, optionally ignoring case.
|
static boolean |
equalName(String s,
String t)
Returns whether two names are equal.
|
static boolean |
equals(Object s,
Object t)
Returns true if two objects are equal, or are both null.
|
static boolean |
equals(String s,
String t)
Returns true if two strings are equal, or are both null.
|
static <PT> Util.Functor1<Boolean,PT> |
falseFunctor() |
static <T> Iterable<T> |
filter(Iterable<T> iterable,
Util.Functor1<Boolean,T>... conds)
Applies a collection of filters to an iterable.
|
static <T> List<T> |
flatList(List<T> t)
Creates a memory-, CPU- and cache-efficient immutable list from an
existing list.
|
static <T> List<T> |
flatList(T... t)
Creates a memory-, CPU- and cache-efficient immutable list.
|
static <T> List<T> |
flatListCopy(T... t)
Creates a memory-, CPU- and cache-efficient immutable list,
always copying the contents.
|
static String |
generateUuidString()
Generates a unique id.
|
static <T> T[] |
genericArray(Class<T> clazz,
int size) |
static <T> T |
getAnnotation(Method method,
String annotationClassName,
T defaultValue)
Returns an annotation of a particular class on a method.
|
static URL |
getClosestResource(ClassLoader classLoader,
String name)
Similar to
ClassLoader.getResource(String) , except the lookup
is in reverse order.i.e. |
static Cube |
getDimensionCube(Dimension dimension)
Tries to find the cube from which a dimension is taken.
|
static String |
getErrorMessage(Throwable err)
Constructs the message associated with an arbitrary Java error, making
up one based on the stack trace if there is none.
|
static String |
getErrorMessage(Throwable err,
boolean prependClassName)
Constructs the message associated with an arbitrary Java error, making
up one based on the stack trace if there is none.
|
static ExecutorService |
getExecutorService(int maximumPoolSize,
int corePoolSize,
long keepAliveTime,
String name,
RejectedExecutionHandler rejectionPolicy)
Creates an
ExecutorService object backed by a thread pool. |
static Member |
getFirstDescendantOnLevel(SchemaReader reader,
Member parent,
Level level)
returns the first descendant on the level underneath parent.
|
static <T extends Throwable> |
getMatchingCause(Throwable e,
Class<T> clazz)
If one of the causes of an exception is of a particular class, returns
that cause.
|
static int |
getMemberOrdinalInParent(SchemaReader reader,
Member member)
Finds the zero based ordinal of a Member among its siblings.
|
static Map<Hierarchy,Set<Member>> |
getMembersToHierarchyMap(List<Member> members) |
static Util.MemoryInfo |
getMemoryInfo() |
static ScheduledExecutorService |
getScheduledExecutorService(int maxNbThreads,
String name)
Creates an
ScheduledExecutorService object backed by a
thread pool with a fixed number of threads.. |
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 <T> Util.Functor1<T,T> |
identityFunctor() |
static String |
implode(List<Id.Segment> names)
Converts an array of name parts {"part1", "part2"} into a single string
"[part1].[part2]".
|
static <E extends Comparable> |
intersect(SortedSet<E> set1,
SortedSet<E> set2)
Returns the intersection of two sorted sets.
|
static boolean |
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
|
static boolean |
isEmpty(String s)
Returns whether a string is null or empty.
|
static boolean |
isNull(Object o) |
static <T> boolean |
isSorted(List<T> list)
Returns whether a list is strictly sorted.
|
static boolean |
isValidProperty(String propertyName,
Level level)
Returns whether a property is valid for a member of a given level.
|
static <T> T |
last(List<T> list)
Returns the last item in a list.
|
static <E extends Enum<E>> |
lookup(Class<E> clazz,
String name)
Looks up an enumeration by name, returning null if null or not valid.
|
static <E extends Enum<E>> |
lookup(Class<E> clazz,
String name,
E defaultValue)
Looks up an enumeration by name, returning a given default value if null
or not valid.
|
static OlapElement |
lookup(Query q,
List<Id.Segment> nameParts) |
static Exp |
lookup(Query q,
List<Id.Segment> nameParts,
boolean allowProp)
Converts an identifier into an expression by resolving its parts into
an OLAP object (dimension, hierarchy, level or member) within the
context of a query.
|
static Exp |
lookup(Query q,
SchemaReader schemaReader,
List<Id.Segment> segments,
boolean allowProp)
Converts an identifier into an expression by resolving its parts into
an OLAP object (dimension, hierarchy, level or member) within the
context of a query.
|
static OlapElement |
lookupCompound(SchemaReader schemaReader,
OlapElement parent,
List<Id.Segment> names,
boolean failIfNotFound,
int category) |
static OlapElement |
lookupCompound(SchemaReader schemaReader,
OlapElement parent,
List<Id.Segment> names,
boolean failIfNotFound,
int category,
MatchType matchType)
Resolves a name such as
'[Products].[Product Department].[Produce]' by resolving the
components ('Products', and so forth) one at a time.
|
static Level |
lookupHierarchyLevel(Hierarchy hierarchy,
String s)
Finds a named level in this hierarchy.
|
static Member |
lookupHierarchyRootMember(SchemaReader reader,
Hierarchy hierarchy,
Id.NameSegment memberName) |
static Member |
lookupHierarchyRootMember(SchemaReader reader,
Hierarchy hierarchy,
Id.NameSegment memberName,
MatchType matchType)
Finds a root member of a hierarchy with a given name.
|
static Property |
lookupProperty(Level level,
String propertyName)
Finds a member property called
propertyName at, or above,
level . |
static BigDecimal |
makeBigDecimalFromDouble(double d)
Make a BigDecimal from a double.
|
static String |
makeFqName(OlapElement parent,
String name) |
static String |
makeFqName(String name) |
static String |
makeFqName(String parentUniqueName,
String name) |
static boolean |
matches(org.olap4j.mdx.IdentifierSegment segment,
String name) |
static boolean |
matches(Member member,
List<Id.Segment> nameParts) |
static String |
mdxEncodeString(String st)
Deprecated.
Will be removed in 4.0
|
static RuntimeException |
needToImplement(Object o)
Returns an exception which indicates that a particular piece of
functionality should work, but a developer has not implemented it yet.
|
static RuntimeException |
newElementNotFoundException(int category,
org.olap4j.mdx.IdentifierNode identifierNode) |
static RuntimeException |
newError(String message)
Creates a non-internal error.
|
static RuntimeException |
newError(Throwable e,
String message)
Creates a non-internal error.
|
static <T> Set<T> |
newIdentityHashSet()
Creates a hash set that, like
IdentityHashMap ,
compares keys using identity. |
static <T> Set<T> |
newIdentityHashSetFake() |
static RuntimeException |
newInternal(String message)
Creates an internal error with a given message.
|
static RuntimeException |
newInternal(Throwable e,
String message)
Creates an internal error with a given message and cause.
|
static Timer |
newTimer(String name,
boolean isDaemon)
Equivalent to
Timer.Timer(String, boolean) . |
static long |
nonDbTimeMillis()
Deprecated.
Will be removed in 4.0.
|
static String |
normalizeName(String s)
Generates a normalized form of a name, for use as a key into a map.
|
static <T> T |
only(List<T> list)
Returns the sole item in a list.
|
static List<String> |
parseCommaList(String nameCommaList)
Parses a comma-separated list.
|
static Util.PropertyList |
parseConnectString(String s)
Converts an OLE DB connect string into a
Util.PropertyList . |
static List<Id.Segment> |
parseIdentifier(String s)
Parses an MDX identifier such as
[Foo].[Bar].Baz.&Key&Key2
and returns the result as a list of segments. |
static Pair<Long,TimeUnit> |
parseInterval(String s,
TimeUnit unit)
Parses an interval.
|
static Locale |
parseLocale(String localeString)
Parses a locale string.
|
static String |
printMemory() |
static String |
printMemory(String msg) |
static String |
quoteForMdx(String val)
Converts a string into a double-quoted string.
|
static StringBuilder |
quoteForMdx(StringBuilder buf,
String val)
Appends a double-quoted string to a string builder.
|
static String |
quoteJavaString(String s)
Quotes a string literal for Java or JavaScript.
|
static String |
quoteMdxIdentifier(List<Id.Segment> ids)
Return identifiers quoted in [...].[...].
|
static void |
quoteMdxIdentifier(List<Id.Segment> ids,
StringBuilder sb) |
static String |
quoteMdxIdentifier(String id)
Return string quoted in [...].
|
static void |
quoteMdxIdentifier(String id,
StringBuilder buf) |
static String |
quotePattern(String s)
Returns a literal pattern String for the specified String.
|
static byte[] |
readFully(InputStream in,
int bufferSize)
Reads an input stream until it returns EOF and returns the contents as an
array of bytes.
|
static String |
readFully(Reader rdr,
int bufferSize)
Reads a Reader until it returns EOF and returns the contents as a String.
|
static String |
readURL(String urlStr,
Map<String,String> map)
Returns the contents of a URL, substituting tokens.
|
static String |
readURL(URL url)
Returns the contents of a URL.
|
static String |
readURL(URL url,
Map<String,String> map)
Returns the contents of a URL, substituting tokens.
|
static InputStream |
readVirtualFile(String url)
Gets content via Apache VFS.
|
static String |
readVirtualFileAsString(String catalogUrl) |
static StringBuilder |
replace(StringBuilder buf,
int start,
String find,
String replace)
Replaces all occurrences of a string in a buffer with another.
|
static String |
replace(String s,
String find,
String replace)
Returns a string with every occurrence of a seek string replaced with
another.
|
static String |
replaceProperties(String text,
Map<String,String> env)
Replaces tokens in a string.
|
static <T> T |
safeGet(Future<T> future,
String message)
Calls
Future.get() and converts any
throwable into a non-checked exception. |
static String |
singleQuoteString(String val)
Encloses a value in single-quotes, to make a SQL string value.
|
static void |
singleQuoteString(String val,
StringBuilder buf)
Encloses a value in single-quotes, to make a SQL string value.
|
static <T extends Comparable> |
sort(Collection<T> collection)
Sorts a collection of
Comparable objects and returns a list. |
static <T> List<T> |
sort(Collection<T> collection,
Comparator<T> comparator)
Sorts a collection of objects using a
Comparator and returns a
list. |
static <T> void |
threadLocalRemove(ThreadLocal<T> threadLocal)
Removes a thread local from the current thread.
|
static Map<String,String> |
toMap(Properties properties)
Converts a
Properties object to a string-to-string Map . |
static <K,V> Map<K,V> |
toNullValuesMap(List<K> list)
Transforms a list into a map for which all the keys return
a null value associated to it.
|
static org.olap4j.mdx.Quoting |
toOlap4j(Id.Quoting quoting) |
static org.olap4j.mdx.IdentifierSegment |
toOlap4j(Id.Segment segment) |
static List<org.olap4j.mdx.IdentifierSegment> |
toOlap4j(List<Id.Segment> segments) |
static URL |
toURL(File file)
Creates a file-protocol URL for the given file.
|
static <PT> Util.Functor1<Boolean,PT> |
trueFunctor() |
static RuntimeException |
unexpected(Enum value)
Returns an exception indicating that we didn't expect to find this value
here.
|
static String |
uniquify(String name,
int maxLength,
Collection<String> nameList)
Makes a name distinct from other names which have already been used
and shorter than a length limit, adds it to the list, and returns it.
|
static String |
unparse(Exp exp)
Converts an expression to a string.
|
static String |
unparse(Query query)
Converts an query to a string.
|
static String |
wildcardToRegexp(List<String> wildcards)
Converts a list of SQL-style patterns into a Java regular expression.
|
addChild, addChild, addChildren, addElement, concatenate, createDefaultParser, discard, discard, discard, discard, discard, discard, discard, discard, discard, getFirstInstance, wrapperToXml
public static final String nl
public static final Object nullValue
public static final Object EmptyValue
public static final UUID JVM_INSTANCE_UUID
public static final boolean IBM_JVM
public static final int JdbcVersion
public static final boolean Retrowoven
UtilCompatible
.
Retroweaver has some problems involving EnumSet
.public static final boolean DEBUG
public static boolean isNull(Object o)
public static <T> boolean isSorted(List<T> list)
list
- Listpublic static byte[] digestSha256(String value)
value
- The source string to parse.public static byte[] digestMd5(String value)
value
- String to create one way hash upon.public static ExecutorService getExecutorService(int maximumPoolSize, int corePoolSize, long keepAliveTime, String name, RejectedExecutionHandler rejectionPolicy)
ExecutorService
object backed by a thread pool.maximumPoolSize
- Maximum number of concurrent
threads.corePoolSize
- Minimum number of concurrent
threads to maintain in the pool, even if they are
idle.keepAliveTime
- Time, in seconds, for which to
keep alive unused threads.name
- The name of the threads.rejectionPolicy
- The rejection policy to enforce.public static ScheduledExecutorService getScheduledExecutorService(int maxNbThreads, String name)
ScheduledExecutorService
object backed by a
thread pool with a fixed number of threads..maxNbThreads
- Maximum number of concurrent
threads.name
- The name of the threads.public static String mdxEncodeString(String st)
public static String quoteForMdx(String val)
public static StringBuilder quoteForMdx(StringBuilder buf, String val)
public static String quoteMdxIdentifier(String id)
public static void quoteMdxIdentifier(String id, StringBuilder buf)
public static String quoteMdxIdentifier(List<Id.Segment> ids)
public static void quoteMdxIdentifier(List<Id.Segment> ids, StringBuilder sb)
public static String quoteJavaString(String s)
s
- Unquoted literalpublic static boolean equals(Object s, Object t)
s
- First objectt
- Second objectpublic static boolean equals(String s, String t)
The result is not affected by
the case sensitive option
; if
you wish to compare names, use equalName(String, String)
.
public static boolean equalName(String s, String t)
case sensitive option
.
Names may be null.public static boolean equal(String s, String t, boolean matchCase)
s
- First stringt
- Second stringmatchCase
- Whether to perform case-sensitive matchpublic static int caseSensitiveCompareName(String s, String t)
case
sensitive option
.
Names must not be null.public static int compareName(String s, String t)
case
sensitive option
.
Names must not be null.public static String normalizeName(String s)
MondrianProperties.CaseSensitive
is true, the name unchanged
otherwise.public static int compareKey(Object k1, Object k2)
Comparable.compareTo(T)
public static int compare(int i0, int i1)
i0
- First integeri1
- Second integerpublic static String replace(String s, String find, String replace)
public static StringBuilder replace(StringBuilder buf, int start, String find, String replace)
buf
- String buffer to act onstart
- Ordinal within find
to start searchingfind
- String to findreplace
- String to replace it withpublic static List<Id.Segment> parseIdentifier(String s)
[Foo].[Bar].Baz.&Key&Key2
and returns the result as a list of segments.s
- MDX identifierpublic static String implode(List<Id.Segment> names)
public static String makeFqName(OlapElement parent, String name)
public static OlapElement lookupCompound(SchemaReader schemaReader, OlapElement parent, List<Id.Segment> names, boolean failIfNotFound, int category)
public static OlapElement lookupCompound(SchemaReader schemaReader, OlapElement parent, List<Id.Segment> names, boolean failIfNotFound, int category, MatchType matchType)
schemaReader
- Schema reader, supplies access-control contextparent
- Parent element to search innames
- Exploded compound name, such as {"Products",
"Product Department", "Produce"}failIfNotFound
- If the element is not found, determines whether
to return null or throw an errorcategory
- Type of returned element, a Category
value;
Category.Unknown
if it doesn't matter.parseIdentifier(String)
public static OlapElement lookup(Query q, List<Id.Segment> nameParts)
public static Exp lookup(Query q, List<Id.Segment> nameParts, boolean allowProp)
If allowProp
is true, also allows property references
from valid members, for example
[Measures].[Unit Sales].FORMATTED_VALUE
.
In this case, the result will be a ResolvedFunCall
.
q
- Query expression belongs tonameParts
- Parts of the identifierallowProp
- Whether to allow property referencespublic static Exp lookup(Query q, SchemaReader schemaReader, List<Id.Segment> segments, boolean allowProp)
If allowProp
is true, also allows property references
from valid members, for example
[Measures].[Unit Sales].FORMATTED_VALUE
.
In this case, the result will be a ResolvedFunCall
.
q
- Query expression belongs toschemaReader
- Schema readersegments
- Parts of the identifierallowProp
- Whether to allow property referencespublic static Exp createExpr(OlapElement element)
public static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName)
public static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName, MatchType matchType)
hierarchy
- HierarchymemberName
- Name of root memberpublic static Level lookupHierarchyLevel(Hierarchy hierarchy, String s)
public static int getMemberOrdinalInParent(SchemaReader reader, Member member)
public static Member getFirstDescendantOnLevel(SchemaReader reader, Member parent, Level level)
public static boolean isEmpty(String s)
public static String singleQuoteString(String val)
singleQuoteForSql(null)
yields NULL
;
singleQuoteForSql("don't")
yields 'don''t'
.public static void singleQuoteString(String val, StringBuilder buf)
singleQuoteForSql(null)
yields NULL
;
singleQuoteForSql("don't")
yields 'don''t'
.public static Random createRandom(long seed)
seed
- Seed for random number generator.
If 0, generate a seed from the system clock and print the value
chosen. (This is effectively non-deterministic.)
If -1, generate a seed from an internal random number generator.
(This is deterministic, but ensures that different tests have
different seeds.)public static boolean isValidProperty(String propertyName, Level level)
propertyName
- Property namelevel
- Levelpublic static Property lookupProperty(Level level, String propertyName)
propertyName
at, or above,
level
.public static <T> T deprecated(T reason)
public static <T> T deprecated(T reason, boolean fail)
public static List<Member> addLevelCalculatedMembers(SchemaReader reader, Level level, List<Member> members)
public static RuntimeException needToImplement(Object o)
public static <T extends Enum<T>> RuntimeException badValue(Enum<T> anEnum)
public static String wildcardToRegexp(List<String> wildcards)
For example, {"Foo_", "Bar%BAZ"} becomes "Foo.|Bar.*BAZ".
wildcards
- List of SQL-style wildcard expressionspublic static String camelToUpper(String s)
For example, camelToUpper("FooBar")
returns "FOO_BAR".
s
- Camel-case stringpublic static List<String> parseCommaList(String nameCommaList)
If a value contains a comma, escape it with a second comma. For
example, parseCommaList("x,y,,z")
returns
{"x", "y,z"}
.
nameCommaList
- List of names separated by commaspublic static <T> T getAnnotation(Method method, String annotationClassName, T defaultValue)
method
- Method containing annotationannotationClassName
- Name of annotation class to finddefaultValue
- Value to return if annotation is not presentpublic static void cancelStatement(Statement stmt)
Statement
using the correct methods
available on the current Java runtime.
If errors are encountered while canceling a statement,
the message is logged in Util
.
stmt
- The statement to cancel.public static Util.MemoryInfo getMemoryInfo()
public static <T> String commaList(String s, List<T> list)
commaList("foo", Arrays.asList({"a", "b"}))
returns "foo(a, b)".s
- Prefixlist
- Listpublic static String uniquify(String name, int maxLength, Collection<String> nameList)
name
- Suggested name, may not be uniquemaxLength
- Maximum length of generated namenameList
- Collection of names already usedpublic static <T> boolean areOccurencesEqual(Collection<T> collection)
collection
- Collectionpublic static <T> List<T> flatList(T... t)
T
- Element typet
- Array of members of listpublic static <T> List<T> flatListCopy(T... t)
T
- Element typet
- Array of members of listpublic static <T> List<T> flatList(List<T> t)
T
- Element typet
- Array of members of listpublic static Locale parseLocale(String localeString)
The inverse operation of Locale.toString()
.
localeString
- Locale string, e.g. "en" or "en_US"public static Pair<Long,TimeUnit> parseInterval(String s, TimeUnit unit) throws NumberFormatException
For example, "30s" becomes (30, TimeUnit.SECONDS
);
"2us" becomes (2, TimeUnit.MICROSECONDS
).
Units m (minutes), h (hours) and d (days) are only available
in JDK 1.6 or later, because the corresponding constants are missing
from TimeUnit
in JDK 1.5.
s
- String to parseunit
- Default time unit; may be nullNumberFormatException
- if unit is not present and there is no
default, or if number is not validpublic static List<Id.Segment> convert(List<org.olap4j.mdx.IdentifierSegment> olap4jSegmentList)
olap4jSegmentList
- List of olap4j segmentspublic static Id.Segment convert(org.olap4j.mdx.IdentifierSegment olap4jSegment)
olap4jSegment
- olap4j segmentpublic static <T> Iterable<T> filter(Iterable<T> iterable, Util.Functor1<Boolean,T>... conds)
T
- iterable
- Iterableconds
- Zero or more conditionspublic static <T extends Comparable> List<T> sort(Collection<T> collection)
Comparable
objects and returns a list.T
- Element typecollection
- Collectionpublic static <T> List<T> sort(Collection<T> collection, Comparator<T> comparator)
Comparator
and returns a
list.T
- Element typecollection
- Collectioncomparator
- Comparatorpublic static List<org.olap4j.mdx.IdentifierSegment> toOlap4j(List<Id.Segment> segments)
public static org.olap4j.mdx.IdentifierSegment toOlap4j(Id.Segment segment)
public static org.olap4j.mdx.Quoting toOlap4j(Id.Quoting quoting)
public static boolean matches(org.olap4j.mdx.IdentifierSegment segment, String name)
public static boolean matches(Member member, List<Id.Segment> nameParts)
public static RuntimeException newElementNotFoundException(int category, org.olap4j.mdx.IdentifierNode identifierNode)
public static <T> T safeGet(Future<T> future, String message)
Future.get()
and converts any
throwable into a non-checked exception.T
- Result typefuture
- Futuremessage
- Message to qualify wrapped exceptionpublic static <T> Set<T> newIdentityHashSetFake()
public static Timer newTimer(String name, boolean isDaemon)
Timer.Timer(String, boolean)
.
(Introduced in JDK 1.5.)name
- the name of the associated threadisDaemon
- true if the associated thread should run as a daemonpublic static <T extends Comparable<T>> int binarySearch(T[] ts, int start, int end, T t)
public static <E extends Comparable> SortedSet<E> intersect(SortedSet<E> set1, SortedSet<E> set2)
Optimized for the case that both sets are ArraySortedSet
.
set1
- First setset2
- Second setpublic static int compareIntegers(int i0, int i1)
Integer.compareTo(Integer)
.i0
- First integeri1
- Second integerpublic static <T> T last(List<T> list)
T
- Element typelist
- ListIndexOutOfBoundsException
- if list is emptypublic static <T> T only(List<T> list)
If the list has 0 or more than one element, throws.
T
- Element typelist
- ListIndexOutOfBoundsException
- if list is empty or has more than 1 eltpublic static SQLException close(ResultSet resultSet, Statement statement, Connection connection)
If any of them throws a SQLException
, returns the first
such exception, but always executes all closes.
resultSet
- Result setstatement
- Statementconnection
- Connectionpublic static BitSet bitSetBetween(int fromIndex, int toIndex)
fromIndex
(inclusive) to
specified toIndex
(exclusive) set to true
.
For example, bitSetBetween(0, 3)
returns a bit set with bits
{0, 1, 2} set.
fromIndex
- Index of the first bit to be set.toIndex
- Index after the last bit to be set.public static <T> T[] genericArray(Class<T> clazz, int size)
public static void assertTrue(boolean b)
assert
, but that is a keyword as of JDK 1.4.public static void assertTrue(boolean b, String message)
assert
, but that is a keyword as
of JDK 1.4.public static RuntimeException newInternal(String message)
public static RuntimeException newInternal(Throwable e, String message)
public static RuntimeException newError(String message)
public static RuntimeException newError(Throwable e, String message)
public static RuntimeException unexpected(Enum value)
value
- Valuepublic static void assertPrecondition(boolean b)
@pre
tag) is satisfied.b
- The value of executing the conditionpublic static void assertPrecondition(boolean b, String condition)
@pre
tag) is satisfied. For example,
void f(String s) { Util.assertPrecondition(s != null, "s != null"); ... }
b
- The value of executing the conditioncondition
- The text of the conditionpublic static void assertPostcondition(boolean b)
@post
tag) is satisfied.b
- The value of executing the conditionpublic static void assertPostcondition(boolean b, String condition)
@post
tag) is satisfied.b
- The value of executing the conditionpublic static String[] convertStackToString(Throwable e)
e
- the error; may be null. Errors are chained according to their
cause
.public static String getErrorMessage(Throwable err)
getErrorMessage(Throwable,boolean)
, but does not print the
class name if the exception is derived from SQLException
or is exactly a Exception
.public static String getErrorMessage(Throwable err, boolean prependClassName)
err
- the errorprependClassName
- should the error be preceded by the
class name of the Java exception? defaults to false, unless the error
is derived from SQLException
or is exactly a Exception
public static <T extends Throwable> T getMatchingCause(Throwable e, Class<T> clazz)
T
- Classe
- Exceptionclazz
- Desired classpublic static URL toURL(File file) throws MalformedURLException
MalformedURLException
public static Util.PropertyList parseConnectString(String s)
Util.PropertyList
.
For example, "Provider=MSOLAP; DataSource=LOCALHOST;"
becomes the set of (key, value) pairs {("Provider","MSOLAP"),
("DataSource", "LOCALHOST")}
. Another example is
Provider='sqloledb';Data Source='MySqlServer';Initial
Catalog='Pubs';Integrated Security='SSPI';
.
This method implements as much as possible of the OLE DB connect string syntax
specification. To find what it actually does, take
a look at the mondrian.olap.UtilTestCase
test case.
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 <T> T[] appendArrays(T[] a0, T[]... as)
Resulting array has same element type as first array. Each arrays may be empty, but must not be null.
a0
- First arrayas
- Zero or more subsequent arrayspublic static <T> T[] append(T[] a, T o)
String[]
) as the input array.a
- Arrayo
- ElementappendArrays(T[], T[]...)
public static double[] copyOf(double[] original, int newLength)
Arrays
.copyOf(double[], int)
, but
exists prior to JDK 1.6.original
- the array to be copiednewLength
- the length of the copy to be returnedpublic static int[] copyOf(int[] original, int newLength)
Arrays
.copyOf(int[], int)
, but
exists prior to JDK 1.6.original
- the array to be copiednewLength
- the length of the copy to be returnedpublic static long[] copyOf(long[] original, int newLength)
Arrays
.copyOf(long[], int)
, but
exists prior to JDK 1.6.original
- the array to be copiednewLength
- the length of the copy to be returnedpublic static <T> T[] copyOf(T[] original, int newLength)
Arrays
.copyOf(Object[], int)
, but
exists prior to JDK 1.6.original
- the array to be copiednewLength
- the length of the copy to be returnedpublic static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
original
- the array to be copiednewLength
- the length of the copy to be returnednewType
- the class of the copy to be returnedpublic static long dbTimeMillis()
Monitor.getServer()
and
ServerInfo.sqlStatementExecuteNanos
;
will be removed in 4.0.public static void addDatabaseTime(long millis)
public static long nonDbTimeMillis()
public static Validator createSimpleValidator(FunTable funTable)
Validator
. (Only
useful for resolving trivial expressions.)public static String readFully(Reader rdr, int bufferSize) throws IOException
rdr
- Reader to Read.bufferSize
- size of buffer to allocate for reading.IOException
- on I/O errorpublic static byte[] readFully(InputStream in, int bufferSize) throws IOException
in
- Input streambufferSize
- size of buffer to allocate for reading.IOException
- on I/O errorpublic static String readURL(String urlStr, Map<String,String> map) throws IOException
Replaces the tokens "${key}" if the map is not null and "key" occurs in the key-value map.
If the URL string starts with "inline:" the contents are the rest of the URL.
urlStr
- URL stringmap
- Key/value mapIOException
- on I/O errorpublic static String readURL(URL url) throws IOException
url
- URLIOException
- on I/O errorpublic static String readURL(URL url, Map<String,String> map) throws IOException
Replaces the tokens "${key}" if the map is not null and "key" occurs in the key-value map.
url
- URLmap
- Key/value mapIOException
- on I/O errorpublic static InputStream readVirtualFile(String url) throws org.apache.commons.vfs2.FileSystemException
url
- Stringorg.apache.commons.vfs2.FileSystemException
- on errorpublic static String readVirtualFileAsString(String catalogUrl) throws IOException
IOException
public static Map<String,String> toMap(Properties properties)
Properties
object to a string-to-string Map
.properties
- Propertiespublic static String replaceProperties(String text, Map<String,String> env)
Replaces the tokens "${key}" if "key" occurs in the key-value map. Otherwise "${key}" is left in the string unchanged.
text
- Source stringenv
- Map of key-value pairspublic static String printMemory()
public static <T> Set<T> cast(Set<?> set)
set
- Setpublic static <T> List<T> cast(List<?> list)
list
- Listpublic static <T> boolean canCast(Collection<?> collection, Class<T> clazz)
T
- Element typecollection
- Collectionclazz
- Target element typepublic static <T> Iterable<T> castToIterable(Object iterable)
Collection
objects do not implement
Iterable
, so this method inserts a casting wrapper. (Since
Iterable does not exist under JDK 1.4, they will have been compiled
under JDK 1.5 or later, then retrowoven to 1.4 class format. References
to Iterable will have been replaced with references to
com.rc.retroweaver.runtime.Retroweaver_
.
Under later JDKs this method is trivial. This method can be deleted when we discontinue support for JDK 1.4.
T
- Element typeiterable
- Object which ought to be iterablepublic static <E extends Enum<E>> E lookup(Class<E> clazz, String name)
clazz
- Enumerated typename
- Name of constantpublic static <E extends Enum<E>> E lookup(Class<E> clazz, String name, E defaultValue)
clazz
- Enumerated typename
- Name of constantdefaultValue
- Default value if constant is not foundpublic static BigDecimal makeBigDecimalFromDouble(double d)
d
- the input doublepublic static String quotePattern(String s)
Specification as for Pattern.quote(String)
, which was
introduced in JDK 1.5.
s
- The string to be literalizedpublic static String generateUuidString()
From JDK 1.5 onwards, uses a UUID
.
public static <T> T compileScript(Class<T> iface, String script, String engineName)
Only valid JDK 1.6 and higher; fails on JDK 1.5 and earlier.
T
- Interfaceiface
- Interface script should implementscript
- Script codeengineName
- Name of engine (e.g. "JavaScript")public static <T> void threadLocalRemove(ThreadLocal<T> threadLocal)
From JDK 1.5 onwards, calls ThreadLocal.remove()
; before
that, no-ops.
T
- TypethreadLocal
- Thread localpublic static <T> Set<T> newIdentityHashSet()
IdentityHashMap
,
compares keys using identity.T
- Element typepublic static UserDefinedFunction createUdf(Class<? extends UserDefinedFunction> udfClass, String functionName)
udfClass
- the class to create new instance forfunctionName
- Function name, or nullpublic static void checkCJResultLimit(long resultSize)
resultSize
- Result limitResourceLimitExceededException
public static String convertOlap4jConnectStringToNativeMondrian(String url)
For example, "jdbc:mondrian:Datasource=jdbc/SampleData;Catalog=foodmart/FoodMart.xml;" becomes "Provider=Mondrian; Datasource=jdbc/SampleData;Catalog=foodmart/FoodMart.xml;"
This method is intended to allow legacy applications (such as JPivot and Mondrian's XMLA server) to continue to create connections using Mondrian's legacy connection API even when they are handed an olap4j connect string.
url
- olap4j connect stringpublic static boolean isBlank(String str)
StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
(Copied from commons-lang.)
str
- the String to check, may be nulltrue
if the String is null, empty or whitespacepublic static Role createRootRole(Schema schema)
schema
- A schema to bind this role to.public static Cube getDimensionCube(Dimension dimension)
public static URL getClosestResource(ClassLoader classLoader, String name)
ClassLoader.getResource(String)
, except the lookup
is in reverse order.classLoader
- The class loader to fetch fromname
- The resource nameClassLoader.getResource(String)
,
ClassLoader.getResources(String)
public static <T> Util.Functor1<T,T> identityFunctor()
public static <PT> Util.Functor1<Boolean,PT> trueFunctor()
public static <PT> Util.Functor1<Boolean,PT> falseFunctor()
public static Map<Hierarchy,Set<Member>> getMembersToHierarchyMap(List<Member> members)
public static <K,V> Map<K,V> toNullValuesMap(List<K> list)
The list passed as an argument will be used to back the map returned and as many methods are overridden as possible to make sure that we don't iterate over the backing list when creating it and when performing operations like .size(), entrySet() and contains().
The returned map is to be considered immutable. It will
throw an UnsupportedOperationException
if attempts to
modify it are made.
Copyright © 2019 Hitachi Vantara. All rights reserved.