edu.internet2.middleware.grouperClientExt.edu.internet2.middleware.morphString
Class MorphStringUtils

java.lang.Object
  extended by edu.internet2.middleware.grouperClientExt.edu.internet2.middleware.morphString.MorphStringUtils

public class MorphStringUtils
extends Object

ExceptionUtils from commons, and some other useful classes, used for websec in oracle and other external plugin type java programs

Version:
$Id: MorphStringUtils.java,v 1.2 2009-11-17 06:25:05 mchyzer Exp $
Author:
mchyzer

Field Summary
static String CONFIG_CACHE_DIR_NAME
          fast config cache dir name (subdir from log dir)
static String EMPTY
          The empty String "".
static String TEMP_DIR_NAME
          fast temp dir name (subdir from log dir)
 
Constructor Summary
MorphStringUtils()
           
 
Method Summary
static void addCauseMethodName(String methodName)
          Adds to the list of method names used in the search for Throwable objects.
static void assertDirExists(String path)
          make sure a directory exists, if not, create it
static String className(Object object)
          null safe classname method
static void closeQuietly(InputStream input)
          Unconditionally close an InputStream.
static void closeQuietly(OutputStream output)
          Unconditionally close an OutputStream.
static void closeQuietly(Reader input)
          Unconditionally close an Reader.
static void closeQuietly(Writer writer)
          close a writer quietly
static int collectionLength(Collection arrayList)
          Null safe arrayList length
static URL computeUrl(String resourceName, boolean canBeNull)
          compute a url of a resource
static boolean contains(String str, String searchStr)
          Checks if String contains a search String, handling null.
static void copy(InputStream input, Writer output, String encoding)
          Copy and convert bytes from an InputStream to chars on a Writer, using the specified encoding.
static int copy(Reader input, Writer output)
          Copy chars from a Reader to a Writer.
static String encodeForUrl(String string)
          encode a param that will go in a url
static boolean equals(String str1, String str2)
          Compares two Strings, returning true if they are equal.
static boolean equalsIgnoreCase(String str1, String str2)
          Compares two Strings, returning true if they are equal ignoring the case.
static String execCommand(String command)
          execute a command and return the output
static Object executeMethod(Object object, String methodName)
          call reflection on an object with no arg method
static Object executeMethod(Object object, String methodName, Class argumentType, Object argument)
          call reflection on an object with no arg method
static ClassLoader fastClassLoader()
          fast class loader
static String fileCanonicalPath(File file)
          get canonical path of file
static File fileFromResourceNameHelper(String resourceName, StringBuffer log, boolean isDebug, boolean isInfo)
          get a file name from a resource name
static Object get(Object arrayOrCollection, int index)
          Get a specific index of an array or collection (note for collections and iterating, it is more efficient to get an iterator and iterate
static Throwable getCause(Throwable throwable)
          Introspects the Throwable to obtain the cause.
static Throwable getCause(Throwable throwable, String[] methodNames)
          Introspects the Throwable to obtain the cause.
static String getFullStackTrace(Throwable throwable)
          A way to get the entire nested stack-trace of an throwable.
static Throwable getRootCause(Throwable throwable)
          Introspects the Throwable to obtain the root cause.
static String[] getRootCauseStackTrace(Throwable throwable)
          Creates a compact stack trace for the root cause of the supplied Throwable.
static List getStackFrameList(Throwable t)
          Produces a List of stack frames - the message is not included.
static String[] getStackFrames(String stackTrace)
          Returns an array where each element is a line from the argument.
static String[] getStackFrames(Throwable throwable)
          Captures the stack trace associated with the specified Throwable object, decomposing it into a list of stack frames.
static String getStackTrace(Throwable throwable)
          Gets the stack trace from a Throwable as a String.
static int getThrowableCount(Throwable throwable)
          Counts the number of Throwable objects in the exception chain.
static Throwable[] getThrowables(Throwable throwable)
          Returns the list of Throwable objects in the exception chain.
static Object growArrayOrList(Object currentArray, int newSize)
          If you want to grow an array (or shrink it) to a certain size
static boolean hasWhitespace(String str)
          Checks if the String contains any whitespace.
static int indexOf(Object[] array, Object objectToFind)
          Find the index of the given object in the array.
static int indexOf(Object[] array, Object objectToFind, int startIndex)
          Find the index of the given object in the array starting at the given index.
static int indexOfThrowable(Throwable throwable, Class clazz)
          Returns the (zero based) index of the first Throwable that matches the specified class (exactly) in the exception chain.
static int indexOfThrowable(Throwable throwable, Class clazz, int fromIndex)
          Returns the (zero based) index of the first Throwable that matches the specified type in the exception chain from a specified index.
static int indexOfType(Throwable throwable, Class type)
          Returns the (zero based) index of the first Throwable that matches the specified class or subclass in the exception chain.
static int indexOfType(Throwable throwable, Class type, int fromIndex)
          Returns the (zero based) index of the first Throwable that matches the specified type in the exception chain from a specified index.
static void initFile(File file)
          make sure parent dirs exist etc
static boolean isBlank(String str)
          Checks if a String is whitespace, empty ("") or null.
static boolean isCauseMethodName(String methodName)
          Tests if the list of method names used in the search for Throwable objects include the given name.
static boolean isEmpty(String str)
          Checks if a String is empty ("") or null.
static boolean isNestedThrowable(Throwable throwable)
          Checks whether this Throwable class can store a cause.
static boolean isNewline(char input)
          return true if newline or formfeed
static boolean isNotEmpty(String str)
          Checks if a String is not empty ("") and not null.
static boolean isThrowableNested()
          Checks if the Throwable class has a getCause method.
static boolean isWindows()
          see if we are running on windows
static Iterator iterator(Object collection)
          null safe iterator getter if the type if collection
static long lastModifiedResources(Object resourceNames)
          find the most recently modified resource
static int length(Object arrayOrCollection)
          Null safe array length or map
static File[] listFilesByExtension(File dir, String extension)
          list files with a certain extension
static List listFilesByExtensionRecursive(File dir, String extension)
          list files with a certain extension.
static File[] listFilesByPrefix(File dir, String prefix)
          list files with a certain prefix
static File[] listSubdirs(File dir)
          get the subdirs of a dir (not ..)
static void mkdirs(File dir)
          Create directories, throw exception if not possible.
static Object next(Object arrayOrCollection, Iterator iterator, int index)
          If array, get the element based on index, if Collection, get it based on iterator.
static long packInts(int first, int second)
          pack two ints into a long.
static void printRootCauseStackTrace(Throwable throwable)
          Prints a compact stack trace for the root cause of a throwable to System.err.
static void printRootCauseStackTrace(Throwable throwable, PrintStream stream)
          Prints a compact stack trace for the root cause of a throwable.
static void printRootCauseStackTrace(Throwable throwable, PrintWriter writer)
          Prints a compact stack trace for the root cause of a throwable.
static String readFileIntoString(File file)
           
static String readFileToString(File file, String encoding)
           Reads the contents of a file into a String.
static String readFromFileIfFile(String in)
          if the input is a file, read string from file.
static String readFromFileIfFile(String in, boolean disableExternalFileLookup)
          if the input is a file, read string from file.
static void removeCauseMethodName(String methodName)
          Removes from the list of method names used in the search for Throwable objects.
static void removeCommonFrames(List causeFrames, List wrapperFrames)
          Removes common frames from the cause trace given the two stack traces.
static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith)
          replace a string or strings from a string, and put the output in a string buffer.
static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith, boolean recurse)
          replace a string or strings from a string, and put the output in a string buffer
static String replace(String text, Object searchFor, Object replaceWith)
          replace a string or strings from a string, and put the output in a string buffer.
static String replace(String text, Object searchFor, Object replaceWith, boolean recurse)
          replace a string or strings from a string, and put the output in a string buffer
static String replace(String text, String repl, String with)
          Replaces all occurrences of a String within another String.
static String replace(String text, String repl, String with, int max)
          Replaces a String with another String inside a larger String, for the first max values of the search String.
static void replace(Writer outWriter, String text, Object searchFor, Object replaceWith)
          replace a string or strings from a string, and put the output in a string buffer.
static void replace(Writer outWriter, String text, Object searchFor, Object replaceWith, boolean recurse)
          replace a string or strings from a string, and put the output in a string buffer
static void saveStringIntoFile(File file, String contents)
          save a string into a file, file does not have to exist
static Object set(Object arrayOrList, int index, Object value)
          safely assign an object to a list (add if not exist)
static String specialChars(String input, boolean isToSpecialChars)
          Unsubstitute special chars from inputs (at least used for regex).
static String[] split(String str)
          Splits the provided text into an array, using whitespace as the separator.
static String[] split(String str, char separatorChar)
          Splits the provided text into an array, separator specified.
static String[] split(String str, String separatorChars)
          Splits the provided text into an array, separators specified.
static String[] split(String str, String separatorChars, int max)
          Splits the provided text into an array with a maximum length, separators specified.
static String[] splitByWholeSeparator(String str, String separator)
          Splits the provided text into an array, separator string specified.
static String[] splitByWholeSeparator(String str, String separator, int max)
          Splits the provided text into an array, separator string specified.
static String[] splitTrim(String input, String separator)
          split a string based on a separator into an array, and trim each entry (see the Commons Util StringUtils.trim for more details)
static String toString(InputStream input, String encoding)
          Get the contents of an InputStream as a String.
static String trim(String str)
          Removes control characters (char <= 32) from both ends of this String, handling null by returning null.
static String trimToEmpty(String str)
          Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null.
static String trimToNull(String str)
          Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null.
static int unpackInt(long theLong, boolean isFirst)
          take a long
static void writeStringToFile(File file, String data, String encoding)
           Writes data to a file.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Field Detail

EMPTY

public static final String EMPTY
The empty String "".

Since:
2.0
See Also:
Constant Field Values

TEMP_DIR_NAME

public static final String TEMP_DIR_NAME
fast temp dir name (subdir from log dir)

See Also:
Constant Field Values

CONFIG_CACHE_DIR_NAME

public static final String CONFIG_CACHE_DIR_NAME
fast config cache dir name (subdir from log dir)

See Also:
Constant Field Values
Constructor Detail

MorphStringUtils

public MorphStringUtils()
Method Detail

encodeForUrl

public static String encodeForUrl(String string)
encode a param that will go in a url

Parameters:
string -
Returns:
the encoded param

initFile

public static void initFile(File file)
make sure parent dirs exist etc

Parameters:
file -

closeQuietly

public static void closeQuietly(Writer writer)
close a writer quietly

Parameters:
writer -

addCauseMethodName

public static void addCauseMethodName(String methodName)

Adds to the list of method names used in the search for Throwable objects.

Parameters:
methodName - the methodName to add to the list, null and empty strings are ignored
Since:
2.0

removeCauseMethodName

public static void removeCauseMethodName(String methodName)

Removes from the list of method names used in the search for Throwable objects.

Parameters:
methodName - the methodName to remove from the list, null and empty strings are ignored
Since:
2.1

isCauseMethodName

public static boolean isCauseMethodName(String methodName)

Tests if the list of method names used in the search for Throwable objects include the given name.

Parameters:
methodName - the methodName to search in the list.
Returns:
if the list of method names used in the search for Throwable objects include the given name.
Since:
2.1

getCause

public static Throwable getCause(Throwable throwable)

Introspects the Throwable to obtain the cause.

The method searches for methods with specific names that return a Throwable object. This will pick up most wrapping exceptions, including those from JDK 1.4, and The method names can be added to using addCauseMethodName(String).

The default list searched for are:

In the absence of any such method, the object is inspected for a detail field assignable to a Throwable.

If none of the above is found, returns null.

Parameters:
throwable - the throwable to introspect for a cause, may be null
Returns:
the cause of the Throwable, null if none found or null throwable input
Since:
1.0

className

public static String className(Object object)
null safe classname method

Parameters:
object -
Returns:
the classname

executeMethod

public static Object executeMethod(Object object,
                                   String methodName)
call reflection on an object with no arg method

Parameters:
object -
methodName -
Returns:
the return of the method

executeMethod

public static Object executeMethod(Object object,
                                   String methodName,
                                   Class argumentType,
                                   Object argument)
call reflection on an object with no arg method

Parameters:
object -
methodName -
argumentType - type of the argument
argument - to the method
Returns:
the return of the method

getCause

public static Throwable getCause(Throwable throwable,
                                 String[] methodNames)

Introspects the Throwable to obtain the cause.

  1. Try known exception types.
  2. Try the supplied array of method names.
  3. Try the field 'detail'.

A null set of method names means use the default set. A null in the set of method names will be ignored.

Parameters:
throwable - the throwable to introspect for a cause, may be null
methodNames - the method names, null treated as default set
Returns:
the cause of the Throwable, null if none found or null throwable input
Since:
1.0

getRootCause

public static Throwable getRootCause(Throwable throwable)

Introspects the Throwable to obtain the root cause.

This method walks through the exception chain to the last element, "root" of the tree, using getCause(Throwable), and returns that exception.

Parameters:
throwable - the throwable to get the root cause for, may be null
Returns:
the root cause of the Throwable, null if none found or null throwable input

isThrowableNested

public static boolean isThrowableNested()

Checks if the Throwable class has a getCause method.

This is true for JDK 1.4 and above.

Returns:
true if Throwable is nestable
Since:
2.0

isNestedThrowable

public static boolean isNestedThrowable(Throwable throwable)

Checks whether this Throwable class can store a cause.

This method does not check whether it actually does store a cause.

Parameters:
throwable - the Throwable to examine, may be null
Returns:
boolean true if nested otherwise false
Since:
2.0

getThrowableCount

public static int getThrowableCount(Throwable throwable)

Counts the number of Throwable objects in the exception chain.

A throwable without cause will return 1. A throwable with one cause will return 2 and so on. A null throwable will return 0.

Parameters:
throwable - the throwable to inspect, may be null
Returns:
the count of throwables, zero if null input

getThrowables

public static Throwable[] getThrowables(Throwable throwable)

Returns the list of Throwable objects in the exception chain.

A throwable without cause will return an array containing one element - the input throwable. A throwable with one cause will return an array containing two elements. - the input throwable and the cause throwable. A null throwable will return an array size zero.

Parameters:
throwable - the throwable to inspect, may be null
Returns:
the array of throwables, never null

indexOfThrowable

public static int indexOfThrowable(Throwable throwable,
                                   Class clazz)

Returns the (zero based) index of the first Throwable that matches the specified class (exactly) in the exception chain. Subclasses of the specified class do not match - see indexOfType(Throwable, Class) for the opposite.

A null throwable returns -1. A null type returns -1. No match in the chain returns -1.

Parameters:
throwable - the throwable to inspect, may be null
clazz - the class to search for, subclasses do not match, null returns -1
Returns:
the index into the throwable chain, -1 if no match or null input

indexOfThrowable

public static int indexOfThrowable(Throwable throwable,
                                   Class clazz,
                                   int fromIndex)

Returns the (zero based) index of the first Throwable that matches the specified type in the exception chain from a specified index. Subclasses of the specified class do not match - see indexOfType(Throwable, Class, int) for the opposite.

A null throwable returns -1. A null type returns -1. No match in the chain returns -1. A negative start index is treated as zero. A start index greater than the number of throwables returns -1.

Parameters:
throwable - the throwable to inspect, may be null
clazz - the class to search for, subclasses do not match, null returns -1
fromIndex - the (zero based) index of the starting position, negative treated as zero, larger than chain size returns -1
Returns:
the index into the throwable chain, -1 if no match or null input

indexOfType

public static int indexOfType(Throwable throwable,
                              Class type)

Returns the (zero based) index of the first Throwable that matches the specified class or subclass in the exception chain. Subclasses of the specified class do match - see indexOfThrowable(Throwable, Class) for the opposite.

A null throwable returns -1. A null type returns -1. No match in the chain returns -1.

Parameters:
throwable - the throwable to inspect, may be null
type - the type to search for, subclasses match, null returns -1
Returns:
the index into the throwable chain, -1 if no match or null input
Since:
2.1

indexOfType

public static int indexOfType(Throwable throwable,
                              Class type,
                              int fromIndex)

Returns the (zero based) index of the first Throwable that matches the specified type in the exception chain from a specified index. Subclasses of the specified class do match - see indexOfThrowable(Throwable, Class) for the opposite.

A null throwable returns -1. A null type returns -1. No match in the chain returns -1. A negative start index is treated as zero. A start index greater than the number of throwables returns -1.

Parameters:
throwable - the throwable to inspect, may be null
type - the type to search for, subclasses match, null returns -1
fromIndex - the (zero based) index of the starting position, negative treated as zero, larger than chain size returns -1
Returns:
the index into the throwable chain, -1 if no match or null input
Since:
2.1

printRootCauseStackTrace

public static void printRootCauseStackTrace(Throwable throwable)

Prints a compact stack trace for the root cause of a throwable to System.err.

The compact stack trace starts with the root cause and prints stack frames up to the place where it was caught and wrapped. Then it prints the wrapped exception and continues with stack frames until the wrapper exception is caught and wrapped again, etc.

The method is equivalent to printStackTrace for throwables that don't have nested causes.

Parameters:
throwable - the throwable to output
Since:
2.0

printRootCauseStackTrace

public static void printRootCauseStackTrace(Throwable throwable,
                                            PrintStream stream)

Prints a compact stack trace for the root cause of a throwable.

The compact stack trace starts with the root cause and prints stack frames up to the place where it was caught and wrapped. Then it prints the wrapped exception and continues with stack frames until the wrapper exception is caught and wrapped again, etc.

The method is equivalent to printStackTrace for throwables that don't have nested causes.

Parameters:
throwable - the throwable to output, may be null
stream - the stream to output to, may not be null
Throws:
IllegalArgumentException - if the stream is null
Since:
2.0

printRootCauseStackTrace

public static void printRootCauseStackTrace(Throwable throwable,
                                            PrintWriter writer)

Prints a compact stack trace for the root cause of a throwable.

The compact stack trace starts with the root cause and prints stack frames up to the place where it was caught and wrapped. Then it prints the wrapped exception and continues with stack frames until the wrapper exception is caught and wrapped again, etc.

The method is equivalent to printStackTrace for throwables that don't have nested causes.

Parameters:
throwable - the throwable to output, may be null
writer - the writer to output to, may not be null
Throws:
IllegalArgumentException - if the writer is null
Since:
2.0

split

public static String[] split(String str)

Splits the provided text into an array, using whitespace as the separator. Whitespace is defined by Character.isWhitespace(char).

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.split(null)       = null
 StringUtils.split("")         = []
 StringUtils.split("abc def")  = ["abc", "def"]
 StringUtils.split("abc  def") = ["abc", "def"]
 StringUtils.split(" abc ")    = ["abc"]
 

Parameters:
str - the String to parse, may be null
Returns:
an array of parsed Strings, null if null String input

split

public static String[] split(String str,
                             char separatorChar)

Splits the provided text into an array, separator specified. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("a.b.c", '.')    = ["a", "b", "c"]
 StringUtils.split("a..b.c", '.')   = ["a", "b", "c"]
 StringUtils.split("a:b:c", '.')    = ["a:b:c"]
 StringUtils.split("a\tb\nc", null) = ["a", "b", "c"]
 StringUtils.split("a b c", ' ')    = ["a", "b", "c"]
 

Parameters:
str - the String to parse, may be null
separatorChar - the character used as the delimiter, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input
Since:
2.0

split

public static String[] split(String str,
                             String separatorChars)

Splits the provided text into an array, separators specified. This is an alternative to using StringTokenizer.

The separator is not included in the returned String array. Adjacent separators are treated as one separator. For more control over the split use the StrTokenizer class.

A null input String returns null. A null separatorChars splits on whitespace.

 StringUtils.split(null, *)         = null
 StringUtils.split("", *)           = []
 StringUtils.split("abc def", null) = ["abc", "def"]
 StringUtils.split("abc def", " ")  = ["abc", "def"]
 StringUtils.split("abc  def", " ") = ["abc", "def"]
 StringUtils.split("ab:cd:ef", ":") = ["ab", "cd", "ef"]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
Returns:
an array of parsed Strings, null if null String input

split

public static String[] split(String str,
                             String separatorChars,
                             int max)

Splits the provided text into an array with a maximum length, separators specified.

The separator is not included in the returned String array. Adjacent separators are treated as one separator.

A null input String returns null. A null separatorChars splits on whitespace.

If more than max delimited substrings are found, the last returned string includes all characters after the first max - 1 returned strings (including separator characters).

 StringUtils.split(null, *, *)            = null
 StringUtils.split("", *, *)              = []
 StringUtils.split("ab de fg", null, 0)   = ["ab", "cd", "ef"]
 StringUtils.split("ab   de fg", null, 0) = ["ab", "cd", "ef"]
 StringUtils.split("ab:cd:ef", ":", 0)    = ["ab", "cd", "ef"]
 StringUtils.split("ab:cd:ef", ":", 2)    = ["ab", "cd:ef"]
 

Parameters:
str - the String to parse, may be null
separatorChars - the characters used as the delimiters, null splits on whitespace
max - the maximum number of elements to include in the array. A zero or negative value implies no limit
Returns:
an array of parsed Strings, null if null String input

splitByWholeSeparator

public static String[] splitByWholeSeparator(String str,
                                             String separator)

Splits the provided text into an array, separator string specified.

The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.

A null input String returns null. A null separator splits on whitespace.

 StringUtils.split(null, *)            = null
 StringUtils.split("", *)              = []
 StringUtils.split("ab de fg", null)   = ["ab", "de", "fg"]
 StringUtils.split("ab   de fg", null) = ["ab", "de", "fg"]
 StringUtils.split("ab:cd:ef", ":")    = ["ab", "cd", "ef"]
 StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy")  = ["bst", "m", "sl", "bst", "m", "sl"]
 StringUtils.split("abstemiouslyaeiouyabstemiously", "aeiouy")  = ["abstemiously", "abstemiously"]
 

Parameters:
str - the String to parse, may be null
separator - String containing the String to be used as a delimiter, null splits on whitespace
Returns:
an array of parsed Strings, null if null String was input

splitByWholeSeparator

public static String[] splitByWholeSeparator(String str,
                                             String separator,
                                             int max)

Splits the provided text into an array, separator string specified. Returns a maximum of max substrings.

The separator(s) will not be included in the returned String array. Adjacent separators are treated as one separator.

A null input String returns null. A null separator splits on whitespace.

 StringUtils.splitByWholeSeparator(null, *, *)               = null
 StringUtils.splitByWholeSeparator("", *, *)                 = []
 StringUtils.splitByWholeSeparator("ab de fg", null, 0)      = ["ab", "de", "fg"]
 StringUtils.splitByWholeSeparator("ab   de fg", null, 0)    = ["ab", "de", "fg"]
 StringUtils.splitByWholeSeparator("ab:cd:ef", ":", 2)       = ["ab", "cd"]
 StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2) = ["bst", "m"]
 StringUtils.splitByWholeSeparator("abstemiouslyaeiouyabstemiously", "aeiouy", 2)  = ["abstemiously", "abstemiously"]
 

Parameters:
str - the String to parse, may be null
separator - String containing the String to be used as a delimiter, null splits on whitespace
max - the maximum number of elements to include in the returned array. A zero or negative value implies no limit.
Returns:
an array of parsed Strings, null if null String was input

splitTrim

public static String[] splitTrim(String input,
                                 String separator)
split a string based on a separator into an array, and trim each entry (see the Commons Util StringUtils.trim for more details)

Parameters:
input - is the delimited input to split and trim
separator - is what to split on
Returns:
the array of items after split and trimmed

getRootCauseStackTrace

public static String[] getRootCauseStackTrace(Throwable throwable)

Creates a compact stack trace for the root cause of the supplied Throwable.

Parameters:
throwable - the throwable to examine, may be null
Returns:
an array of stack trace frames, never null
Since:
2.0

removeCommonFrames

public static void removeCommonFrames(List causeFrames,
                                      List wrapperFrames)

Removes common frames from the cause trace given the two stack traces.

Parameters:
causeFrames - stack trace of a cause throwable
wrapperFrames - stack trace of a wrapper throwable
Throws:
IllegalArgumentException - if either argument is null
Since:
2.0

getStackTrace

public static String getStackTrace(Throwable throwable)

Gets the stack trace from a Throwable as a String.

Parameters:
throwable - the Throwable to be examined
Returns:
the stack trace as generated by the exception's printStackTrace(PrintWriter) method

getFullStackTrace

public static String getFullStackTrace(Throwable throwable)

A way to get the entire nested stack-trace of an throwable.

Parameters:
throwable - the Throwable to be examined
Returns:
the nested stack trace, with the root cause first
Since:
2.0

getStackFrames

public static String[] getStackFrames(Throwable throwable)

Captures the stack trace associated with the specified Throwable object, decomposing it into a list of stack frames.

Parameters:
throwable - the Throwable to examine, may be null
Returns:
an array of strings describing each stack frame, never null

getStackFrames

public static String[] getStackFrames(String stackTrace)

Returns an array where each element is a line from the argument.

The end of line is determined by the value of separator.

Functionality shared between the getStackFrames(Throwable) methods of this and the classes.

Parameters:
stackTrace - A stack trace String.
Returns:
an array where each element is a line from the argument.

getStackFrameList

public static List getStackFrameList(Throwable t)

Produces a List of stack frames - the message is not included.

This works in most cases - it will only fail if the exception message contains a line that starts with: "   at".

Parameters:
t - is any throwable
Returns:
List of stack frames

isNotEmpty

public static boolean isNotEmpty(String str)

Checks if a String is not empty ("") and not null.

 StringUtils.isNotEmpty(null)      = false
 StringUtils.isNotEmpty("")        = false
 StringUtils.isNotEmpty(" ")       = true
 StringUtils.isNotEmpty("bob")     = true
 StringUtils.isNotEmpty("  bob  ") = true
 

Parameters:
str - the String to check, may be null
Returns:
true if the String is not empty and not null

indexOf

public static int indexOf(Object[] array,
                          Object objectToFind)

Find the index of the given object in the array.

This method returns -1 if null array input.

Parameters:
array - the array to search through for the object, may be null
objectToFind - the object to find, may be null
Returns:
the index of the object within the array, -1 if not found or null array input

indexOf

public static int indexOf(Object[] array,
                          Object objectToFind,
                          int startIndex)

Find the index of the given object in the array starting at the given index.

This method returns -1 if null array input.

A negative startIndex is treated as zero. A startIndex larger than the array length will return -1.

Parameters:
array - the array to search through for the object, may be null
objectToFind - the object to find, may be null
startIndex - the index to start searching at
Returns:
the index of the object within the array starting at the index, -1 if not found or null array input

equals

public static boolean equals(String str1,
                             String str2)

Compares two Strings, returning true if they are equal.

nulls are handled without exceptions. Two null references are considered to be equal. The comparison is case sensitive.

 StringUtils.equals(null, null)   = true
 StringUtils.equals(null, "abc")  = false
 StringUtils.equals("abc", null)  = false
 StringUtils.equals("abc", "abc") = true
 StringUtils.equals("abc", "ABC") = false
 

Parameters:
str1 - the first String, may be null
str2 - the second String, may be null
Returns:
true if the Strings are equal, case sensitive, or both null
See Also:
String.equals(Object)

equalsIgnoreCase

public static boolean equalsIgnoreCase(String str1,
                                       String str2)

Compares two Strings, returning true if they are equal ignoring the case.

nulls are handled without exceptions. Two null references are considered equal. Comparison is case insensitive.

 StringUtils.equalsIgnoreCase(null, null)   = true
 StringUtils.equalsIgnoreCase(null, "abc")  = false
 StringUtils.equalsIgnoreCase("abc", null)  = false
 StringUtils.equalsIgnoreCase("abc", "abc") = true
 StringUtils.equalsIgnoreCase("abc", "ABC") = true
 

Parameters:
str1 - the first String, may be null
str2 - the second String, may be null
Returns:
true if the Strings are equal, case insensitive, or both null

replace

public static String replace(String text,
                             String repl,
                             String with)

Replaces all occurrences of a String within another String.

A null reference passed to this method is a no-op.

 StringUtils.replace(null, *, *)        = null
 StringUtils.replace("", *, *)          = ""
 StringUtils.replace("any", null, *)    = "any"
 StringUtils.replace("any", *, null)    = "any"
 StringUtils.replace("any", "", *)      = "any"
 StringUtils.replace("aba", "a", null)  = "aba"
 StringUtils.replace("aba", "a", "")    = "b"
 StringUtils.replace("aba", "a", "z")   = "zbz"
 

Parameters:
text - text to search and replace in, may be null
repl - the String to search for, may be null
with - the String to replace with, may be null
Returns:
the text with any replacements processed, null if null String input
See Also:
replace(String text, String repl, String with, int max)

replace

public static String replace(String text,
                             String repl,
                             String with,
                             int max)

Replaces a String with another String inside a larger String, for the first max values of the search String.

A null reference passed to this method is a no-op.

 StringUtils.replace(null, *, *, *)         = null
 StringUtils.replace("", *, *, *)           = ""
 StringUtils.replace("any", null, *, *)     = "any"
 StringUtils.replace("any", *, null, *)     = "any"
 StringUtils.replace("any", "", *, *)       = "any"
 StringUtils.replace("any", *, *, 0)        = "any"
 StringUtils.replace("abaa", "a", null, -1) = "abaa"
 StringUtils.replace("abaa", "a", "", -1)   = "b"
 StringUtils.replace("abaa", "a", "z", 0)   = "abaa"
 StringUtils.replace("abaa", "a", "z", 1)   = "zbaa"
 StringUtils.replace("abaa", "a", "z", 2)   = "zbza"
 StringUtils.replace("abaa", "a", "z", -1)  = "zbzz"
 

Parameters:
text - text to search and replace in, may be null
repl - the String to search for, may be null
with - the String to replace with, may be null
max - maximum number of values to replace, or -1 if no maximum
Returns:
the text with any replacements processed, null if null String input

isEmpty

public static boolean isEmpty(String str)

Checks if a String is empty ("") or null.

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false
 

NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().

Parameters:
str - the String to check, may be null
Returns:
true if the String is empty or null

readFileIntoString

public static String readFileIntoString(File file)
Parameters:
file - is the file to read into a string
Returns:
String

readFileToString

public static String readFileToString(File file,
                                      String encoding)
                               throws IOException

Reads the contents of a file into a String.

There is no readFileToString method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.

Parameters:
file - the file to read.
encoding - the encoding to use
Returns:
The file contents or null if read failed.
Throws:
IOException - in case of an I/O error

toString

public static String toString(InputStream input,
                              String encoding)
                       throws IOException
Get the contents of an InputStream as a String.

Parameters:
input - the InputStream to read from
encoding - The name of a supported character encoding. See the IANA Charset Registry for a list of valid encoding types.
Returns:
the requested String
Throws:
IOException - In case of an I/O problem

copy

public static void copy(InputStream input,
                        Writer output,
                        String encoding)
                 throws IOException
Copy and convert bytes from an InputStream to chars on a Writer, using the specified encoding.

Parameters:
input - the InputStream to read from
output - the Writer to write to
encoding - The name of a supported character encoding. See the IANA Charset Registry for a list of valid encoding types.
Throws:
IOException - In case of an I/O problem

copy

public static int copy(Reader input,
                       Writer output)
                throws IOException
Copy chars from a Reader to a Writer.

Parameters:
input - the Reader to read from
output - the Writer to write to
Returns:
the number of characters copied
Throws:
IOException - In case of an I/O problem

closeQuietly

public static void closeQuietly(Reader input)
Unconditionally close an Reader. Equivalent to Reader.close(), except any exceptions will be ignored.

Parameters:
input - A (possibly null) Reader

closeQuietly

public static void closeQuietly(OutputStream output)
Unconditionally close an OutputStream. Equivalent to OutputStream.close(), except any exceptions will be ignored.

Parameters:
output - A (possibly null) OutputStream

closeQuietly

public static void closeQuietly(InputStream input)
Unconditionally close an InputStream. Equivalent to InputStream.close(), except any exceptions will be ignored.

Parameters:
input - A (possibly null) InputStream

trim

public static String trim(String str)

Removes control characters (char <= 32) from both ends of this String, handling null by returning null.

The String is trimmed using String.trim(). Trim removes start and end characters <= 32. To strip whitespace use strip(String)

To trim your choice of characters, use the strip(String, String) methods.

 StringUtils.trim(null)          = null
 StringUtils.trim("")            = ""
 StringUtils.trim("     ")       = ""
 StringUtils.trim("abc")         = "abc"
 StringUtils.trim("    abc    ") = "abc"
 

Parameters:
str - the String to be trimmed, may be null
Returns:
the trimmed string, null if null String input

trimToNull

public static String trimToNull(String str)

Removes control characters (char <= 32) from both ends of this String returning null if the String is empty ("") after the trim or if it is null.

The String is trimmed using String.trim(). Trim removes start and end characters <= 32. To strip whitespace use stripToNull.

 StringUtils.trimToNull(null)          = null
 StringUtils.trimToNull("")            = null
 StringUtils.trimToNull("     ")       = null
 StringUtils.trimToNull("abc")         = "abc"
 StringUtils.trimToNull("    abc    ") = "abc"
 

Parameters:
str - the String to be trimmed, may be null
Returns:
the trimmed String, null if only chars <= 32, empty or null String input
Since:
2.0

trimToEmpty

public static String trimToEmpty(String str)

Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null.

The String is trimmed using trim(). Trim removes start and end characters <= 32. To strip whitespace use stripToEmpty(String).

 StringUtils.trimToEmpty(null)          = ""
 StringUtils.trimToEmpty("")            = ""
 StringUtils.trimToEmpty("     ")       = ""
 StringUtils.trimToEmpty("abc")         = "abc"
 StringUtils.trimToEmpty("    abc    ") = "abc"
 

Parameters:
str - the String to be trimmed, may be null
Returns:
the trimmed String, or an empty String if null input
Since:
2.0

hasWhitespace

public static boolean hasWhitespace(String str)

Checks if the String contains any whitespace.

null will return false. An empty String ("") will return false.

 StringUtils.isWhitespace(null)   = false
 StringUtils.isWhitespace("")     = false
 StringUtils.isWhitespace("  ")   = true
 StringUtils.isWhitespace("abc")  = false
 StringUtils.isWhitespace("ab 2c") = true
 StringUtils.isWhitespace("ab-c") = false
 

Parameters:
str - the String to check, may be null
Returns:
true if contains any whitespace, and is non-null

contains

public static boolean contains(String str,
                               String searchStr)

Checks if String contains a search String, handling null. This method uses indexOf(int).

A null String will return false.

 StringUtils.contains(null, *)     = false
 StringUtils.contains(*, null)     = false
 StringUtils.contains("", "")      = true
 StringUtils.contains("abc", "")   = true
 StringUtils.contains("abc", "a")  = true
 StringUtils.contains("abc", "z")  = false
 

Parameters:
str - the String to check, may be null
searchStr - the String to find, may be null
Returns:
true if the String contains the search String, false if not or null string input
Since:
2.0

next

public static Object next(Object arrayOrCollection,
                          Iterator iterator,
                          int index)
If array, get the element based on index, if Collection, get it based on iterator.

Parameters:
arrayOrCollection -
iterator -
index -
Returns:
the object

iterator

public static Iterator iterator(Object collection)
null safe iterator getter if the type if collection

Parameters:
collection -
Returns:
the iterator

length

public static int length(Object arrayOrCollection)
Null safe array length or map

Parameters:
arrayOrCollection -
Returns:
the length of the array (0 for null)

lastModifiedResources

public static long lastModifiedResources(Object resourceNames)
find the most recently modified resource

Parameters:
resourceNames - resource name, or array or list
Returns:
the most recently modified value, or 0 if cant find any or all

fileFromResourceNameHelper

public static File fileFromResourceNameHelper(String resourceName,
                                              StringBuffer log,
                                              boolean isDebug,
                                              boolean isInfo)
get a file name from a resource name

Parameters:
resourceName - is the classpath location
log -
isDebug -
isInfo -
Returns:
the file path on the system

fastClassLoader

public static ClassLoader fastClassLoader()
fast class loader

Returns:
the class loader

computeUrl

public static URL computeUrl(String resourceName,
                             boolean canBeNull)
compute a url of a resource

Parameters:
resourceName -
canBeNull - if cant be null, throw runtime
Returns:
the URL

get

public static Object get(Object arrayOrCollection,
                         int index)
Get a specific index of an array or collection (note for collections and iterating, it is more efficient to get an iterator and iterate

Parameters:
arrayOrCollection -
index -
Returns:
the object at that index

packInts

public static long packInts(int first,
                            int second)
pack two ints into a long. Note: the first is held in the left bits, the second is held in the right bits

Parameters:
first - is first int
second - is second int
Returns:
the long which has two ints in there

replace

public static void replace(StringBuffer outBuffer,
                           String text,
                           Object searchFor,
                           Object replaceWith,
                           boolean recurse)
replace a string or strings from a string, and put the output in a string buffer

Parameters:
outBuffer - stringbuffer to write to
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with
recurse - if true then do multiple replaces (on the replacements)

replace

public static void replace(StringBuffer outBuffer,
                           String text,
                           Object searchFor,
                           Object replaceWith)
replace a string or strings from a string, and put the output in a string buffer. This does not recurse

Parameters:
outBuffer - stringbuffer to write to
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with

replace

public static void replace(Writer outWriter,
                           String text,
                           Object searchFor,
                           Object replaceWith,
                           boolean recurse)
replace a string or strings from a string, and put the output in a string buffer

Parameters:
outWriter - writer to write to
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with
recurse - if true then do multiple replaces (on the replacements)

replace

public static void replace(Writer outWriter,
                           String text,
                           Object searchFor,
                           Object replaceWith)
replace a string or strings from a string, and put the output in a string buffer. This does not recurse

Parameters:
outWriter - writer to write to
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with

replace

public static String replace(String text,
                             Object searchFor,
                             Object replaceWith,
                             boolean recurse)
replace a string or strings from a string, and put the output in a string buffer

Parameters:
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with
recurse - if true then do multiple replaces (on the replacements)
Returns:
the string

replace

public static String replace(String text,
                             Object searchFor,
                             Object replaceWith)
replace a string or strings from a string, and put the output in a string buffer. This does not recurse

Parameters:
text - string to look in
searchFor - string array to search for
replaceWith - string array to replace with
Returns:
the string

unpackInt

public static int unpackInt(long theLong,
                            boolean isFirst)
take a long

Parameters:
theLong - to unpack
isFirst - true for first, false for second
Returns:
one of the packed ints, first or second

assertDirExists

public static void assertDirExists(String path)
make sure a directory exists, if not, create it

Parameters:
path - is the local path to the directory

collectionLength

public static int collectionLength(Collection arrayList)
Null safe arrayList length

Parameters:
arrayList - is the array list to test
Returns:
the length of the arrayList (0 for null)

growArrayOrList

public static Object growArrayOrList(Object currentArray,
                                     int newSize)
If you want to grow an array (or shrink it) to a certain size

Parameters:
currentArray - is the array to grow. Can be null, will return null if so
newSize - is the new size which can be greater than or less than or equal to the old size
Returns:
the new array (typecast to the array type)

isNewline

public static boolean isNewline(char input)
return true if newline or formfeed

Parameters:
input -
Returns:
true if newline

mkdirs

public static void mkdirs(File dir)
Create directories, throw exception if not possible. This is will be ok if the directory already exists (will not delete it)

Parameters:
dir -

saveStringIntoFile

public static void saveStringIntoFile(File file,
                                      String contents)
save a string into a file, file does not have to exist

Parameters:
file - is the file to save to
contents - is the contents of the file

writeStringToFile

public static void writeStringToFile(File file,
                                     String data,
                                     String encoding)
                              throws IOException

Writes data to a file. The file will be created if it does not exist.

There is no readFileToString method without encoding parameter because the default encoding can differ between platforms and therefore results in inconsistent results.

Parameters:
file - the file to write.
data - The content to write to the file.
encoding - encoding to use
Throws:
IOException - in case of an I/O error
UnsupportedEncodingException - if the encoding is not supported by the VM

set

public static Object set(Object arrayOrList,
                         int index,
                         Object value)
safely assign an object to a list (add if not exist)

Parameters:
arrayOrList - is array or set or list (if null, make an array
index -
value -
Returns:
the arrayOrListOrSet

specialChars

public static String specialChars(String input,
                                  boolean isToSpecialChars)
Unsubstitute special chars from inputs (at least used for regex). If you change this, change the equivalent Javascript method. %28 -> ( %29 -> ) %2C -> , %3B -> ; %22 -> " %27 -> ' %25 -> % %5F -> _ %5C -> \

Parameters:
input - is the input string
isToSpecialChars - true if the output has special chars, false if not
Returns:
the string subbed with special chars

listFilesByExtension

public static File[] listFilesByExtension(File dir,
                                          String extension)
list files with a certain extension

Parameters:
dir -
extension - if this is the empty string it should list all
Returns:
the array of files

listFilesByPrefix

public static File[] listFilesByPrefix(File dir,
                                       String prefix)
list files with a certain prefix

Parameters:
dir -
prefix - if this is the empty string it should list all
Returns:
the array of files

listFilesByExtensionRecursive

public static List listFilesByExtensionRecursive(File dir,
                                                 String extension)
list files with a certain extension. Note, there cannot be more than 10000 files or exception will be throws

Parameters:
dir -
extension - if this is the empty string it should list all
Returns:
the array of files

listSubdirs

public static File[] listSubdirs(File dir)
get the subdirs of a dir (not ..)

Parameters:
dir -
Returns:
the dirs

isWindows

public static boolean isWindows()
see if we are running on windows

Returns:
true if windows

execCommand

public static String execCommand(String command)
execute a command and return the output

Parameters:
command -
Returns:
the output (end errors), and trim the output

readFromFileIfFile

public static String readFromFileIfFile(String in)
if the input is a file, read string from file. if not, or if disabled from grouper.properties, return the input

Parameters:
in -
Returns:
the result

readFromFileIfFile

public static String readFromFileIfFile(String in,
                                        boolean disableExternalFileLookup)
if the input is a file, read string from file. if not, or if disabled from grouper.properties, return the input

Parameters:
in -
disableExternalFileLookup -
Returns:
the result

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
 

Parameters:
str - the String to check, may be null
Returns:
true if the String is null, empty or whitespace
Since:
2.0

fileCanonicalPath

public static String fileCanonicalPath(File file)
get canonical path of file

Parameters:
file -
Returns:
the path


Copyright © 2012 Internet2. All Rights Reserved.