Class Util
- Direct Known Subclasses:
FunUtil
- Since:
- 6 August, 2001
- Author:
- jhyde
-
Nested Class Summary
Modifier and TypeClassDescriptionstatic class
static class
This class implements the Knuth-Morris-Pratt algorithm to search within a byte array for a token byte array.static class
protected static class
List that stores its two elements in the two members of the class.protected static class
List that stores its three elements in the three members of the class.static interface
static class
Garbage-collecting iterator.static interface
Information about memory usage.static class
PropertyList
is an order-preserving list of key-value pairs.static class
AComparator
implementation which can deal correctly withRolapUtil.sqlNullValue
. -
Field Summary
Modifier and TypeFieldDescriptionstatic final boolean
Flag to control expensive debugging.static final Object
Placeholder which indicates an EMPTY value.static final boolean
Whether this is an IBM JVM.static final int
What version of JDBC? Returns: 0x0401 in JDK 1.7 and higher 0x0400 in JDK 1.6 0x0300 otherwisestatic final UUID
Unique id for this JVM instance.static final String
static final Object
Placeholder which indicates a value NULL.static final boolean
Whether the code base has re-engineered using retroweaver. -
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionstatic void
addAppender
(org.apache.logging.log4j.core.Appender appender, org.apache.logging.log4j.Logger logger, org.apache.logging.log4j.Level level) static void
addDatabaseTime
(long millis) Deprecated.Will be removed in 4.0.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>>
RuntimeExceptionReturns an exception indicating that we didn't expect to find this value here.static <T extends Comparable<T>>
intbinarySearch
(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 fromfromIndex
(inclusive) to specifiedtoIndex
(exclusive) set totrue
.static String
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 aStatement
using the correct methods available on the current Java runtime.static int
Compares two names.static <T> List<T>
Casts a List to a List with a different element type.static <T> Set<T>
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
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 asInteger.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 List<Id.Segment>
Converts a list of olap4j-style segments to a list of mondrian-style segments.static Id.Segment
convert
(org.olap4j.mdx.IdentifierSegment olap4jSegment) Converts an olap4j-style segment to a mondrian-style segment.static String
Converts an olap4j connect string into a legacy mondrian connect string.static String[]
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.Arrays
.copyOf(double[], int)static int[]
copyOf
(int[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(int[], int)static long[]
copyOf
(long[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(long[], int)static <T> T[]
copyOf
(T[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(Object[], int)static <T,
U> T[] 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 ofValidator
.static UserDefinedFunction
createUdf
(Class<? extends UserDefinedFunction> udfClass, String functionName) Creates a new udf instance from the given udf class.static long
Deprecated.UseMonitor.getServer()
andServerInfo.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[]
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
Tests two strings for equality, optionally ignoring case.static boolean
Returns whether two names are equal.static boolean
Returns true if two objects are equal, or are both null.static boolean
Returns true if two strings are equal, or are both null.static void
explain
(ProfileHandler handler, String title, Calc calc, QueryTiming timing) Called during major steps of executing a MDX query to provide insight into Calc calls/times and key function calls/times.static <PT> Util.Functor1<Boolean,
PT> 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>
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
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 toClassLoader.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 anExecutorService
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>
TgetMatchingCause
(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 Util.MemoryInfo
static ScheduledExecutorService
getScheduledExecutorService
(int maxNbThreads, String name) Creates anScheduledExecutorService
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
Computes a hash code from an existing hash code and an object (which may be null).static int
Computes a hash code from an existing hash code and an array of objects (which may be null).static <T> Util.Functor1<T,
T> 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>
SortedSet<E>Returns the intersection of two sorted sets.static boolean
Checks if a String is whitespace, empty ("") or null.static boolean
Returns whether a string is null or empty.static boolean
static <T> boolean
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
Returns the last item in a list.static <E extends Enum<E>>
ELooks up an enumeration by name, returning null if null or not valid.static <E extends Enum<E>>
ELooks 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 calledpropertyName
at, or above,level
.static org.apache.logging.log4j.core.Appender
makeAppender
(String name, StringWriter sw, String layout) static BigDecimal
makeBigDecimalFromDouble
(double d) Make a BigDecimal from a double.static String
makeFqName
(String name) static String
makeFqName
(String parentUniqueName, String name) static String
makeFqName
(OlapElement parent, String name) static boolean
matches
(Member member, List<Id.Segment> nameParts) static boolean
static String
Deprecated.Will be removed in 4.0static RuntimeException
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
Creates a non-internal error.static RuntimeException
Creates a non-internal error.static <T> Set<T>
Creates a hash set that, likeIdentityHashMap
, compares keys using identity.static <T> Set<T>
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
Equivalent toTimer(String, boolean)
.static long
Deprecated.Will be removed in 4.0.static String
Generates a normalized form of a name, for use as a key into a map.static <T> T
Returns the sole item in a list.parseCommaList
(String nameCommaList) Parses a comma-separated list.static Util.PropertyList
Converts an OLE DB connect string into aUtil.PropertyList
.static List<Id.Segment>
Parses an MDX identifier such as[Foo].[Bar].Baz.&Key&Key2
and returns the result as a list of segments.parseInterval
(String s, TimeUnit unit) Parses an interval.static Locale
parseLocale
(String localeString) Parses a locale string.static String
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
Quotes a string literal for Java or JavaScript.static String
Return string quoted in [...].static void
quoteMdxIdentifier
(String id, StringBuilder buf) static String
quoteMdxIdentifier
(List<Id.Segment> ids) Return identifiers quoted in [...].[...].static void
quoteMdxIdentifier
(List<Id.Segment> ids, StringBuilder sb) static String
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
Reads a Reader until it returns EOF and returns the contents as a String.static String
Returns the contents of a URL, substituting tokens.static String
Returns the contents of a URL.static String
Returns the contents of a URL, substituting tokens.static InputStream
readVirtualFile
(String url) Gets content via Apache VFS.static String
readVirtualFileAsString
(String catalogUrl) static void
removeAppender
(org.apache.logging.log4j.core.Appender appender, org.apache.logging.log4j.Logger logger) static StringBuilder
replace
(StringBuilder buf, int start, String find, String replace) Replaces all occurrences of a string in a buffer with another.static String
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
CallsFuture.get()
and converts any throwable into a non-checked exception.static void
setLevel
(org.apache.logging.log4j.Logger logger, org.apache.logging.log4j.Level level) 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>
List<T>sort
(Collection<T> collection) Sorts a collection ofComparable
objects and returns a list.static <T> List<T>
sort
(Collection<T> collection, Comparator<T> comparator) Sorts a collection of objects using aComparator
and returns a list.static <T> void
threadLocalRemove
(ThreadLocal<T> threadLocal) Removes a thread local from the current thread.toMap
(Properties properties) Converts aProperties
object to a string-to-stringMap
.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 List<org.olap4j.mdx.IdentifierSegment>
toOlap4j
(List<Id.Segment> segments) static org.olap4j.mdx.Quoting
toOlap4j
(Id.Quoting quoting) static org.olap4j.mdx.IdentifierSegment
toOlap4j
(Id.Segment segment) static URL
Creates a file-protocol URL for the given file.static <PT> Util.Functor1<Boolean,
PT> 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
Converts an expression to a string.static String
Converts an query to a string.static String
wildcardToRegexp
(List<String> wildcards) Converts a list of SQL-style patterns into a Java regular expression.Methods inherited from class org.eigenbase.xom.XOMUtil
addChild, addChild, addChildren, addElement, concatenate, createDefaultParser, discard, discard, discard, discard, discard, discard, discard, discard, discard, getFirstInstance, wrapperToXml
Methods inherited from class org.eigenbase.xom.XMLUtil
getFirstTagName, printAtt, printAtt, printAtt, printAtt, printPCDATA, printPCDATA, printPCDATA, quoteAtt, quoteAtt, quoteAtt, quoteAtt, quotePCDATA, stringEncodeXML, stringHasXMLSpecials
-
Field Details
-
nl
-
nullValue
Placeholder which indicates a value NULL. -
EmptyValue
Placeholder which indicates an EMPTY value. -
JVM_INSTANCE_UUID
Unique id for this JVM instance. Part of a key that ensures that if two JVMs in the same cluster have a data-source with the same identity-hash-code, they will be treated as different data-sources, and therefore caches will not be incorrectly shared. -
IBM_JVM
public static final boolean IBM_JVMWhether this is an IBM JVM. -
JdbcVersion
public static final int JdbcVersionWhat version of JDBC? Returns:- 0x0401 in JDK 1.7 and higher
- 0x0400 in JDK 1.6
- 0x0300 otherwise
-
Retrowoven
public static final boolean RetrowovenWhether the code base has re-engineered using retroweaver. If this is the case, some functionality is not available, but a lot of things are available viaUtilCompatible
. Retroweaver has some problems involvingEnumSet
. -
DEBUG
public static final boolean DEBUGFlag to control expensive debugging. (More expensive than merely enabling assertions: as we know, a lot of people run with assertions enabled.)- See Also:
-
-
Constructor Details
-
Util
public Util()
-
-
Method Details
-
isNull
-
isSorted
Returns whether a list is strictly sorted.- Parameters:
list
- List- Returns:
- whether list is sorted
-
digestSha256
Parses a string and returns a SHA-256 checksum of it.- Parameters:
value
- The source string to parse.- Returns:
- A checksum of the source string.
-
digestMd5
Creates an MD5 hash of a String.- Parameters:
value
- String to create one way hash upon.- Returns:
- MD5 hash.
-
getExecutorService
public static ExecutorService getExecutorService(int maximumPoolSize, int corePoolSize, long keepAliveTime, String name, RejectedExecutionHandler rejectionPolicy) Creates anExecutorService
object backed by a thread pool.- Parameters:
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.- Returns:
- An executor service preconfigured.
-
getScheduledExecutorService
Creates anScheduledExecutorService
object backed by a thread pool with a fixed number of threads..- Parameters:
maxNbThreads
- Maximum number of concurrent threads.name
- The name of the threads.- Returns:
- An scheduled executor service preconfigured.
-
mdxEncodeString
Deprecated.Will be removed in 4.0Encodes string for MDX (escapes ] as ]] inside a name). -
quoteForMdx
Converts a string into a double-quoted string. -
quoteForMdx
Appends a double-quoted string to a string builder. -
quoteMdxIdentifier
Return string quoted in [...]. For example, "San Francisco" becomes "[San Francisco]"; "a [bracketed] string" becomes "[a [bracketed]] string]". -
quoteMdxIdentifier
-
quoteMdxIdentifier
Return identifiers quoted in [...].[...]. For example, {"Store", "USA", "California"} becomes "[Store].[USA].[California]". -
quoteMdxIdentifier
-
quoteJavaString
Quotes a string literal for Java or JavaScript.- Parameters:
s
- Unquoted literal- Returns:
- Quoted string literal
-
equals
Returns true if two objects are equal, or are both null.- Parameters:
s
- First objectt
- Second object- Returns:
- Whether objects are equal or both null
-
equals
Returns true if two strings are equal, or are both null.The result is not affected by
the case sensitive option
; if you wish to compare names, useequalName(String, String)
. -
equalName
Returns whether two names are equal. Takes into account thecase sensitive option
. Names may be null. -
equal
Tests two strings for equality, optionally ignoring case.- Parameters:
s
- First stringt
- Second stringmatchCase
- Whether to perform case-sensitive match- Returns:
- Whether strings are equal
-
caseSensitiveCompareName
Compares two names. if case sensitive flag is false, apply finer grain difference with case sensitive Takes into account thecase sensitive option
. Names must not be null. -
compareName
Compares two names. Takes into account thecase sensitive option
. Names must not be null. -
normalizeName
Generates a normalized form of a name, for use as a key into a map. Returns the upper case name ifMondrianProperties.CaseSensitive
is true, the name unchanged otherwise. -
compareKey
Returns the result of ((Comparable) k1).compareTo(k2), with special-casing for the fact that Boolean only became comparable in JDK 1.5.- See Also:
-
compare
public static int compare(int i0, int i1) Compares integer values.- Parameters:
i0
- First integeri1
- Second integer- Returns:
- Comparison of integers
-
replace
Returns a string with every occurrence of a seek string replaced with another. -
replace
Replaces all occurrences of a string in a buffer with another.- Parameters:
buf
- String buffer to act onstart
- Ordinal withinfind
to start searchingfind
- String to findreplace
- String to replace it with- Returns:
- The string buffer
-
parseIdentifier
Parses an MDX identifier such as[Foo].[Bar].Baz.&Key&Key2
and returns the result as a list of segments.- Parameters:
s
- MDX identifier- Returns:
- List of segments
-
implode
Converts an array of name parts {"part1", "part2"} into a single string "[part1].[part2]". If the names contain "]" they are escaped as "]]". -
makeFqName
-
makeFqName
-
makeFqName
-
lookupCompound
public static OlapElement lookupCompound(SchemaReader schemaReader, OlapElement parent, List<Id.Segment> names, boolean failIfNotFound, int category) -
lookupCompound
public 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.- Parameters:
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, aCategory
value;Category.Unknown
if it doesn't matter.- See Also:
-
lookup
-
lookup
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.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 aResolvedFunCall
.- Parameters:
q
- Query expression belongs tonameParts
- Parts of the identifierallowProp
- Whether to allow property references- Returns:
- OLAP object or property reference
-
lookup
public 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.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 aResolvedFunCall
.- Parameters:
q
- Query expression belongs toschemaReader
- Schema readersegments
- Parts of the identifierallowProp
- Whether to allow property references- Returns:
- OLAP object or property reference
-
createExpr
Converts an olap element (dimension, hierarchy, level or member) into an expression representing a usage of that element in an MDX statement. -
lookupHierarchyRootMember
public static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName) -
lookupHierarchyRootMember
public static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.NameSegment memberName, MatchType matchType) Finds a root member of a hierarchy with a given name.- Parameters:
hierarchy
- HierarchymemberName
- Name of root member- Returns:
- Member, or null if not found
-
lookupHierarchyLevel
Finds a named level in this hierarchy. Returns null if there is no such level. -
getMemberOrdinalInParent
Finds the zero based ordinal of a Member among its siblings. -
getFirstDescendantOnLevel
returns the first descendant on the level underneath parent. If parent = [Time].[1997] and level = [Time].[Month], then the member [Time].[1997].[Q1].[1] will be returned -
isEmpty
Returns whether a string is null or empty. -
singleQuoteString
Encloses a value in single-quotes, to make a SQL string value. Examples:singleQuoteForSql(null)
yieldsNULL
;singleQuoteForSql("don't")
yields'don''t'
. -
singleQuoteString
Encloses a value in single-quotes, to make a SQL string value. Examples:singleQuoteForSql(null)
yieldsNULL
;singleQuoteForSql("don't")
yields'don''t'
. -
createRandom
Creates a random number generator.- Parameters:
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.)- Returns:
- A random number generator.
-
isValidProperty
Returns whether a property is valid for a member of a given level. It is valid if the property is defined at the level or at an ancestor level, or if the property is a standard property such as "FORMATTED_VALUE".- Parameters:
propertyName
- Property namelevel
- Level- Returns:
- Whether property is valid
-
lookupProperty
Finds a member property calledpropertyName
at, or above,level
. -
deprecated
public static <T> T deprecated(T reason) Deprecated.Insert a call to this method if you want to flag a piece of undesirable code. -
deprecated
public static <T> T deprecated(T reason, boolean fail) Deprecated.Insert a call to this method if you want to flag a piece of undesirable code. -
addLevelCalculatedMembers
-
needToImplement
Returns an exception which indicates that a particular piece of functionality should work, but a developer has not implemented it yet. -
badValue
Returns an exception indicating that we didn't expect to find this value here. -
wildcardToRegexp
Converts a list of SQL-style patterns into a Java regular expression.For example, {"Foo_", "Bar%BAZ"} becomes "Foo.|Bar.*BAZ".
- Parameters:
wildcards
- List of SQL-style wildcard expressions- Returns:
- Regular expression
-
camelToUpper
Converts a camel-case name to an upper-case name with underscores.For example,
camelToUpper("FooBar")
returns "FOO_BAR".- Parameters:
s
- Camel-case string- Returns:
- Upper-case string
-
parseCommaList
Parses a comma-separated list.If a value contains a comma, escape it with a second comma. For example,
parseCommaList("x,y,,z")
returns{"x", "y,z"}
.- Parameters:
nameCommaList
- List of names separated by commas- Returns:
- List of names
-
getAnnotation
Returns an annotation of a particular class on a method. Returns the default value if the annotation is not present, or in JDK 1.4.- Parameters:
method
- Method containing annotationannotationClassName
- Name of annotation class to finddefaultValue
- Value to return if annotation is not present- Returns:
- value of annotation
-
cancelStatement
Closes and cancels aStatement
using the correct methods available on the current Java runtime.If errors are encountered while canceling a statement, the message is logged in
Util
.- Parameters:
stmt
- The statement to cancel.
-
getMemoryInfo
-
commaList
Converts a list of a string. For example,commaList("foo", Arrays.asList({"a", "b"}))
returns "foo(a, b)".- Parameters:
s
- Prefixlist
- List- Returns:
- String representation of string
-
uniquify
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.- Parameters:
name
- Suggested name, may not be uniquemaxLength
- Maximum length of generated namenameList
- Collection of names already used- Returns:
- Unique name
-
areOccurencesEqual
Returns whether a collection contains precisely one distinct element. Returns false if the collection is empty, or if it contains elements that are not the same as each other.- Parameters:
collection
- Collection- Returns:
- boolean true if all values are same
-
flatList
Creates a memory-, CPU- and cache-efficient immutable list.- Type Parameters:
T
- Element type- Parameters:
t
- Array of members of list- Returns:
- List containing the given members
-
flatListCopy
Creates a memory-, CPU- and cache-efficient immutable list, always copying the contents.- Type Parameters:
T
- Element type- Parameters:
t
- Array of members of list- Returns:
- List containing the given members
-
flatList
Creates a memory-, CPU- and cache-efficient immutable list from an existing list. The list is always copied.- Type Parameters:
T
- Element type- Parameters:
t
- Array of members of list- Returns:
- List containing the given members
-
parseLocale
Parses a locale string.The inverse operation of
Locale.toString()
.- Parameters:
localeString
- Locale string, e.g. "en" or "en_US"- Returns:
- Java locale object
-
parseInterval
public static Pair<Long,TimeUnit> parseInterval(String s, TimeUnit unit) throws NumberFormatException Parses an interval.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.- Parameters:
s
- String to parseunit
- Default time unit; may be null- Returns:
- Pair of value and time unit. Neither pair or its components are null
- Throws:
NumberFormatException
- if unit is not present and there is no default, or if number is not valid
-
convert
Converts a list of olap4j-style segments to a list of mondrian-style segments.- Parameters:
olap4jSegmentList
- List of olap4j segments- Returns:
- List of mondrian segments
-
convert
Converts an olap4j-style segment to a mondrian-style segment.- Parameters:
olap4jSegment
- olap4j segment- Returns:
- mondrian segment
-
filter
Applies a collection of filters to an iterable.- Type Parameters:
T
-- Parameters:
iterable
- Iterableconds
- Zero or more conditions- Returns:
- Iterable that returns only members of underlying iterable for for which all conditions evaluate to true
-
sort
Sorts a collection ofComparable
objects and returns a list.- Type Parameters:
T
- Element type- Parameters:
collection
- Collection- Returns:
- Sorted list
-
sort
Sorts a collection of objects using aComparator
and returns a list.- Type Parameters:
T
- Element type- Parameters:
collection
- Collectioncomparator
- Comparator- Returns:
- Sorted list
-
toOlap4j
-
toOlap4j
-
toOlap4j
-
matches
-
matches
-
newElementNotFoundException
public static RuntimeException newElementNotFoundException(int category, org.olap4j.mdx.IdentifierNode identifierNode) -
safeGet
CallsFuture.get()
and converts any throwable into a non-checked exception.- Type Parameters:
T
- Result type- Parameters:
future
- Futuremessage
- Message to qualify wrapped exception- Returns:
- Result
-
newIdentityHashSetFake
-
newTimer
Equivalent toTimer(String, boolean)
. (Introduced in JDK 1.5.)- Parameters:
name
- the name of the associated threadisDaemon
- true if the associated thread should run as a daemon- Returns:
- timer
-
binarySearch
As Arrays#binarySearch(Object[], int, int, Object), but available pre-JDK 1.6. -
intersect
Returns the intersection of two sorted sets. Does not modify either set.Optimized for the case that both sets are
ArraySortedSet
.- Parameters:
set1
- First setset2
- Second set- Returns:
- Intersection of the sets
-
compareIntegers
public static int compareIntegers(int i0, int i1) Compares two integers using the same algorithm asInteger.compareTo(Integer)
.- Parameters:
i0
- First integeri1
- Second integer- Returns:
- Comparison
-
last
Returns the last item in a list.- Type Parameters:
T
- Element type- Parameters:
list
- List- Returns:
- Last item in the list
- Throws:
IndexOutOfBoundsException
- if list is empty
-
only
Returns the sole item in a list.If the list has 0 or more than one element, throws.
- Type Parameters:
T
- Element type- Parameters:
list
- List- Returns:
- Sole item in the list
- Throws:
IndexOutOfBoundsException
- if list is empty or has more than 1 elt
-
close
Closes a JDBC result set, statement, and connection, ignoring any errors. If any of them are null, that's fine.If any of them throws a
SQLException
, returns the first such exception, but always executes all closes.- Parameters:
resultSet
- Result setstatement
- Statementconnection
- Connection
-
bitSetBetween
Creates a bitset with bits fromfromIndex
(inclusive) to specifiedtoIndex
(exclusive) set totrue
.For example,
bitSetBetween(0, 3)
returns a bit set with bits {0, 1, 2} set.- Parameters:
fromIndex
- Index of the first bit to be set.toIndex
- Index after the last bit to be set.- Returns:
- Bit set
-
genericArray
-
assertTrue
public static void assertTrue(boolean b) Throws an internal error if condition is not true. It would be calledassert
, but that is a keyword as of JDK 1.4. -
assertTrue
Throws an internal error with the given messagee if condition is not true. It would be calledassert
, but that is a keyword as of JDK 1.4. -
newInternal
Creates an internal error with a given message. -
newInternal
Creates an internal error with a given message and cause. -
newError
Creates a non-internal error. Currently implemented in terms of internal errors, but later we will create resourced messages. -
newError
Creates a non-internal error. Currently implemented in terms of internal errors, but later we will create resourced messages. -
unexpected
Returns an exception indicating that we didn't expect to find this value here.- Parameters:
value
- Value
-
assertPrecondition
public static void assertPrecondition(boolean b) Checks that a precondition (declared using the javadoc@pre
tag) is satisfied.- Parameters:
b
- The value of executing the condition
-
assertPrecondition
Checks that a precondition (declared using the javadoc@pre
tag) is satisfied. For example,void f(String s) { Util.assertPrecondition(s != null, "s != null"); ... }
- Parameters:
b
- The value of executing the conditioncondition
- The text of the condition
-
assertPostcondition
public static void assertPostcondition(boolean b) Checks that a postcondition (declared using the javadoc@post
tag) is satisfied.- Parameters:
b
- The value of executing the condition
-
assertPostcondition
Checks that a postcondition (declared using the javadoc@post
tag) is satisfied.- Parameters:
b
- The value of executing the condition
-
convertStackToString
Converts an error into an array of strings, the most recent error first.- Parameters:
e
- the error; may be null. Errors are chained according to theircause
.
-
getErrorMessage
Constructs the message associated with an arbitrary Java error, making up one based on the stack trace if there is none. AsgetErrorMessage(Throwable,boolean)
, but does not print the class name if the exception is derived fromSQLException
or is exactly aException
. -
getErrorMessage
Constructs the message associated with an arbitrary Java error, making up one based on the stack trace if there is none.- Parameters:
err
- the errorprependClassName
- should the error be preceded by the class name of the Java exception? defaults to false, unless the error is derived fromSQLException
or is exactly aException
-
getMatchingCause
If one of the causes of an exception is of a particular class, returns that cause. Otherwise returns null.- Type Parameters:
T
- Class- Parameters:
e
- Exceptionclazz
- Desired class- Returns:
- Cause of given class, or null
-
unparse
Converts an expression to a string. -
unparse
Converts an query to a string. -
toURL
Creates a file-protocol URL for the given file.- Throws:
MalformedURLException
-
parseConnectString
Converts an OLE DB connect string into aUtil.PropertyList
.For example,
"Provider=MSOLAP; DataSource=LOCALHOST;"
becomes the set of (key, value) pairs{("Provider","MSOLAP"), ("DataSource", "LOCALHOST")}
. Another example isProvider='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. -
hash
public static int hash(int i, int j) Combines two integers into a hash code. -
hash
Computes a hash code from an existing hash code and an object (which may be null). -
hashArray
Computes a hash code from an existing hash code and an array of objects (which may be null). -
appendArrays
public static <T> T[] appendArrays(T[] a0, T[]... as) Concatenates one or more arrays.Resulting array has same element type as first array. Each arrays may be empty, but must not be null.
- Parameters:
a0
- First arrayas
- Zero or more subsequent arrays- Returns:
- Array containing all elements
-
append
public static <T> T[] append(T[] a, T o) Adds an object to the end of an array. The resulting array is of the same type (e.g.String[]
) as the input array.- Parameters:
a
- Arrayo
- Element- Returns:
- New array containing original array plus element
- See Also:
-
copyOf
public static double[] copyOf(double[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(double[], int)- Parameters:
original
- the array to be copiednewLength
- the length of the copy to be returned- Returns:
- a copy of the original array, truncated or padded with zeros to obtain the specified length
-
copyOf
public static int[] copyOf(int[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(int[], int)- Parameters:
original
- the array to be copiednewLength
- the length of the copy to be returned- Returns:
- a copy of the original array, truncated or padded with zeros to obtain the specified length
-
copyOf
public static long[] copyOf(long[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(long[], int)- Parameters:
original
- the array to be copiednewLength
- the length of the copy to be returned- Returns:
- a copy of the original array, truncated or padded with zeros to obtain the specified length
-
copyOf
public static <T> T[] copyOf(T[] original, int newLength) Like
, but exists prior to JDK 1.6.Arrays
.copyOf(Object[], int)- Parameters:
original
- the array to be copiednewLength
- the length of the copy to be returned- Returns:
- a copy of the original array, truncated or padded with zeros to obtain the specified length
-
copyOf
Copies the specified array.- Parameters:
original
- the array to be copiednewLength
- the length of the copy to be returnednewType
- the class of the copy to be returned- Returns:
- a copy of the original array, truncated or padded with nulls to obtain the specified length
-
dbTimeMillis
public static long dbTimeMillis()Deprecated.UseMonitor.getServer()
andServerInfo.sqlStatementExecuteNanos
; will be removed in 4.0.Returns the cumulative amount of time spent accessing the database. -
addDatabaseTime
public static void addDatabaseTime(long millis) Deprecated.Will be removed in 4.0.Adds to the cumulative amount of time spent accessing the database. -
nonDbTimeMillis
public static long nonDbTimeMillis()Deprecated.Will be removed in 4.0.Returns the system time less the time spent accessing the database. Use this method to figure out how long an operation took: call this method before an operation and after an operation, and the difference is the amount of non-database time spent. -
createSimpleValidator
Creates a very simple implementation ofValidator
. (Only useful for resolving trivial expressions.) -
readFully
Reads a Reader until it returns EOF and returns the contents as a String.- Parameters:
rdr
- Reader to Read.bufferSize
- size of buffer to allocate for reading.- Returns:
- content of Reader as String
- Throws:
IOException
- on I/O error
-
readFully
Reads an input stream until it returns EOF and returns the contents as an array of bytes.- Parameters:
in
- Input streambufferSize
- size of buffer to allocate for reading.- Returns:
- content of stream as an array of bytes
- Throws:
IOException
- on I/O error
-
readURL
Returns the contents of a URL, substituting tokens.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.
- Parameters:
urlStr
- URL stringmap
- Key/value map- Returns:
- Contents of URL with tokens substituted
- Throws:
IOException
- on I/O error
-
readURL
Returns the contents of a URL.- Parameters:
url
- URL- Returns:
- Contents of URL
- Throws:
IOException
- on I/O error
-
readURL
Returns the contents of a URL, substituting tokens.Replaces the tokens "${key}" if the map is not null and "key" occurs in the key-value map.
- Parameters:
url
- URLmap
- Key/value map- Returns:
- Contents of URL with tokens substituted
- Throws:
IOException
- on I/O error
-
readVirtualFile
public static InputStream readVirtualFile(String url) throws org.apache.commons.vfs2.FileSystemException Gets content via Apache VFS. File must exist and have content- Parameters:
url
- String- Returns:
- Apache VFS FileContent for further processing
- Throws:
org.apache.commons.vfs2.FileSystemException
- on error
-
readVirtualFileAsString
- Throws:
IOException
-
toMap
Converts aProperties
object to a string-to-stringMap
.- Parameters:
properties
- Properties- Returns:
- String-to-string map
-
replaceProperties
Replaces tokens in a string.Replaces the tokens "${key}" if "key" occurs in the key-value map. Otherwise "${key}" is left in the string unchanged.
- Parameters:
text
- Source stringenv
- Map of key-value pairs- Returns:
- String with tokens substituted
-
printMemory
-
printMemory
-
cast
Casts a Set to a Set with a different element type.- Parameters:
set
- Set- Returns:
- Set of desired type
-
cast
Casts a List to a List with a different element type.- Parameters:
list
- List- Returns:
- List of desired type
-
canCast
Returns whether it is safe to cast a collection to a collection with a given element type.- Type Parameters:
T
- Element type- Parameters:
collection
- Collectionclazz
- Target element type- Returns:
- Whether all not-null elements of the collection are instances of element type
-
castToIterable
Casts a collection to iterable. Under JDK 1.4,Collection
objects do not implementIterable
, 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 tocom.rc.retroweaver.runtime.Retroweaver_
.Under later JDKs this method is trivial. This method can be deleted when we discontinue support for JDK 1.4.
- Type Parameters:
T
- Element type- Parameters:
iterable
- Object which ought to be iterable- Returns:
- Object cast to Iterable
-
lookup
Looks up an enumeration by name, returning null if null or not valid.- Parameters:
clazz
- Enumerated typename
- Name of constant
-
lookup
Looks up an enumeration by name, returning a given default value if null or not valid.- Parameters:
clazz
- Enumerated typename
- Name of constantdefaultValue
- Default value if constant is not found- Returns:
- Value, or null if name is null or value does not exist
-
makeBigDecimalFromDouble
Make a BigDecimal from a double. On JDK 1.5 or later, the BigDecimal precision reflects the precision of the double while with JDK 1.4 this is not the case.- Parameters:
d
- the input double- Returns:
- the BigDecimal
-
quotePattern
Returns a literal pattern String for the specified String.Specification as for
Pattern.quote(String)
, which was introduced in JDK 1.5.- Parameters:
s
- The string to be literalized- Returns:
- A literal string replacement
-
generateUuidString
Generates a unique id.From JDK 1.5 onwards, uses a
UUID
.- Returns:
- A unique id
-
compileScript
Compiles a script to yield a Java interface.Only valid JDK 1.6 and higher; fails on JDK 1.5 and earlier.
- Type Parameters:
T
- Interface- Parameters:
iface
- Interface script should implementscript
- Script codeengineName
- Name of engine (e.g. "JavaScript")- Returns:
- Object that implements given interface
-
threadLocalRemove
Removes a thread local from the current thread.From JDK 1.5 onwards, calls
ThreadLocal.remove()
; before that, no-ops.- Type Parameters:
T
- Type- Parameters:
threadLocal
- Thread local
-
newIdentityHashSet
Creates a hash set that, likeIdentityHashMap
, compares keys using identity.- Type Parameters:
T
- Element type- Returns:
- Set
-
createUdf
public static UserDefinedFunction createUdf(Class<? extends UserDefinedFunction> udfClass, String functionName) Creates a new udf instance from the given udf class.- Parameters:
udfClass
- the class to create new instance forfunctionName
- Function name, or null- Returns:
- an instance of UserDefinedFunction
-
checkCJResultLimit
public static void checkCJResultLimit(long resultSize) Check the resultSize against the result limit setting. Throws LimitExceededDuringCrossjoin exception if limit exceeded. When it is called from RolapNativeSet.checkCrossJoin(), it is only possible to check the known input size, because the final CJ result will come from the DB(and will be checked against the limit when fetching from the JDBC result set, in SqlTupleReader.prepareTuples())- Parameters:
resultSize
- Result limit- Throws:
ResourceLimitExceededException
-
convertOlap4jConnectStringToNativeMondrian
Converts an olap4j connect string into a legacy mondrian connect string.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.
- Parameters:
url
- olap4j connect string- Returns:
- mondrian connect string, or null if cannot be converted
-
isBlank
Checks if a String is whitespace, empty ("") or null.StringUtils.isBlank(null) = true StringUtils.isBlank("") = true StringUtils.isBlank(" ") = true StringUtils.isBlank("bob") = false StringUtils.isBlank(" bob ") = false
(Copied from commons-lang.)
- Parameters:
str
- the String to check, may be null- Returns:
true
if the String is null, empty or whitespace
-
createRootRole
Returns a role which has access to everything.- Parameters:
schema
- A schema to bind this role to.- Returns:
- A role with root access to the schema.
-
getDimensionCube
Tries to find the cube from which a dimension is taken. It considers private dimensions, shared dimensions and virtual dimensions. If it can't determine with certitude the origin of the dimension, it returns null. -
getClosestResource
Similar toClassLoader.getResource(String)
, except the lookup is in reverse order.
i.e. returns the resource from the supplied classLoader or the one closest to it in the hierarchy, instead of the closest to the root class loader- Parameters:
classLoader
- The class loader to fetch fromname
- The resource name- Returns:
- A URL object for reading the resource, or null if the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
- See Also:
-
identityFunctor
-
trueFunctor
-
falseFunctor
-
toNullValuesMap
Transforms a list into a map for which all the keys return a null value associated to it.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. -
explain
Called during major steps of executing a MDX query to provide insight into Calc calls/times and key function calls/times.- Parameters:
handler
-title
-calc
-timing
-
-
addAppender
public static void addAppender(org.apache.logging.log4j.core.Appender appender, org.apache.logging.log4j.Logger logger, org.apache.logging.log4j.Level level) -
removeAppender
public static void removeAppender(org.apache.logging.log4j.core.Appender appender, org.apache.logging.log4j.Logger logger) -
makeAppender
public static org.apache.logging.log4j.core.Appender makeAppender(String name, StringWriter sw, String layout) -
setLevel
public static void setLevel(org.apache.logging.log4j.Logger logger, org.apache.logging.log4j.Level level)
-