mondrian.olap
Class Util

java.lang.Object
  extended by org.eigenbase.xom.XMLUtil
      extended by org.eigenbase.xom.XOMUtil
          extended by mondrian.olap.Util
Direct Known Subclasses:
FunUtil

public class Util
extends XOMUtil

Utility functions used throughout mondrian. All methods are static.

Since:
6 August, 2001
Version:
$Id: //open/mondrian-release/3.2/src/main/mondrian/olap/Util.java#13 $
Author:
jhyde

Nested Class Summary
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 class Util.PropertyList
          PropertyList is an order-preserving list of key-value pairs.
 
Field Summary
static Object EmptyValue
          Placeholder which indicates an EMPTY value.
static int JdbcVersion
          What version of JDBC? Returns 4 in JDK 1.6 and higher, 3 otherwise.
static String nl
           
static Object nullValue
          Placeholder which indicates a value NULL.
static boolean PreJdk15
          Whether we are running a version of Java before 1.5.
static boolean Retrowoven
          Whether the code base has re-engineered using retroweaver.
 
Constructor Summary
Util()
           
 
Method Summary
static void addDatabaseTime(long millis)
          Adds to the cumulative amount of time spent accessing the database.
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>>
RuntimeException
badValue(Enum<T> anEnum)
          Returns an exception indicating that we didn't expect to find this value here.
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 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
<T> String
commaList(String s, List<T> list)
          Converts a list of a string.
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 Id.Segment convert(IdentifierNode.Segment olap4jSegment)
          Converts an olap4j-style segment to a mondrian-style segment.
static List<Id.Segment> convert(List<IdentifierNode.Segment> 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 Arrays.copyOf(double[], int), but exists prior to JDK 1.6.
static int[] copyOf(int[] original, int newLength)
          Like Arrays.copyOf(int[], int), but exists prior to JDK 1.6.
static Object[] copyOf(Object[] original, int newLength)
          Like Arrays.copyOf(Object[], int), but exists prior to JDK 1.6.
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 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()
          Returns the cumulative amount of time spent accessing the database.
static void deprecated(String reason)
          Deprecated.  
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
<T> List<T>
flatList(T[] t)
          Creates a memory-, CPU- and cache-efficient immutable list.
static
<T> T
getAnnotation(Method method, String annotationClassName, T defaultValue)
          Returns an annotation of a particular class on a method.
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 Member getFirstDescendantOnLevel(SchemaReader reader, Member parent, Level level)
          returns the first descendant on the level underneath parent.
static int getMemberOrdinalInParent(SchemaReader reader, Member member)
          Finds the zero based ordinal of a Member among its siblings.
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 String implode(List<Id.Segment> names)
          Converts an array of name parts {"part1", "part2"} into a single string "[part1].[part2]".
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(Member member, String propertyName)
          Returns whether a property is valid for a given member.
static
<E extends Enum<E>>
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>>
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> 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 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.
(package private) static Cube lookupCube(SchemaReader schemaReader, String cubeName, boolean fail)
          Looks up a cube in a schema reader.
static Level lookupHierarchyLevel(Hierarchy hierarchy, String s)
          Finds a named level in this hierarchy.
static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.Segment memberName)
           
static Member lookupHierarchyRootMember(SchemaReader reader, Hierarchy hierarchy, Id.Segment memberName, MatchType matchType)
          Finds a root member of a hierarchy with a given name.
protected 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 String maskVersion(String str)
          Masks Mondrian's version number from a string.
static String mdxEncodeString(String st)
          Encodes string for MDX (escapes ] as ]] inside a name).
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 newError(String message)
          Creates a non-internal error.
static RuntimeException newError(Throwable e, String message)
          Creates a non-internal error.
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 long nonDbTimeMillis()
          Returns the system time less the time spent accessing the database.
static String normalizeName(String s)
          Generates a normalized form of a name, for use as a key into a map.
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 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 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 String readFully(Reader rdr, int bufferSize)
          Reads a Reader until it returns EOF and return the contents as a String.
static String readURL(String urlStr)
          Read URL and return String containing content.
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 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 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 Map<String,String> toMap(Properties properties)
          Converts a Properties object to a string-to-string Map.
static URL toURL(File file)
          Creates a file-protocol URL for the given file.
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.
 
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
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

nl

public static final String nl

nullValue

public static final Object nullValue
Placeholder which indicates a value NULL.


EmptyValue

public static final Object EmptyValue
Placeholder which indicates an EMPTY value.


PreJdk15

public static final boolean PreJdk15
Whether we are running a version of Java before 1.5.

If this variable is true, we will be running retroweaver. Retroweaver has some problems involving EnumSet.


JdbcVersion

public static final int JdbcVersion
What version of JDBC? Returns 4 in JDK 1.6 and higher, 3 otherwise.


Retrowoven

public static final boolean Retrowoven
Whether the code base has re-engineered using retroweaver. If this is the case, some functionality is not available.

Constructor Detail

Util

public Util()
Method Detail

isNull

public static boolean isNull(Object o)

isSorted

public static <T> boolean isSorted(List<T> list)
Returns whether a list is strictly sorted.

Parameters:
list - List
Returns:
whether list is sorted

mdxEncodeString

public static String mdxEncodeString(String st)
Encodes string for MDX (escapes ] as ]] inside a name).


quoteForMdx

public static String quoteForMdx(String val)
Converts a string into a double-quoted string.


quoteForMdx

public static StringBuilder quoteForMdx(StringBuilder buf,
                                        String val)
Appends a double-quoted string to a string builder.


quoteMdxIdentifier

public static String quoteMdxIdentifier(String id)
Return string quoted in [...]. For example, "San Francisco" becomes "[San Francisco]"; "a [bracketed] string" becomes "[a [bracketed]] string]".


quoteMdxIdentifier

public static void quoteMdxIdentifier(String id,
                                      StringBuilder buf)

quoteMdxIdentifier

public static String quoteMdxIdentifier(List<Id.Segment> ids)
Return identifiers quoted in [...].[...]. For example, {"Store", "USA", "California"} becomes "[Store].[USA].[California]".


quoteMdxIdentifier

public static void quoteMdxIdentifier(List<Id.Segment> ids,
                                      StringBuilder sb)

equals

public static boolean equals(Object s,
                             Object t)
Returns true if two objects are equal, or are both null.

Parameters:
s - First object
t - Second object
Returns:
Whether objects are equal or both null

equals

public static boolean equals(String s,
                             String t)
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, use equalName(String, String).


equalName

public static boolean equalName(String s,
                                String t)
Returns whether two names are equal. Takes into account the case sensitive option. Names may be null.


equal

public static boolean equal(String s,
                            String t,
                            boolean matchCase)
Tests two strings for equality, optionally ignoring case.

Parameters:
s - First string
t - Second string
matchCase - Whether to perform case-sensitive match
Returns:
Whether strings are equal

caseSensitiveCompareName

public static int caseSensitiveCompareName(String s,
                                           String t)
Compares two names. if case sensitive flag is false, apply finer grain difference with case sensitive Takes into account the case sensitive option. Names must not be null.


compareName

public static int compareName(String s,
                              String t)
Compares two names. Takes into account the case sensitive option. Names must not be null.


normalizeName

public static String normalizeName(String s)
Generates a normalized form of a name, for use as a key into a map. Returns the upper case name if MondrianProperties.CaseSensitive is true, the name unchanged otherwise.


compareKey

public 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.

See Also:
Comparable.compareTo(T)

replace

public static String replace(String s,
                             String find,
                             String replace)
Returns a string with every occurrence of a seek string replaced with another.


replace

public static StringBuilder replace(StringBuilder buf,
                                    int start,
                                    String find,
                                    String replace)
Replaces all occurrences of a string in a buffer with another.

Parameters:
buf - String buffer to act on
start - Ordinal within find to start searching
find - String to find
replace - String to replace it with
Returns:
The string buffer

parseIdentifier

public 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.

Parameters:
s - MDX identifier
Returns:
List of segments

implode

public static String implode(List<Id.Segment> names)
Converts an array of name parts {"part1", "part2"} into a single string "[part1].[part2]". If the names contain "]" they are escaped as "]]".


makeFqName

public static String makeFqName(String name)

makeFqName

public static String makeFqName(OlapElement parent,
                                String name)

makeFqName

public static String makeFqName(String parentUniqueName,
                                String name)

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 context
parent - Parent element to search in
names - Exploded compound name, such as {"Products", "Product Department", "Produce"}
failIfNotFound - If the element is not found, determines whether to return null or throw an error
category - Type of returned element, a Category value; Category.Unknown if it doesn't matter.
See Also:
parseIdentifier(String)
Pre-condition:
parent != null
Post-condition:
!(failIfNotFound && return == null)

lookup

public static OlapElement lookup(Query q,
                                 List<Id.Segment> nameParts)

lookup

public 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.

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.

Parameters:
q - Query expression belongs to
nameParts - Parts of the identifier
allowProp - Whether to allow property references
Returns:
OLAP object or property reference

lookup

public static Exp lookup(Query q,
                         SchemaReader schemaReader,
                         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.

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.

Parameters:
q - Query expression belongs to
schemaReader - Schema reader
nameParts - Parts of the identifier
allowProp - Whether to allow property references
Returns:
OLAP object or property reference

lookupCube

static Cube lookupCube(SchemaReader schemaReader,
                       String cubeName,
                       boolean fail)
Looks up a cube in a schema reader.

Parameters:
cubeName - Cube name
fail - Whether to fail if not found.
Returns:
Cube, or null if not found

createExpr

public 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.


lookupHierarchyRootMember

public static Member lookupHierarchyRootMember(SchemaReader reader,
                                               Hierarchy hierarchy,
                                               Id.Segment memberName)

lookupHierarchyRootMember

public static Member lookupHierarchyRootMember(SchemaReader reader,
                                               Hierarchy hierarchy,
                                               Id.Segment memberName,
                                               MatchType matchType)
Finds a root member of a hierarchy with a given name.

Parameters:
hierarchy - Hierarchy
memberName - Name of root member
Returns:
Member, or null if not found

lookupHierarchyLevel

public static Level lookupHierarchyLevel(Hierarchy hierarchy,
                                         String s)
Finds a named level in this hierarchy. Returns null if there is no such level.


getMemberOrdinalInParent

public static int getMemberOrdinalInParent(SchemaReader reader,
                                           Member member)
Finds the zero based ordinal of a Member among its siblings.


getFirstDescendantOnLevel

public static Member getFirstDescendantOnLevel(SchemaReader reader,
                                               Member parent,
                                               Level level)
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

public static boolean isEmpty(String s)
Returns whether a string is null or empty.


singleQuoteString

public static String singleQuoteString(String val)
Encloses a value in single-quotes, to make a SQL string value. Examples: singleQuoteForSql(null) yields NULL; singleQuoteForSql("don't") yields 'don''t'.


singleQuoteString

public static void singleQuoteString(String val,
                                     StringBuilder buf)
Encloses a value in single-quotes, to make a SQL string value. Examples: singleQuoteForSql(null) yields NULL; singleQuoteForSql("don't") yields 'don''t'.


createRandom

public static Random createRandom(long seed)
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

public static boolean isValidProperty(Member member,
                                      String propertyName)
Returns whether a property is valid for a given member. It is valid if the property is defined at the member's level or at an ancestor level, or if the property is a standard property such as "FORMATTED_VALUE".

Parameters:
member - Member
propertyName - Property name
Returns:
Whether property is valid

lookupProperty

protected static Property lookupProperty(Level level,
                                         String propertyName)
Finds a member property called propertyName at, or above, level.


deprecated

public static void deprecated(String reason)
Deprecated. 

Insert a call to this method if you want to flag a piece of undesirable code.


addLevelCalculatedMembers

public static List<Member> addLevelCalculatedMembers(SchemaReader reader,
                                                     Level level,
                                                     List<Member> members)

needToImplement

public 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.


badValue

public static <T extends Enum<T>> RuntimeException badValue(Enum<T> anEnum)
Returns an exception indicating that we didn't expect to find this value here.


maskVersion

public static String maskVersion(String str)
Masks Mondrian's version number from a string.

Parameters:
str - String
Returns:
String with each occurrence of mondrian's version number (e.g. "2.3.0.0") replaced with "${mondrianVersion}"

wildcardToRegexp

public static String wildcardToRegexp(List<String> wildcards)
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

public static String camelToUpper(String s)
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

public static List<String> parseCommaList(String nameCommaList)
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

public static <T> T getAnnotation(Method method,
                                  String annotationClassName,
                                  T defaultValue)
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 annotation
annotationClassName - Name of annotation class to find
defaultValue - Value to return if annotation is not present
Returns:
value of annotation

commaList

public static <T> String commaList(String s,
                                   List<T> list)
Converts a list of a string. For example, commaList("foo", Arrays.asList({"a", "b"})) returns "foo(a, b)".

Parameters:
s - Prefix
list - List
Returns:
String representation of string

uniquify

public 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.

Parameters:
name - Suggested name, may not be unique
maxLength - Maximum length of generated name
nameList - Collection of names already used
Returns:
Unique name

areOccurencesEqual

public static <T> boolean areOccurencesEqual(Collection<T> collection)
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

public static <T> List<T> flatList(T[] t)
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

parseLocale

public static Locale parseLocale(String localeString)
Parses a locale string.

The inverse operation of Locale.toString().

Parameters:
localeString - Locale string, e.g. "en" or "en_US"
Returns:
Java locale object

convert

public static List<Id.Segment> convert(List<IdentifierNode.Segment> olap4jSegmentList)
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

public static Id.Segment convert(IdentifierNode.Segment olap4jSegment)
Converts an olap4j-style segment to a mondrian-style segment.

Parameters:
olap4jSegment - olap4j segment
Returns:
mondrian segment

assertTrue

public static void assertTrue(boolean b)
Throws an internal error if condition is not true. It would be called assert, but that is a keyword as of JDK 1.4.


assertTrue

public static void assertTrue(boolean b,
                              String message)
Throws an internal error with the given messagee if condition is not true. It would be called assert, but that is a keyword as of JDK 1.4.


newInternal

public static RuntimeException newInternal(String message)
Creates an internal error with a given message.


newInternal

public static RuntimeException newInternal(Throwable e,
                                           String message)
Creates an internal error with a given message and cause.


newError

public static RuntimeException newError(String message)
Creates a non-internal error. Currently implemented in terms of internal errors, but later we will create resourced messages.


newError

public static RuntimeException newError(Throwable e,
                                        String message)
Creates a non-internal error. Currently implemented in terms of internal errors, but later we will create resourced messages.


unexpected

public static RuntimeException unexpected(Enum value)
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

public static void assertPrecondition(boolean b,
                                      String condition)
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 condition
condition - 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

public static void assertPostcondition(boolean b,
                                       String condition)
Checks that a postcondition (declared using the javadoc @post tag) is satisfied.

Parameters:
b - The value of executing the condition

convertStackToString

public static String[] convertStackToString(Throwable e)
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 their cause.

getErrorMessage

public 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. As getErrorMessage(Throwable,boolean), but does not print the class name if the exception is derived from SQLException or is exactly a Exception.


getErrorMessage

public 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.

Parameters:
err - the error
prependClassName - 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

unparse

public static String unparse(Exp exp)
Converts an expression to a string.


unparse

public static String unparse(Query query)
Converts an query to a string.


toURL

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

Throws:
MalformedURLException

parseConnectString

public static Util.PropertyList parseConnectString(String s)
Converts an OLE DB connect string into a 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.


hash

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


hash

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


hashArray

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


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 array
as - 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 - Array
o - Element
Returns:
New array containing original array plus element
See Also:
appendArrays(T[], T[]...)

copyOf

public static double[] copyOf(double[] original,
                              int newLength)
Like Arrays.copyOf(double[], int), but exists prior to JDK 1.6.

Parameters:
original - the array to be copied
newLength - 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 Arrays.copyOf(int[], int), but exists prior to JDK 1.6.

Parameters:
original - the array to be copied
newLength - 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 Object[] copyOf(Object[] original,
                              int newLength)
Like Arrays.copyOf(Object[], int), but exists prior to JDK 1.6.

Parameters:
original - the array to be copied
newLength - 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

dbTimeMillis

public static long dbTimeMillis()
Returns the cumulative amount of time spent accessing the database.


addDatabaseTime

public static void addDatabaseTime(long millis)
Adds to the cumulative amount of time spent accessing the database.


nonDbTimeMillis

public static long nonDbTimeMillis()
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

public static Validator createSimpleValidator(FunTable funTable)
Creates a very simple implementation of Validator. (Only useful for resolving trivial expressions.)


readFully

public static String readFully(Reader rdr,
                               int bufferSize)
                        throws IOException
Reads a Reader until it returns EOF and return the contents as a String.

Parameters:
rdr - Reader to Read.
bufferSize - size of buffer to allocate for reading.
Returns:
content of Reader as String or null if Reader was empty.
Throws:
IOException

readURL

public static String readURL(String urlStr)
                      throws IOException
Read URL and return String containing content.

Parameters:
urlStr - actually a catalog URL
Returns:
String containing content of catalog.
Throws:
MalformedURLException
IOException

readURL

public static String readURL(String urlStr,
                             Map<String,String> map)
                      throws IOException
Returns the contents of a URL, substituting tokens.

Replaces the tokens "${key}" if "key" occurs in the key-value map.

Parameters:
urlStr - URL string
map - Key/value map
Returns:
Contents of URL with tokens substituted
Throws:
MalformedURLException
IOException

readURL

public static String readURL(URL url)
                      throws IOException
Returns the contents of a URL.

Parameters:
url - URL
Returns:
Contents of URL
Throws:
IOException

readURL

public static String readURL(URL url,
                             Map<String,String> map)
                      throws IOException
Returns the contents of a URL, substituting tokens.

Replaces the tokens "${key}" if "key" occurs in the key-value map.

Parameters:
url - URL
map - Key/value map
Returns:
Contents of URL with tokens substituted
Throws:
IOException

readVirtualFile

public static InputStream readVirtualFile(String url)
                                   throws org.apache.commons.vfs.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.vfs.FileSystemException

toMap

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

Parameters:
properties - Properties
Returns:
String-to-string map

replaceProperties

public static String replaceProperties(String text,
                                       Map<String,String> env)
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 string
env - Map of key-value pairs
Returns:
String with tokens substituted

printMemory

public static String printMemory()

printMemory

public static String printMemory(String msg)

cast

public static <T> Set<T> cast(Set<?> set)
Casts a Set to a Set with a different element type.

Parameters:
set - Set
Returns:
Set of desired type

cast

public static <T> List<T> cast(List<?> list)
Casts a List to a List with a different element type.

Parameters:
list - List
Returns:
List of desired type

canCast

public 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.

Type Parameters:
T - Element type
Parameters:
collection - Collection
clazz - Target element type
Returns:
Whether all not-null elements of the collection are instances of element type

castToIterable

public static <T> Iterable<T> castToIterable(Object iterable)
Casts a collection to iterable. Under JDK 1.4, 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.

Type Parameters:
T - Element type
Parameters:
iterable - Object which ought to be iterable
Returns:
Object cast to Iterable

lookup

public static <E extends Enum<E>> E lookup(Class<E> clazz,
                                           String name)
Looks up an enumeration by name, returning null if null or not valid.

Parameters:
clazz - Enumerated type
name - Name of constant

lookup

public static <E extends Enum<E>> 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.

Parameters:
clazz - Enumerated type
name - Name of constant
defaultValue - Default value if constant is not found
Returns:
Value, or null if name is null or value does not exist

makeBigDecimalFromDouble

public static BigDecimal makeBigDecimalFromDouble(double d)
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

public static String quotePattern(String s)
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

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 for
functionName - 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

public static String convertOlap4jConnectStringToNativeMondrian(String url)
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

public static boolean isBlank(String str)
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

Get Mondrian at SourceForge.net. Fast, secure and free Open Source software downloads