public class ConfigPropertiesCascadeCommonUtils extends Object
Modifier and Type | Class and Description |
---|---|
static class |
ConfigPropertiesCascadeCommonUtils.CommandResult
The results of executing a command.
|
Modifier and Type | Field and Description |
---|---|
static String |
DATE_FORMAT
string format of dates
|
static String |
DATE_MINUTES_SECONDS_FORMAT
format including minutes and seconds: yyyy/MM/dd HH:mm:ss
|
static String |
DATE_MINUTES_SECONDS_NO_SLASH_FORMAT
format including minutes and seconds: yyyyMMdd HH:mm:ss
|
static int |
DEFAULT_BUFFER_SIZE
The name says it all.
|
static String |
EMPTY
The empty String
"" . |
static Object[] |
EMPTY_OBJECT_ARRAY
An empty immutable
Object array. |
static String[] |
EMPTY_STRING_ARRAY
An empty immutable
String array. |
static int |
INDEX_NOT_FOUND
Represents a failed index search.
|
static String |
LOG_ERROR |
static int |
NOT_FOUND
special number when a number is not found
|
static long |
ONE_GB
The number of bytes in a gigabyte.
|
static long |
ONE_KB
The number of bytes in a kilobyte.
|
static long |
ONE_MB
The number of bytes in a megabyte.
|
static String |
TIMESTAMP_FORMAT
format on screen of config for milestone: yyyy/MM/dd HH:mm:ss.SSS
|
static String |
TIMESTAMP_NO_SLASH_FORMAT
format on screen of config for milestone: yyyyMMdd HH:mm:ss.SSS
|
Constructor and Description |
---|
ConfigPropertiesCascadeCommonUtils() |
Modifier and Type | Method and Description |
---|---|
static String |
abbreviate(String str,
int maxWidth)
Abbreviates a String using ellipses.
|
static String |
abbreviate(String str,
int offset,
int maxWidth)
Abbreviates a String using ellipses.
|
static String |
absolutePath(File file)
absolute path null safe
|
static <T> void |
addIfNotThere(Collection<T> list,
Collection<T> listToAdd)
add each element of listToAdd if it is not already in list
|
static void |
append(StringBuilder result,
String separatorIfResultNotEmpty,
String stringToAppend)
append and maybe put a separator in there
|
static String |
argAfter(String[] args,
String argBefore)
return the arg after the argBefore, or null if not there, or exception
if argBefore is not found
|
static String |
argKey(String option)
from a command line arg, get the key.
|
static Map<String,String> |
argMap(String[] args)
add an option: --whatever=val to a map of options where --whatever is key, and val is value
|
static Boolean |
argMapBoolean(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key)
get the value from the argMap
|
static boolean |
argMapBoolean(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required,
boolean defaultValue)
get the value from the argMap, throw exception if not there and required
|
static List<String> |
argMapFileList(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required)
get the list from comma separated from the argMap, throw exception if not there and required
|
static Integer |
argMapInteger(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required,
Integer defaultValue)
get the value from the argMap, throw exception if not there and required
|
static List<String> |
argMapList(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required)
get the list from comma separated from the argMap, throw exception if not there and required
|
static Set<String> |
argMapSet(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required)
get the set from comma separated from the argMap, throw exception if not there and required
|
static String |
argMapString(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key,
boolean required)
get the value from the argMap, throw exception if not there and required
|
static Timestamp |
argMapTimestamp(Map<String,String> argMap,
Map<String,String> argMapNotUsed,
String key)
get the value from the argMap, throw exception if not there and required
|
static String |
argValue(String option)
from a command line arg, get the key.
|
static void |
assertion(boolean isTrue,
String reason)
If false, throw an assertException, and give a reason
|
static void |
assignField(Class theClass,
Object invokeOn,
String fieldName,
Object dataToAssign,
boolean callOnSupers,
boolean overrideSecurity,
boolean typeCast,
Class<? extends Annotation> annotationWithValueOverride)
assign data to a field
|
static void |
assignField(Class theClass,
Object invokeOn,
String fieldName,
Object dataToAssign,
Class<? extends Annotation> annotationWithValueOverride)
assign data to a field.
|
static void |
assignField(Field field,
Object invokeOn,
Object dataToAssign,
boolean overrideSecurity,
boolean typeCast)
assign data to a field
|
static void |
assignField(Field field,
Object invokeOn,
Object dataToAssign,
boolean overrideSecurity,
boolean typeCast,
Class<? extends Annotation> annotationWithValueOverride)
assign data to a field
|
static void |
assignField(Object invokeOn,
String fieldName,
Object dataToAssign)
assign data to a field.
|
static void |
assignSetter(Object invokeOn,
String fieldName,
Object dataToAssign,
boolean typeCast)
assign data to a setter.
|
static <T> List<T> |
batchList(Collection<T> collection,
int batchSize,
int batchIndex)
retrieve a batch by 0 index.
|
static int |
batchNumberOfBatches(Collection<?> collection,
int batchSize)
If batching this is the number of batches
|
static int |
batchNumberOfBatches(int count,
int batchSize)
If batching this is the number of batches
|
static BigDecimal |
bigDecimalObjectValue(Object input)
Convert an object to a byte, allow nulls
|
static Boolean |
booleanObjectValue(Object object)
get the Boolean value for an object
|
static boolean |
booleanValue(Object object)
get the boolean value for an object, cant be null or blank
|
static boolean |
booleanValue(Object object,
boolean defaultBoolean)
get the boolean value for an object
|
static String |
byteCountToDisplaySize(long size)
Returns a human-readable version of the file size (original is in
bytes).
|
static Byte |
byteObjectValue(Object input)
Convert an object to a byte, allow nulls
|
static byte |
byteValue(Object input)
convert an object to a byte
|
static Object |
callMethod(Class theClass,
Object invokeOn,
String methodName)
helper method for calling a method with no params (could be in
superclass)
|
static Object |
callMethod(Class theClass,
Object invokeOn,
String methodName,
Object paramTypesOrArrayOrList,
Object paramsOrListOrArray)
helper method for calling a method (could be in superclass)
|
static Object |
callMethod(Class theClass,
Object invokeOn,
String methodName,
Object paramTypesOrArrayOrList,
Object paramsOrListOrArray,
boolean callOnSupers)
helper method for calling a method
|
static Object |
callMethod(Class theClass,
Object invokeOn,
String methodName,
Object paramTypesOrArrayOrList,
Object paramsOrListOrArray,
boolean callOnSupers,
boolean overrideSecurity)
helper method for calling a method
|
static Object |
callMethod(Class theClass,
String methodName)
helper method for calling a static method up the stack.
|
static Object |
callMethod(Class theClass,
String methodName,
boolean callOnSupers)
helper method for calling a static method with no params
|
static Object |
callMethod(Class theClass,
String methodName,
Object paramTypesOrArrayOrList,
Object paramsOrListOrArray)
helper method for calling a static method up the stack
|
static Object |
callMethod(Object invokeOn,
String methodName)
helper method for calling a method with no params (could be in
superclass), will override security
|
static String |
capitalize(String str)
Capitalizes a String changing the first letter to title case as
per
Character.toTitleCase(char) . |
static Character |
charObjectValue(Object input)
get the Character wrapper value for the input
|
static char |
charValue(Object input)
convert an object to a char
|
static String |
classesString(Object object)
print the simple names of a list of classes
|
static ClassLoader |
classLoader()
fast class loader
|
static String |
className(Object object)
null safe classname method, gets the unenhanced name
|
static String |
classNameCollection(Object object)
null safe classname method, max out at 20
|
static <T> T |
clone(T object,
Set<String> fieldsToClone)
clone an object, assign primitives, Strings, maps of string attributes.
|
static <T> void |
cloneFields(T object,
T result,
Set<String> fieldsToClone)
clone an object, assign primitives, Strings, maps of string attributes.
|
static <T> T |
cloneValue(T value)
helper method to clone the value of a field.
|
static void |
closeQuietly(Connection connection)
close a connection null safe and dont throw exception
|
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(ResultSet resultSet)
close a resultSet null safe and dont throw exception
|
static void |
closeQuietly(Statement statement)
close a statement null safe and dont throw exception
|
static void |
closeQuietly(Writer writer)
close a writer quietly
|
static Set<String> |
compareObjectFields(Object first,
Object second,
Set<String> fieldsToCompare,
String mapPrefix)
compare two objects, compare primitives, Strings, maps of string attributes.
|
static URL |
computeUrl(String resourceName,
boolean canBeNull)
compute a url of a resource
|
static <T> T |
construct(Class<T> theClass,
Class[] types,
Object[] args)
construct an instance by reflection
|
static boolean |
contains(Object[] array,
Object objectToFind)
Checks if the object is in the given array.
|
static boolean |
contains(String str,
char searchChar)
Checks if String contains a search character, handling
null . |
static boolean |
contains(String str,
String searchStr)
Checks if String contains a search String, handling
null . |
static String |
convertLongToChar(long theLong)
this method takes a long (less than 62) and converts it to a 1 character
string (a-z, A-Z, 0-9)
|
static String |
convertLongToCharSmall(long theLong)
this method takes a long (less than 36) and converts it to a 1 character
string (A-Z, 0-9)
|
static String |
convertLongToString(long theLong)
convert a long to a string by converting it to base 62 (26 lower, 26 upper,
10 digits)
|
static String |
convertLongToStringSmall(long theLong)
convert a long to a string by converting it to base 36 (26 upper, 10
digits)
|
static void |
convertToRuntimeException(Exception e)
convert an exception to a runtime exception
|
static void |
copy(File fromFile,
File toFile)
copy a file to a new file
|
static int |
copy(InputStream input,
OutputStream output)
Copy bytes from an
InputStream to an
OutputStream . |
static void |
copy(InputStream input,
Writer output)
Copy bytes from an
InputStream to chars on a
Writer using the default character encoding of the platform. |
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 long |
copyLarge(InputStream input,
OutputStream output)
Copy bytes from a large (over 2GB)
InputStream to an
OutputStream . |
static void |
createParentDirectories(File file)
Create the parent directories for a file if they do not already exist
|
static String |
dateToString(Date date)
convert a date to a string using the standard web service pattern
yyyy/MM/dd HH:mm:ss.SSS Note that HH is 0-23
|
static Date |
dateValue(Object inputObject)
Convert an object to a java.util.Date.
|
static String |
defaultIfBlank(String string,
String defaultStringIfBlank)
return the string or the other if the first is blank
|
static String |
defaultIfEmpty(String str,
String defaultStr)
Returns either the passed in String, or if the String is
empty or
null , the value of defaultStr . |
static <T> T |
defaultIfNull(T theValue,
T defaultIfTheValueIsNull)
genericized method to see if first is null, if so then return second, else first.
|
static String |
defaultString(String str)
Returns either the passed in String,
or if the String is
null , an empty String (""). |
static String |
defaultString(String str,
String defaultStr)
Returns either the passed in String, or if the String is
null , the value of defaultStr . |
static void |
deleteCreateFile(File file)
delete and create a new file.
|
static void |
deleteFile(File file)
Delete a file, throw exception if cannot
|
static void |
deleteRecursiveDirectory(String dirName)
clear out all files recursively in a directory, including the directory
itself
|
static Double |
doubleObjectValue(Object input,
boolean allowNullBlank)
get the Double value of an object
|
static double |
doubleValue(Object input)
get the double value of an object
|
static double |
doubleValueNoError(Object input)
get the double value of an object, do not throw an
exception if there is an
error
|
static <E extends Enum<?>> |
enumValueOfIgnoreCase(Class<E> theEnumClass,
String string,
boolean exceptionOnNotFound)
do a case-insensitive matching
|
static boolean |
equals(Object object1,
Object object2)
Compares two objects for equality, where either one or both
objects may be
null . |
static boolean |
equals(String first,
String second)
null safe string compare
|
static boolean |
equalsIgnoreCase(String str1,
String str2)
equalsignorecase
|
static String |
escapeUrlDecode(String string)
unescape url chars (e.g.
|
static String |
escapeUrlEncode(String string)
escape url chars (e.g.
|
static void |
execCommand(String command)
This will execute a command, and split spaces for args (might not be what
you want if you are using quotes)
|
static ConfigPropertiesCascadeCommonUtils.CommandResult |
execCommand(String[] arguments)
This will execute a command (with args).
|
static ConfigPropertiesCascadeCommonUtils.CommandResult |
execCommand(String[] arguments,
boolean exceptionOnExitValueNeZero)
This will execute a command (with args).
|
static String |
extensionFromName(String name)
get the extension from name.
|
static Field |
field(Class theClass,
String fieldName,
boolean callOnSupers,
boolean throwExceptionIfNotFound)
get a field object for a class, potentially in superclasses
|
static Set<String> |
fieldNames(Class theClass,
Class fieldType,
boolean includeStaticFields)
return a set of Strings for a class and type.
|
static Set<String> |
fieldNames(Class theClass,
Class superclassToStopAt,
Class<?> fieldType,
boolean includeSuperclassToStopAt,
boolean includeStaticFields,
boolean includeFinalFields)
get all field names from a class, including superclasses (if specified)
|
static Set<String> |
fieldNames(Class theClass,
Class superclassToStopAt,
Class<?> fieldType,
boolean includeSuperclassToStopAt,
boolean includeStaticFields,
boolean includeFinalFields,
Class<? extends Annotation> markerAnnotationToIngore)
get all field names from a class, including superclasses (if specified).
|
static Set<String> |
fieldNames(Class theClass,
Class superclassToStopAt,
Class<? extends Annotation> markerAnnotationToIngore)
get all field names from a class, including superclasses (if specified)
(up to and including the specified superclass).
|
static Set<Field> |
fields(Class theClass,
Class superclassToStopAt,
Class<? extends Annotation> markerAnnotation,
boolean includeAnnotation)
get all fields from a class, including superclasses (if specified) (up to
and including the specified superclass).
|
static Set<Field> |
fields(Class theClass,
Class superclassToStopAt,
Class fieldType,
boolean includeSuperclassToStopAt,
boolean includeStaticFields,
boolean includeFinalFields,
Class<? extends Annotation> markerAnnotation,
boolean includeAnnotation)
get all fields from a class, including superclasses (if specified)
|
static Object |
fieldValue(Class theClass,
Object invokeOn,
String fieldName,
boolean callOnSupers,
boolean overrideSecurity)
find out a field value
|
static Object |
fieldValue(Field field,
Object invokeOn)
get the value of a field, override security if needbe
|
static Object |
fieldValue(Field field,
Object invokeOn,
boolean overrideSecurity)
get the value of a field
|
static Object |
fieldValue(Object invokeOn,
String fieldName)
find out a field value (invoke on supers, override security)
|
static String |
fileCanonicalPath(File file)
get canonical path of file
|
static File |
fileFromResourceName(String resourceName)
get a file name from a resource name
|
static InputStream |
fileOrClasspathInputstream(String typeAndLocation,
String logHint)
file or classpath location
|
static Float |
floatObjectValue(Object input,
boolean allowNullBlank)
get the Float value of an object
|
static float |
floatValue(Object input)
get the float value of an object
|
static float |
floatValueNoError(Object input)
get the float value of an object, do not throw an exception if there is an
error
|
static Class |
forName(String origClassName)
Returns the class object.
|
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 Method |
getter(Class theClass,
String fieldName,
boolean callOnSupers,
boolean throwExceptionIfNotFound)
get a getter method object for a class, potentially in superclasses
|
static Method |
getterHelper(Class theClass,
String fieldName,
String getterName,
boolean callOnSupers,
boolean throwExceptionIfNotFound)
get a setter method object for a class, potentially in superclasses
|
static String |
getterNameFromPropertyName(String propertyName)
generate getBb from bb
|
static Set<Method> |
getters(Class theClass,
Class superclassToStopAt,
Class<? extends Annotation> markerAnnotation,
Boolean includeAnnotation)
get all getters from a class, including superclasses (if specified) (up to and including the specified superclass).
|
static Throwable[] |
getThrowables(Throwable throwable)
Returns the list of
Throwable objects in the
exception chain. |
static boolean |
hasOption(int options,
int option)
see if options have a specific option by int bits
|
static String |
hostname()
get the hostname of this machine
|
static char |
incrementChar(char theChar)
increment a character (A-Z then 0-9)
|
static char[] |
incrementStringInt(char[] string)
Increment a string with A-Z and 0-9 (no lower case so case insensitive apps
like windows IE will still work)
|
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 boolean |
injectInException(Throwable t,
String message)
If we can, inject this into the exception, else return false
|
static Integer |
intObjectValue(Object input,
boolean allowNullBlank)
get the Integer value of an object
|
static int |
intValue(Object input)
convert an object to a int
|
static int |
intValue(Object input,
int valueIfNull)
convert an object to a int
|
static int |
intValueNoError(Object input)
get the int value of an object, do not throw an exception if there is an
error
|
static Object |
invokeMethod(Method method,
Object invokeOn)
Safely invoke a reflection method that takes no args
|
static Object |
invokeMethod(Method method,
Object invokeOn,
Object paramsOrListOrArray)
Safely invoke a reflection method
|
static boolean |
isAscii(char input)
is ascii char
|
static boolean |
isBlank(Object input)
See if the input is null or if string, if it is empty or blank (whitespace)
|
static boolean |
isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
|
static boolean |
isEmpty(String str)
Checks if a String is empty ("") or null.
|
static boolean |
isGetter(Method method)
if the method name starts with get, and takes no args, and returns something,
then getter
|
static boolean |
isNestedThrowable(Throwable throwable)
Checks whether this
Throwable class can store a cause. |
static boolean |
isNotBlank(String str) |
static boolean |
isScalar(Class<?> type)
see if a class is a scalar (not bean, not array or list, etc)
|
static boolean |
isSetter(Method method)
if the method name starts with get, and takes no args, and returns something,
then getter
|
static boolean |
isThrowableNested()
Checks if the Throwable class has a
getCause method. |
static Iterator |
iterator(Object collection)
null safe iterator getter if the type if collection
|
static File |
jarFile(Class sampleClass)
get a jar file from a sample class
|
static String |
join(Iterator iterator,
char separator)
Joins the elements of the provided
Iterator into
a single String containing the provided elements. |
static String |
join(Iterator iterator,
String separator)
Joins the elements of the provided
Iterator into
a single String containing the provided elements. |
static String |
join(Object[] array)
Joins the elements of the provided array into a single String
containing the provided list of elements.
|
static String |
join(Object[] array,
char separator)
Joins the elements of the provided array into a single String
containing the provided list of elements.
|
static String |
join(Object[] array,
String separator)
Joins the elements of the provided array into a single String
containing the provided list of elements.
|
static String |
leftPad(String str,
int size)
Left pad a String with spaces (' ').
|
static String |
leftPad(String str,
int size,
char padChar)
Left pad a String with a specified character.
|
static String |
leftPad(String str,
int size,
String padStr)
Left pad a String with a specified String.
|
static int |
length(Object arrayOrCollection)
Null safe array length or map
|
static int |
lengthAscii(String input)
find the length of ascii chars (non ascii are counted as two)
|
static Long |
longObjectValue(Object input,
boolean allowNullBlank)
get the Long value of an object
|
static long |
longValue(Object input)
convert an object to a long
|
static long |
longValue(Object input,
long valueIfNull)
convert an object to a long
|
static long |
longValueNoError(Object input)
get the long value of an object, do not throw an exception if there is an
error
|
static <K,V> void |
mapDifferences(Map<K,V> first,
Map<K,V> second,
Set<K> differences,
String prefix)
see if two maps are the equivalent (based on number of entries,
and the equals() method of the keys and values)
|
static <K,V> boolean |
mapEquals(Map<K,V> first,
Map<K,V> second)
see if two maps are the equivalent (based on number of entries,
and the equals() method of the keys and values)
|
static String |
mapToString(Map map)
convert a set to a string (comma separate)
|
static String |
MapToString(Map map)
Deprecated.
use mapToString(map)
|
static Method |
method(Class<?> theClass,
String methodName,
Object paramTypesOrArrayOrList,
Class<?> superclassToStopAt,
boolean includeSuperclassToStopAt,
boolean isStaticOrInstance,
Class<? extends Annotation> markerAnnotation,
boolean includeAnnotation)
get the set of methods
|
static Set<String> |
methodNames(Class<?> theClass,
Class<?> superclassToStopAt,
boolean includeSuperclassToStopAt,
boolean includeStaticMethods)
simple method to get method names
|
static void |
methodsHelper(Class<?> theClass,
Class<?> superclassToStopAt,
boolean includeSuperclassToStopAt,
boolean includeStaticMethods,
Class<? extends Annotation> markerAnnotation,
boolean includeAnnotation,
Set<Method> methodSet)
get the set of methods
|
static void |
mkdirs(File dir)
Create directories, throw exception if not possible.
|
static int |
monthInt(String mon)
convert a month string to an int (1 indexed).
|
static File |
newFileUniqueName(String parentDirName,
String namePrefix,
String nameSuffix,
boolean createFile)
make a new file in the name prefix dir.
|
static <T> T |
newInstance(Class<T> theClass)
Construct a class
|
static <T> T |
newInstance(Class<T> theClass,
boolean allowPrivateConstructor)
Construct a class
|
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 <T> List<T> |
nonNull(List<T> list)
make sure a list is non null.
|
static <K,V> Map<K,V> |
nonNull(Map<K,V> map)
make sure it is non null, if null, then give new map
|
static <T> Set<T> |
nonNull(Set<T> set)
make sure a list is non null.
|
static <T> T[] |
nonNull(T[] array,
Class<?> theClass)
make sure a array is non null.
|
static boolean |
nullOrBlank(Object object)
is an object null or blank
|
static String |
oracleStandardNameFromJava(String javaName)
get the oracle underscore name e.g.
|
static long |
packInts(int first,
int second)
pack two ints into a long.
|
static String |
parentStemNameFromName(String name)
get the parent stem name from name.
|
static String |
prefixOrSuffix(String startString,
String separator,
boolean isPrefix)
get the prefix or suffix of a string based on a separator
|
static void |
propertiesCacheClear()
clear properties cache (e.g.
|
static Properties |
propertiesFromFile(File file)
read properties from file
|
static Properties |
propertiesFromResourceName(String resourceName)
read properties from a resource, dont modify the properties returned since they are cached
|
static Properties |
propertiesFromResourceName(String resourceName,
boolean useCache,
boolean exceptionIfNotExist,
Class<?> classInJar,
StringBuilder callingLog)
read properties from a resource, dont modify the properties returned since they are cached
|
static Map<String,String> |
propertiesThreadLocalOverrideMap(String propertiesFileName)
override map for properties in thread local to be used in a web server or the like, based on property file name
|
static String |
propertiesValue(Properties properties,
Map<String,String> overrideMap,
Map<String,String> overrideMap2,
String key)
get a value (trimmed to e) from a property file
|
static String |
propertiesValue(Properties properties,
Map<String,String> overrideMap,
String key)
get a value (trimmed to e) from a property file
|
static String |
propertiesValue(Properties properties,
String key)
get a value (trimmed to e) from a property file
|
static String |
propertiesValue(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String propertyName,
boolean required)
get a boolean property, or the default if cant find.
|
static boolean |
propertiesValueBoolean(Properties properties,
Map<String,String> overrideMap,
Map<String,String> overrideMap2,
String propertyName,
boolean defaultValue)
get a boolean property, or the default if cant find
|
static boolean |
propertiesValueBoolean(Properties properties,
Map<String,String> overrideMap,
String propertyName,
boolean defaultValue)
get a boolean property, or the default if cant find
|
static boolean |
propertiesValueBoolean(Properties properties,
String propertyName,
boolean defaultValue)
get a boolean property, or the default if cant find
|
static boolean |
propertiesValueBoolean(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String propertyName,
boolean defaultValue,
boolean required)
get a boolean property, or the default if cant find.
|
static int |
propertiesValueInt(Properties properties,
Map<String,String> overrideMap,
Map<String,String> overrideMap2,
String propertyName,
int defaultValue)
get a int property, or the default if cant find
|
static int |
propertiesValueInt(Properties properties,
Map<String,String> overrideMap,
String propertyName,
int defaultValue)
get a int property, or the default if cant find
|
static int |
propertiesValueInt(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String propertyName,
int defaultValue,
boolean required)
get an int property, or the default if cant find.
|
static String |
propertyName(Method method)
If this is a getter or setter, then get the property name
|
static Class |
propertyType(Class theClass,
String propertyName)
use reflection to get a property type based on getter or setter or field
|
static boolean |
propertyValidateValueBoolean(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String key,
boolean required,
boolean exceptionOnError)
make sure a value is boolean in properties
|
static boolean |
propertyValidateValueClass(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String key,
Class<?> classType,
boolean required,
boolean exceptionOnError)
make sure a property is a class of a certain type
|
static boolean |
propertyValidateValueInt(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String key,
boolean required,
boolean exceptionOnError)
make sure a value is int in properties
|
static boolean |
propertyValidateValueRequired(String resourceName,
Properties properties,
Map<String,String> overrideMap,
String key,
boolean exceptionOnError)
make sure a value exists in properties
|
static Object |
propertyValue(Object object,
String property)
this assumes the property exists, and is a simple property
|
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,
boolean disableExternalFileLookup)
if the input is a file, read string from file.
|
static String |
readResourceIntoString(String resourceName,
boolean allowNull) |
static String |
readResourceIntoString(String resourceName,
Class<?> classInJar)
read resource into string
|
static Object |
remove(Object arrayOrCollection,
int index)
Remove the iterator or index
|
static Object |
remove(Object arrayOrCollection,
Iterator iterator,
int index)
Remove the iterator or index
|
static void |
renameTo(File fromFile,
File toFile)
rename a file to another file and throw runtime exception if not ok
|
static String |
repeat(String str,
int repeat)
Repeat a String
repeat times to form a
new String. |
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,
Object searchFor,
Object replaceWith,
boolean recurse,
boolean removeIfFound)
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 String |
replaceWhitespaceWithSpace(String input)
replace all whitespace with space
|
static ExecutorService |
retrieveExecutorService() |
static String |
retrievePasswordFromStdin(boolean dontMask,
String prompt)
retrieve a password from stdin
|
static char[] |
retrievePasswordFromStdin(InputStream in,
String prompt) |
static String |
rightPad(String str,
int size)
Right pad a String with spaces (' ').
|
static String |
rightPad(String str,
int size,
char padChar)
Right pad a String with a specified character.
|
static String |
rightPad(String str,
int size,
String padStr)
Right pad a String with a specified String.
|
static void |
rollbackQuietly(Connection connection)
rollback a connection quietly
|
static void |
saveStringIntoFile(File file,
String contents)
save a string into a file, file does not have to exist
|
static boolean |
saveStringIntoFile(File file,
String contents,
boolean onlyIfDifferentContents,
boolean ignoreWhitespace)
save a string into a file, file does not have to exist
|
static void |
serializeObjectToFile(Serializable object,
File file)
serialize an object to a file (create parent dir if necessary)
|
static Method |
setter(Class theClass,
String fieldName,
boolean callOnSupers,
boolean throwExceptionIfNotFound)
get a setter method object for a class, potentially in superclasses
|
static Method |
setterHelper(Class theClass,
String fieldName,
String setterName,
boolean callOnSupers,
boolean throwExceptionIfNotFound)
get a setter method object for a class, potentially in superclasses
|
static String |
setterNameFromPropertyName(String propertyName)
generate setBb from bb
|
static Set<Method> |
setters(Class theClass,
Class superclassToStopAt,
Class<?> fieldType,
boolean includeSuperclassToStopAt,
Class<? extends Annotation> markerAnnotation,
boolean includeAnnotation)
get all setters from a class, including superclasses (if specified)
|
static String |
setToString(Set set)
convert a set to a string (comma separate)
|
static Short |
shortObjectValue(Object input)
get the Short value of an object.
|
static short |
shortValue(Object input)
convert an object to a short
|
static void |
sleep(long millis)
sleep, if interrupted, throw runtime
|
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[] |
splitPreserveAllTokens(String str)
Splits the provided text into an array, using whitespace as the
separator, preserving all tokens, including empty tokens created by
adjacent separators.
|
static String[] |
splitPreserveAllTokens(String str,
char separatorChar)
Splits the provided text into an array, separator specified,
preserving all tokens, including empty tokens created by adjacent
separators.
|
static String[] |
splitPreserveAllTokens(String str,
String separatorChars)
Splits the provided text into an array, separators specified,
preserving all tokens, including empty tokens created by adjacent
separators.
|
static String[] |
splitPreserveAllTokens(String str,
String separatorChars,
int max)
Splits the provided text into an array with a maximum length,
separators specified, preserving all tokens, including empty tokens
created by adjacent separators.
|
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 trim() for more details)
|
static String[] |
splitTrim(String input,
String separator,
boolean treatAdjacentSeparatorsAsOne)
split a string based on a separator into an array, and trim each entry (see
the Commons Util trim() for more details)
|
static List<String> |
splitTrimToList(String input,
String separator)
split a string based on a separator into an array, and trim each entry (see
the Commons Util trim() for more details)
|
static Date |
stringToDate(String dateString)
convert a string to a date using the standard web service pattern Note
that HH is 0-23
|
static Date |
stringToDate2(String input)
take as input:
yyyy/mm/dd
yyyy-mm-dd
dd-mon-yyyy
yyyy/mm/dd hh:mm:ss
dd-mon-yyyy hh:mm:ss
yyyy/mm/dd hh:mm:ss.SSS
dd-mon-yyyy hh:mm:ss.SSS
|
static Timestamp |
stringToTimestamp(String input)
convert a string to timestamp based on the following formats:
yyyyMMdd
yyyy/MM/dd HH:mm:ss
yyyy/MM/dd HH:mm:ss.SSS
yyyy/MM/dd HH:mm:ss.SSSSSS
|
static String |
stringValue(Date date)
convert a date to the standard string yyyymmdd
|
static String |
stringValue(Object input)
convert an object to a string
|
static String |
stripEnd(String str,
String stripChars)
Strips any of a set of characters from the end of a String.
|
static String |
stripLastSlashIfExists(String input)
strip the last slash (/ or \) from a string if it exists
|
static String |
stripStart(String str,
String stripChars)
Strips any of a set of characters from the start of a String.
|
static String |
substituteCommonVars(String string)
substitute common vars like $space$ and $newline$
|
static String |
substringAfter(String str,
String separator)
Gets the substring after the first occurrence of a separator.
|
static String |
substringAfterLast(String str,
String separator)
Gets the substring after the last occurrence of a separator.
|
static String |
substringBefore(String str,
String separator)
Gets the substring before the first occurrence of a separator.
|
static String |
substringBeforeLast(String str,
String separator)
Gets the substring before the last occurrence of a separator.
|
static String |
suffixAfterChar(String input,
char theChar)
return the suffix after a char.
|
static String |
timestampToString(Date timestamp)
Convert a timestamp into a string: yyyy/MM/dd HH:mm:ss.SSS
|
static <T> T[] |
toArray(Collection collection,
Class<T> theClass)
convert a list into an array of type of theClass
|
static Object |
toArray(Object objectOrArrayOrCollection)
Convert a list to an array with the type of the first element e.g.
|
static <T> List<T> |
toList(T... objects)
return a list of objects from varargs.
|
static List<Class<?>> |
toListClasses(Class<?>... classes)
convert classes to a list
|
static <T> Set<T> |
toSet(T... objects)
return a set of objects from varargs.
|
static Date |
toSqlDate(Date date)
null safe convert from util date to sql date
|
static String |
toString(InputStream input,
String encoding)
Get the contents of an
InputStream as a String. |
static String |
toStringForLog(Object object)
print out various types of objects
|
static String |
toStringForLog(Object object,
int maxChars)
print out various types of objects
|
static String |
toStringSafe(Object object)
fail safe toString for Exception blocks, and include the stack
if there is a problem with toString()
|
static Timestamp |
toTimestamp(Object input)
Convert a string or object to a timestamp (could be string, date, timestamp, etc)
yyyymmdd
or
yyyy/MM/dd HH:mm:ss
or
yyyy/MM/dd HH:mm:ss.SSS
or
yyyy/MM/dd HH:mm:ss.SSSSSS
|
static String |
trim(String str)
trim whitespace from string
|
static String |
trimToEmpty(String str)
trim to empty, convert null to empty
|
static String |
truncateAscii(String input,
int requiredLength)
find the length of ascii chars (non ascii are counted as two)
|
static <T> T |
typeCast(Object value,
Class<T> theClass)
If necessary, convert an object to another type.
|
static <T> T |
typeCast(Object value,
Class<T> theClass,
boolean convertNullToDefaultPrimitive,
boolean useNewInstanceHooks)
If necessary, convert an object to another type.
|
static String |
uniqueId()
get a unique string identifier based on the current time,
this is not globally unique, just unique for as long as this
server is running...
|
static int |
unpackInt(long theLong,
boolean isFirst)
take a long
|
static Serializable |
unserializeObjectFromFile(File file,
boolean nullIfException,
boolean deleteFileOnException)
unserialize an object from a file if it exists
|
static void |
writeStringToFile(File file,
String data,
String encoding)
Writes data to a file.
|
public static final String LOG_ERROR
public static final long ONE_KB
public static final long ONE_MB
public static final long ONE_GB
public static final String DATE_FORMAT
public static final String DATE_MINUTES_SECONDS_FORMAT
public static final String DATE_MINUTES_SECONDS_NO_SLASH_FORMAT
public static final String TIMESTAMP_FORMAT
public static final String TIMESTAMP_NO_SLASH_FORMAT
public static final int NOT_FOUND
public static final int DEFAULT_BUFFER_SIZE
public static final String[] EMPTY_STRING_ARRAY
String
array.public static final Object[] EMPTY_OBJECT_ARRAY
Object
array.public static final String EMPTY
""
.public static final int INDEX_NOT_FOUND
public static String argAfter(String[] args, String argBefore)
args
- argBefore
- public static void append(StringBuilder result, String separatorIfResultNotEmpty, String stringToAppend)
result
- separatorIfResultNotEmpty
- stringToAppend
- public static String byteCountToDisplaySize(long size)
size
- The number of bytes.public static boolean hasOption(int options, int option)
options
- option
- public static String fileCanonicalPath(File file)
file
- public static String suffixAfterChar(String input, char theChar)
input
- stringtheChar
- charpublic static String oracleStandardNameFromJava(String javaName)
javaName
- the java convention namepublic static <K,V> boolean mapEquals(Map<K,V> first, Map<K,V> second)
K
- V
- first
- second
- public static <K,V> void mapDifferences(Map<K,V> first, Map<K,V> second, Set<K> differences, String prefix)
K
- V
- first
- map to check diffssecond
- map to check diffsdifferences
- set of keys (with prefix) of the diffsprefix
- for the entries in the diffs (e.g. "attribute__"public static void sleep(long millis)
millis
- public static boolean injectInException(Throwable t, String message)
t
- message
- public static String uniqueId()
public static File fileFromResourceName(String resourceName)
resourceName
- is the classpath locationpublic static URL computeUrl(String resourceName, boolean canBeNull)
resourceName
- canBeNull
- if cant be null, throw runtimepublic static ClassLoader classLoader()
public static <T> T[] nonNull(T[] array, Class<?> theClass)
T
- array
- theClass
- to make array frompublic static String prefixOrSuffix(String startString, String separator, boolean isPrefix)
startString
- is the string to start withseparator
- is the separator to split onisPrefix
- if thre prefix or suffix should be returnedpublic static String extensionFromName(String name)
name
- public static Class forName(String origClassName)
Returns the class object.
origClassName
- is fully qualifiedpublic static <T> T newInstance(Class<T> theClass)
T
- template typetheClass
- public static <T> T newInstance(Class<T> theClass, boolean allowPrivateConstructor)
T
- template typetheClass
- allowPrivateConstructor
- true if should allow private constructorspublic static String parentStemNameFromName(String name)
name
- public static String defaultIfBlank(String string, String defaultStringIfBlank)
string
- defaultStringIfBlank
- public static <T> T defaultIfNull(T theValue, T defaultIfTheValueIsNull)
T
- theValue
- first inputdefaultIfTheValueIsNull
- second inputpublic static <T> void addIfNotThere(Collection<T> list, Collection<T> listToAdd)
T
- list
- to add tolistToAdd
- each element will be added to list, or null if nonepublic static String setToString(Set set)
set
- @Deprecated public static String MapToString(Map map)
map
- public static String mapToString(Map map)
map
- public static String toStringForLog(Object object)
object
- public static String toStringForLog(Object object, int maxChars)
object
- maxChars
- is the max chars that should be returned (abbreviate if longer), or -1 for any amountpublic static int batchNumberOfBatches(int count, int batchSize)
count
- is size of setbatchSize
- public static int batchNumberOfBatches(Collection<?> collection, int batchSize)
collection
- batchSize
- public static <T> List<T> batchList(Collection<T> collection, int batchSize, int batchIndex)
T
- template typecollection
- batchSize
- batchIndex
- public static String[] splitTrim(String input, String separator)
input
- is the delimited input to split and trimseparator
- is what to split onpublic static List<String> splitTrimToList(String input, String separator)
input
- is the delimited input to split and trimseparator
- is what to split onpublic static String[] splitTrim(String input, String separator, boolean treatAdjacentSeparatorsAsOne)
input
- is the delimited input to split and trimseparator
- is what to split ontreatAdjacentSeparatorsAsOne
- public static String escapeUrlEncode(String string)
string
- inputpublic static String escapeUrlDecode(String string)
string
- inputpublic static <T> List<T> nonNull(List<T> list)
T
- list
- public static <T> Set<T> nonNull(Set<T> set)
T
- set
- public static <K,V> Map<K,V> nonNull(Map<K,V> map)
K
- key of mapV
- value of mapmap
- is mappublic static <T> List<T> toList(T... objects)
T
- template type of the objectsobjects
- public static List<Class<?>> toListClasses(Class<?>... classes)
classes
- public static <T> Set<T> toSet(T... objects)
T
- template type of the objectsobjects
- public static void assertion(boolean isTrue, String reason)
isTrue
- reason
- public static void assignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, boolean callOnSupers, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticfieldName
- method name to calldataToAssign
- datacallOnSupers
- if static and method not exists, try on supersoverrideSecurity
- true to call on protected or private etc methodstypeCast
- true if we should typecastannotationWithValueOverride
- annotation with value of overridepublic static void assignField(Class theClass, Object invokeOn, String fieldName, Object dataToAssign, Class<? extends Annotation> annotationWithValueOverride)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticfieldName
- method name to calldataToAssign
- dataannotationWithValueOverride
- annotation with value of overridepublic static void assignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast)
field
- is the field to assign toinvokeOn
- to call on or null for staticdataToAssign
- dataoverrideSecurity
- true to call on protected or private etc methodstypeCast
- true if we should typecastpublic static Iterator iterator(Object collection)
collection
- public static int length(Object arrayOrCollection)
arrayOrCollection
- public static Object next(Object arrayOrCollection, Iterator iterator, int index)
arrayOrCollection
- iterator
- index
- public static Object remove(Object arrayOrCollection, int index)
arrayOrCollection
- index
- public static Object remove(Object arrayOrCollection, Iterator iterator, int index)
arrayOrCollection
- iterator
- index
- public static String classesString(Object object)
object
- public static String classNameCollection(Object object)
object
- public static String className(Object object)
object
- public static void assignField(Field field, Object invokeOn, Object dataToAssign, boolean overrideSecurity, boolean typeCast, Class<? extends Annotation> annotationWithValueOverride)
field
- is the field to assign toinvokeOn
- to call on or null for staticdataToAssign
- dataoverrideSecurity
- true to call on protected or private etc methodstypeCast
- true if we should typecastannotationWithValueOverride
- annotation with value of override, or null if nonepublic static void assignField(Object invokeOn, String fieldName, Object dataToAssign)
invokeOn
- to call on or null for staticfieldName
- method name to calldataToAssign
- datapublic static Field field(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound)
theClass
- fieldName
- callOnSupers
- true if superclasses should be looked in for the fieldthrowExceptionIfNotFound
- will throw runtime exception if not foundpublic static Set<String> fieldNames(Class theClass, Class fieldType, boolean includeStaticFields)
theClass
- fieldType
- or null for allincludeStaticFields
- public static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectfieldType
- is the type of the field to getincludeSuperclassToStopAt
- if we should include the superclassincludeStaticFields
- if include static fieldsincludeFinalFields
- if final fields should be includedpublic static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotationToIngore)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectfieldType
- is the type of the field to getincludeSuperclassToStopAt
- if we should include the superclassincludeStaticFields
- if include static fieldsincludeFinalFields
- if final fields should be includedmarkerAnnotationToIngore
- if this is not null, then if the field has this annotation,
then do not include in listpublic static Set<String> fieldNames(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotationToIngore)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectmarkerAnnotationToIngore
- if this is not null, then if the field has this annotation,
then do not include in listpublic static Set<Field> fields(Class theClass, Class superclassToStopAt, Class fieldType, boolean includeSuperclassToStopAt, boolean includeStaticFields, boolean includeFinalFields, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectfieldType
- is the type of the field to getincludeSuperclassToStopAt
- if we should include the superclassincludeStaticFields
- if include static fieldsincludeFinalFields
- if final fields should be includedmarkerAnnotation
- if this is not null, then if the field has this annotation,
then do not include in list (if includeAnnotation is false)includeAnnotation
- true if the attribute should be included if annotation is
present, false if excludepublic static Set<Field> fields(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectmarkerAnnotation
- if this is not null, then if the field has this annotation,
then do not include in list (if includeAnnotation is false)includeAnnotation
- true if the attribute should be included if annotation is
present, false if excludepublic static Set<String> compareObjectFields(Object first, Object second, Set<String> fieldsToCompare, String mapPrefix)
first
- second
- fieldsToCompare
- mapPrefix
- is the prefix for maps which are compared (e.g. attribute__)public static <T> T clone(T object, Set<String> fieldsToClone)
T
- templateobject
- fieldsToClone
- public static <T> void cloneFields(T object, T result, Set<String> fieldsToClone)
T
- templateobject
- result
- fieldsToClone
- public static <T> T cloneValue(T value)
T
- templatevalue
- public static Set<String> methodNames(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods)
theClass
- superclassToStopAt
- includeSuperclassToStopAt
- includeStaticMethods
- public static void methodsHelper(Class<?> theClass, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean includeStaticMethods, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation, Set<Method> methodSet)
theClass
- superclassToStopAt
- includeSuperclassToStopAt
- includeStaticMethods
- markerAnnotation
- includeAnnotation
- methodSet
- public static Method method(Class<?> theClass, String methodName, Object paramTypesOrArrayOrList, Class<?> superclassToStopAt, boolean includeSuperclassToStopAt, boolean isStaticOrInstance, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation)
theClass
- methodName
- paramTypesOrArrayOrList
- types of the paramssuperclassToStopAt
- includeSuperclassToStopAt
- isStaticOrInstance
- true if staticmarkerAnnotation
- includeAnnotation
- public static Object fieldValue(Class theClass, Object invokeOn, String fieldName, boolean callOnSupers, boolean overrideSecurity)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticfieldName
- method name to callcallOnSupers
- if static and method not exists, try on supersoverrideSecurity
- true to call on protected or private etc methodspublic static Object fieldValue(Field field, Object invokeOn)
field
- invokeOn
- public static Object fieldValue(Field field, Object invokeOn, boolean overrideSecurity)
field
- invokeOn
- overrideSecurity
- public static Object fieldValue(Object invokeOn, String fieldName)
invokeOn
- to call on or null for staticfieldName
- method name to callpublic static Object callMethod(Class theClass, Object invokeOn, String methodName)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticmethodName
- method name to callpublic static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticmethodName
- method name to callparamTypesOrArrayOrList
- types of the paramsparamsOrListOrArray
- datapublic static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticmethodName
- method name to callparamTypesOrArrayOrList
- types of the paramsparamsOrListOrArray
- datacallOnSupers
- if static and method not exists, try on superspublic static <T> T construct(Class<T> theClass, Class[] types, Object[] args)
T
- theClass
- args
- types
- public static Object callMethod(Class theClass, Object invokeOn, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray, boolean callOnSupers, boolean overrideSecurity)
theClass
- the class which has the methodinvokeOn
- to call on or null for staticmethodName
- method name to callparamTypesOrArrayOrList
- types of the paramsparamsOrListOrArray
- datacallOnSupers
- if static and method not exists, try on supersoverrideSecurity
- true to call on protected or private etc methodspublic static Object invokeMethod(Method method, Object invokeOn)
method
- to invokeinvokeOn
- if NO_PARAMS then will not pass in params.public static Object invokeMethod(Method method, Object invokeOn, Object paramsOrListOrArray)
method
- to invokeinvokeOn
- paramsOrListOrArray
- must be an arg. If null, will pass null.
if NO_PARAMS then will not pass in params.public static Object toArray(Object objectOrArrayOrCollection)
objectOrArrayOrCollection
- is a listpublic static <T> T[] toArray(Collection collection, Class<T> theClass)
T
- is the type of the arraycollection
- list to converttheClass
- type of array to returnpublic static Object callMethod(Class theClass, String methodName)
theClass
- the class which has the methodmethodName
- method name to callpublic static Object callMethod(Class theClass, String methodName, boolean callOnSupers)
theClass
- the class which has the methodmethodName
- method name to callcallOnSupers
- if we should try the super classes if not exists in this classpublic static Object callMethod(Class theClass, String methodName, Object paramTypesOrArrayOrList, Object paramsOrListOrArray)
theClass
- the class which has the methodmethodName
- method name to callparamTypesOrArrayOrList
- types of the paramsparamsOrListOrArray
- datapublic static Object callMethod(Object invokeOn, String methodName)
invokeOn
- instance to invoke onmethodName
- method name to call not exists in this classpublic static String replace(String text, Object searchFor, Object replaceWith)
text
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withpublic static String replace(String text, Object searchFor, Object replaceWith, boolean recurse)
text
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withrecurse
- if true then do multiple replaces (on the replacements)public static String replace(String text, Object searchFor, Object replaceWith, boolean recurse, boolean removeIfFound)
text
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withrecurse
- if true then do multiple replaces (on the replacements)removeIfFound
- true if removing from searchFor and replaceWith if foundpublic 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.
replace(null, *, *) = null replace("", *, *) = "" replace("any", null, *) = "any" replace("any", *, null) = "any" replace("any", "", *) = "any" replace("aba", "a", null) = "aba" replace("aba", "a", "") = "b" replace("aba", "a", "z") = "zbz"
text
- text to search and replace in, may be nullrepl
- the String to search for, may be nullwith
- the String to replace with, may be nullnull
if
null String inputreplace(String text, String repl, String with, int max)
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.
replace(null, *, *, *) = null replace("", *, *, *) = "" replace("any", null, *, *) = "any" replace("any", *, null, *) = "any" replace("any", "", *, *) = "any" replace("any", *, *, 0) = "any" replace("abaa", "a", null, -1) = "abaa" replace("abaa", "a", "", -1) = "b" replace("abaa", "a", "z", 0) = "abaa" replace("abaa", "a", "z", 1) = "zbaa" replace("abaa", "a", "z", 2) = "zbza" replace("abaa", "a", "z", -1) = "zbzz"
text
- text to search and replace in, may be nullrepl
- the String to search for, may be nullwith
- the String to replace with, may be nullmax
- maximum number of values to replace, or -1
if
no maximumnull
if
null String inputpublic static boolean isEmpty(String str)
Checks if a String is empty ("") or null.
isEmpty(null) = true isEmpty("") = true isEmpty(" ") = false isEmpty("bob") = false isEmpty(" bob ") = false
NOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().
str
- the String to check, may be nulltrue
if the String is empty or nullpublic static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith)
outBuffer
- stringbuffer to write totext
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withpublic static void replace(StringBuffer outBuffer, String text, Object searchFor, Object replaceWith, boolean recurse)
outBuffer
- stringbuffer to write totext
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withrecurse
- if true then do multiple replaces (on the replacements)public static void replace(Writer outWriter, String text, Object searchFor, Object replaceWith)
outWriter
- writer to write totext
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withpublic static void replace(Writer outWriter, String text, Object searchFor, Object replaceWith, boolean recurse)
outWriter
- writer to write totext
- string to look insearchFor
- string array to search forreplaceWith
- string array to replace withrecurse
- if true then do multiple replaces (on the replacements)public static long packInts(int first, int second)
first
- is first intsecond
- is second intpublic static int unpackInt(long theLong, boolean isFirst)
theLong
- to unpackisFirst
- true for first, false for secondpublic static Object get(Object arrayOrCollection, int index)
arrayOrCollection
- index
- public static String toStringSafe(Object object)
object
- public static boolean booleanValue(Object object)
object
- public static boolean booleanValue(Object object, boolean defaultBoolean)
object
- defaultBoolean
- if object is null or emptypublic static Boolean booleanObjectValue(Object object)
object
- public static boolean nullOrBlank(Object object)
object
- public static Method getter(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound)
theClass
- fieldName
- callOnSupers
- true if superclasses should be looked in for the getterthrowExceptionIfNotFound
- will throw runtime exception if not foundpublic static Method getterHelper(Class theClass, String fieldName, String getterName, boolean callOnSupers, boolean throwExceptionIfNotFound)
theClass
- fieldName
- getterName
- name of settercallOnSupers
- true if superclasses should be looked in for the setterthrowExceptionIfNotFound
- will throw runtime exception if not foundpublic static String getterNameFromPropertyName(String propertyName)
propertyName
- public static Set<Method> getters(Class theClass, Class superclassToStopAt, Class<? extends Annotation> markerAnnotation, Boolean includeAnnotation)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectmarkerAnnotation
- if this is not null, then if the field has this annotation, then do not
include in list (if includeAnnotation is false)includeAnnotation
- true if the attribute should be included if annotation is present, false if excludepublic static boolean isGetter(Method method)
method
- public static void assignSetter(Object invokeOn, String fieldName, Object dataToAssign, boolean typeCast)
invokeOn
- to call on or null for staticfieldName
- method name to calldataToAssign
- datatypeCast
- will typecast if trueRuntimeException
- if not therepublic static boolean isSetter(Method method)
method
- public static Method setter(Class theClass, String fieldName, boolean callOnSupers, boolean throwExceptionIfNotFound)
theClass
- fieldName
- callOnSupers
- true if superclasses should be looked in for the setterthrowExceptionIfNotFound
- will throw runtime exception if not foundpublic static Method setterHelper(Class theClass, String fieldName, String setterName, boolean callOnSupers, boolean throwExceptionIfNotFound)
theClass
- fieldName
- setterName
- name of settercallOnSupers
- true if superclasses should be looked in for the setterthrowExceptionIfNotFound
- will throw runtime exception if not foundpublic static String setterNameFromPropertyName(String propertyName)
propertyName
- public static Set<Method> setters(Class theClass, Class superclassToStopAt, Class<?> fieldType, boolean includeSuperclassToStopAt, Class<? extends Annotation> markerAnnotation, boolean includeAnnotation)
theClass
- to look for fields insuperclassToStopAt
- to go up to or null to go up to ObjectfieldType
- is the type of the field to getincludeSuperclassToStopAt
- if we should include the superclassmarkerAnnotation
- if this is not null, then if the field has this annotation, then do not
include in list (if includeAnnotation is false)includeAnnotation
- true if the attribute should be included if annotation is present, false if excludepublic static String propertyName(Method method)
method
- public static Class propertyType(Class theClass, String propertyName)
theClass
- propertyName
- public static <T> T typeCast(Object value, Class<T> theClass)
T
- is template typevalue
- theClass
- public static File newFileUniqueName(String parentDirName, String namePrefix, String nameSuffix, boolean createFile)
make a new file in the name prefix dir. If parent dir name is c:\temp and namePrefix is grouperDdl and nameSuffix is sql, then the file will be: c:\temp\grouperDdl_20080721_13_45_43_123.sql If the file exists, it will make a new filename, and create the empty file, and return it
parentDirName
- can be blank for current dirnamePrefix
- the part before the date partnameSuffix
- the last part of file name (can contain dot or will be the extensioncreateFile
- true to create the filepublic static Date dateValue(Object inputObject)
Convert an object to a java.util.Date. allows, dates, null, blank, yyyymmdd or yyyymmdd hh24:mm:ss or yyyy/MM/dd HH:mm:ss.SSS
inputObject
- is the String or Date to convertpublic static boolean isBlank(Object input)
input
- public static <T> T typeCast(Object value, Class<T> theClass, boolean convertNullToDefaultPrimitive, boolean useNewInstanceHooks)
T
- is the type to returnvalue
- theClass
- convertNullToDefaultPrimitive
- if the value is null, and theClass is primitive, should we
convert the null to a primitive default valueuseNewInstanceHooks
- if theClass is not recognized, then honor the string "null", "newInstance",
or get a constructor with one param, and call itpublic static boolean isScalar(Class<?> type)
type
- public static Timestamp toTimestamp(Object input)
Convert a string or object to a timestamp (could be string, date, timestamp, etc) yyyymmdd or yyyy/MM/dd HH:mm:ss or yyyy/MM/dd HH:mm:ss.SSS or yyyy/MM/dd HH:mm:ss.SSSSSS
input
- RuntimeException
- if invalid formatpublic static String stringValue(Object input)
input
- is the object to convertpublic static String timestampToString(Date timestamp)
timestamp
- public static String stringValue(Date date)
date
- public static Timestamp stringToTimestamp(String input)
convert a string to timestamp based on the following formats: yyyyMMdd yyyy/MM/dd HH:mm:ss yyyy/MM/dd HH:mm:ss.SSS yyyy/MM/dd HH:mm:ss.SSSSSS
input
- public static BigDecimal bigDecimalObjectValue(Object input)
input
- public static Byte byteObjectValue(Object input)
input
- public static byte byteValue(Object input)
input
- public static Double doubleObjectValue(Object input, boolean allowNullBlank)
input
- is a number or StringallowNullBlank
- used to default to false, if true, return null if nul inputtedpublic static double doubleValue(Object input)
input
- is a number or Stringpublic static double doubleValueNoError(Object input)
input
- is a number or Stringpublic static Float floatObjectValue(Object input, boolean allowNullBlank)
input
- is a number or StringallowNullBlank
- true if allow null or blankpublic static float floatValue(Object input)
input
- is a number or Stringpublic static float floatValueNoError(Object input)
input
- is a number or Stringpublic static Integer intObjectValue(Object input, boolean allowNullBlank)
input
- is a number or StringallowNullBlank
- true if convert null or blank to nullpublic static int intValue(Object input)
input
- public static int intValue(Object input, int valueIfNull)
input
- valueIfNull
- is if the input is null or empty, return this valuepublic static int intValueNoError(Object input)
input
- is a number or Stringpublic static Long longObjectValue(Object input, boolean allowNullBlank)
input
- is a number or StringallowNullBlank
- true if null or blank converts to nullpublic static long longValue(Object input)
input
- public static long longValue(Object input, long valueIfNull)
input
- valueIfNull
- is if the input is null or empty, return this valuepublic static long longValueNoError(Object input)
input
- is a number or Stringpublic static Short shortObjectValue(Object input)
input
- is a number or Stringpublic static short shortValue(Object input)
input
- public static Character charObjectValue(Object input)
input
- allow null, return nullpublic static char charValue(Object input)
input
- public static void createParentDirectories(File file)
file
- public static void saveStringIntoFile(File file, String contents)
file
- is the file to save tocontents
- is the contents of the filepublic static boolean saveStringIntoFile(File file, String contents, boolean onlyIfDifferentContents, boolean ignoreWhitespace)
file
- is the file to save tocontents
- is the contents of the fileonlyIfDifferentContents
- true if only saving due to different contentsignoreWhitespace
- true to ignore whitespacepublic 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.
file
- the file to write.data
- The content to write to the file.encoding
- encoding to useIOException
- in case of an I/O errorUnsupportedEncodingException
- if the encoding is not supported
by the VMpublic static String readFileIntoString(File file)
file
- is the file to read into a stringpublic static String readResourceIntoString(String resourceName, boolean allowNull)
resourceName
- is the string resource from classpath to read (e.g. grouper.properties)allowNull
- is true if its ok if the resource is null or if it is not found or blank or whatever.public static String readResourceIntoString(String resourceName, Class<?> classInJar)
resourceName
- classInJar
- if not null, then look for the jar where this file is, and look in the same dirpublic 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.
file
- the file to read.encoding
- the encoding to useIOException
- in case of an I/O errorpublic static String replaceWhitespaceWithSpace(String input)
input
- public static void closeQuietly(InputStream input)
InputStream
.
Equivalent to InputStream.close()
, except any exceptions will be ignored.input
- A (possibly null) InputStreampublic static void closeQuietly(OutputStream output)
OutputStream
.
Equivalent to OutputStream.close()
, except any exceptions will be ignored.output
- A (possibly null) OutputStreampublic static void closeQuietly(Reader input)
Reader
.
Equivalent to Reader.close()
, except any exceptions will be ignored.input
- A (possibly null) Readerpublic static void closeQuietly(Writer writer)
writer
- public static String toString(InputStream input, String encoding) throws IOException
InputStream
as a String.input
- the InputStream
to read fromencoding
- The name of a supported character encoding. See the
IANA
Charset Registry for a list of valid encoding types.String
IOException
- In case of an I/O problempublic static void copy(InputStream input, Writer output, String encoding) throws IOException
InputStream
to chars on a
Writer
, using the specified encoding.input
- the InputStream
to read fromoutput
- the Writer
to write toencoding
- The name of a supported character encoding. See the
IANA
Charset Registry for a list of valid encoding types.IOException
- In case of an I/O problempublic static int copy(Reader input, Writer output) throws IOException
Reader
to a Writer
.input
- the Reader
to read fromoutput
- the Writer
to write toIOException
- In case of an I/O problempublic static String convertLongToChar(long theLong)
theLong
- is the long (less than 62) to convert to a 1 character stringpublic static String convertLongToCharSmall(long theLong)
theLong
- is the long (less than 36) to convert to a 1 character stringpublic static String convertLongToString(long theLong)
theLong
- is the long to convertpublic static String convertLongToStringSmall(long theLong)
theLong
- is the long to convertpublic static char incrementChar(char theChar)
theChar
- public static char[] incrementStringInt(char[] string)
string
- public static Properties propertiesFromResourceName(String resourceName)
resourceName
- public static void propertiesCacheClear()
public static Properties propertiesFromFile(File file)
file
- public static Properties propertiesFromResourceName(String resourceName, boolean useCache, boolean exceptionIfNotExist, Class<?> classInJar, StringBuilder callingLog)
resourceName
- useCache
- exceptionIfNotExist
- classInJar
- if not null, then look for the jar where this file is, and look in the same dircallingLog
- public static <E extends Enum<?>> E enumValueOfIgnoreCase(Class<E> theEnumClass, String string, boolean exceptionOnNotFound) throws RuntimeException
E
- generic typetheEnumClass
- class of the enumstring
- exceptionOnNotFound
- true if exception should be thrown on not foundRuntimeException
- if there is a problempublic static Object propertyValue(Object object, String property)
object
- property
- public static String propertiesValue(Properties properties, String key)
properties
- key
- public static String propertiesValue(Properties properties, Map<String,String> overrideMap, String key)
properties
- overrideMap
- for testing, to override some properties valueskey
- public static String propertiesValue(Properties properties, Map<String,String> overrideMap, Map<String,String> overrideMap2, String key)
properties
- overrideMap
- for testing or threadlocal, to override some properties valuesoverrideMap2
- for testing, to provide some properties valueskey
- public static String substituteCommonVars(String string)
string
- public static boolean propertiesValueBoolean(Properties properties, String propertyName, boolean defaultValue)
properties
- propertyName
- defaultValue
- public static boolean propertiesValueBoolean(String resourceName, Properties properties, Map<String,String> overrideMap, String propertyName, boolean defaultValue, boolean required)
resourceName
- properties
- overrideMap
- for testing to override propertiespropertyName
- defaultValue
- required
- public static int propertiesValueInt(String resourceName, Properties properties, Map<String,String> overrideMap, String propertyName, int defaultValue, boolean required)
resourceName
- properties
- overrideMap
- for testing to override propertiespropertyName
- defaultValue
- required
- public static String propertiesValue(String resourceName, Properties properties, Map<String,String> overrideMap, String propertyName, boolean required)
resourceName
- properties
- overrideMap
- for threadlocal or testing to override propertiespropertyName
- required
- public static int propertiesValueInt(Properties properties, Map<String,String> overrideMap, String propertyName, int defaultValue)
properties
- overrideMap
- for testing to override propertiespropertyName
- defaultValue
- public static int propertiesValueInt(Properties properties, Map<String,String> overrideMap, Map<String,String> overrideMap2, String propertyName, int defaultValue)
properties
- overrideMap
- for testing to override propertiesoverrideMap2
- propertyName
- defaultValue
- public static boolean propertiesValueBoolean(Properties properties, Map<String,String> overrideMap, String propertyName, boolean defaultValue)
properties
- overrideMap
- for testing to override propertiespropertyName
- defaultValue
- public static boolean propertiesValueBoolean(Properties properties, Map<String,String> overrideMap, Map<String,String> overrideMap2, String propertyName, boolean defaultValue)
properties
- overrideMap
- for testing or threadlocal to override propertiesoverrideMap2
- for testing or threadlocal to override propertiespropertyName
- defaultValue
- public static void closeQuietly(Connection connection)
connection
- public static void closeQuietly(Statement statement)
statement
- public static void closeQuietly(ResultSet resultSet)
resultSet
- public static String hostname()
public static boolean isAscii(char input)
input
- public static int lengthAscii(String input)
input
- public static void rollbackQuietly(Connection connection)
connection
- public static String truncateAscii(String input, int requiredLength)
input
- is the string to operate onrequiredLength
- length we need the string to bepublic static String readFromFileIfFile(String in, boolean disableExternalFileLookup)
in
- disableExternalFileLookup
- public static void mkdirs(File dir)
dir
- public static boolean equals(String first, String second)
first
- second
- public static boolean isBlank(String str)
Checks if a String is whitespace, empty ("") or null.
isBlank(null) = true isBlank("") = true isBlank(" ") = true isBlank("bob") = false isBlank(" bob ") = false
str
- the String to check, may be nulltrue
if the String is null, empty or whitespacepublic static boolean isNotBlank(String str)
str
- public static String trim(String str)
str
- public static boolean equalsIgnoreCase(String str1, String str2)
str1
- str2
- public static String trimToEmpty(String str)
str
- public static String abbreviate(String str, int maxWidth)
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "Now is the time for..."
Specifically:
str
is less than maxWidth
characters
long, return it.(substring(str, 0, max-3) + "...")
.maxWidth
is less than 4
, throw an
IllegalArgumentException
.maxWidth
.StringUtils.abbreviate(null, *) = null StringUtils.abbreviate("", 4) = "" StringUtils.abbreviate("abcdefg", 6) = "abc..." StringUtils.abbreviate("abcdefg", 7) = "abcdefg" StringUtils.abbreviate("abcdefg", 8) = "abcdefg" StringUtils.abbreviate("abcdefg", 4) = "a..." StringUtils.abbreviate("abcdefg", 3) = IllegalArgumentException
str
- the String to check, may be nullmaxWidth
- maximum length of result String, must be at least 4null
if null String inputIllegalArgumentException
- if the width is too smallpublic static String abbreviate(String str, int offset, int maxWidth)
Abbreviates a String using ellipses. This will turn "Now is the time for all good men" into "...is the time for..."
Works like abbreviate(String, int)
, but allows you to specify
a "left edge" offset. Note that this left edge is not necessarily going to
be the leftmost character in the result, or the first character following the
ellipses, but it will appear somewhere in the result.
In no case will it return a String of length greater than
maxWidth
.
StringUtils.abbreviate(null, *, *) = null StringUtils.abbreviate("", 0, 4) = "" StringUtils.abbreviate("abcdefghijklmno", -1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 0, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 1, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 4, 10) = "abcdefg..." StringUtils.abbreviate("abcdefghijklmno", 5, 10) = "...fghi..." StringUtils.abbreviate("abcdefghijklmno", 6, 10) = "...ghij..." StringUtils.abbreviate("abcdefghijklmno", 8, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 10, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghijklmno", 12, 10) = "...ijklmno" StringUtils.abbreviate("abcdefghij", 0, 3) = IllegalArgumentException StringUtils.abbreviate("abcdefghij", 5, 6) = IllegalArgumentException
str
- the String to check, may be nulloffset
- left edge of source StringmaxWidth
- maximum length of result String, must be at least 4null
if null String inputIllegalArgumentException
- if the width is too smallpublic 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"]
str
- the String to parse, may be nullnull
if null String inputpublic 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"]
str
- the String to parse, may be nullseparatorChar
- the character used as the delimiter,
null
splits on whitespacenull
if null String inputpublic 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"]
str
- the String to parse, may be nullseparatorChars
- the characters used as the delimiters,
null
splits on whitespacenull
if null String inputpublic 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"]
str
- the String to parse, may be nullseparatorChars
- the characters used as the delimiters,
null
splits on whitespacemax
- the maximum number of elements to include in the
array. A zero or negative value implies no limitnull
if null String inputpublic 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"]
str
- the String to parse, may be nullseparator
- String containing the String to be used as a delimiter,
null
splits on whitespacenull
if null String was inputpublic 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"]
str
- the String to parse, may be nullseparator
- String containing the String to be used as a delimiter,
null
splits on whitespacemax
- the maximum number of elements to include in the returned
array. A zero or negative value implies no limit.null
if null String was inputpublic static String[] splitPreserveAllTokens(String str)
Splits the provided text into an array, using whitespace as the
separator, preserving all tokens, including empty tokens created by
adjacent separators. This is an alternative to using StringTokenizer.
Whitespace is defined by Character.isWhitespace(char)
.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A null
input String returns null
.
StringUtils.splitPreserveAllTokens(null) = null StringUtils.splitPreserveAllTokens("") = [] StringUtils.splitPreserveAllTokens("abc def") = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def") = ["abc", "", "def"] StringUtils.splitPreserveAllTokens(" abc ") = ["", "abc", ""]
str
- the String to parse, may be null
null
if null String inputpublic static String[] splitPreserveAllTokens(String str, char separatorChar)
Splits the provided text into an array, separator specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A null
input String returns null
.
StringUtils.splitPreserveAllTokens(null, *) = null StringUtils.splitPreserveAllTokens("", *) = [] StringUtils.splitPreserveAllTokens("a.b.c", '.') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a..b.c", '.') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a:b:c", '.') = ["a:b:c"] StringUtils.splitPreserveAllTokens("a\tb\nc", null) = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a b c", ' ') = ["a", "b", "c"] StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", ""] StringUtils.splitPreserveAllTokens("a b c ", ' ') = ["a", "b", "c", "", ""] StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", a", "b", "c"] StringUtils.splitPreserveAllTokens(" a b c", ' ') = ["", "", a", "b", "c"] StringUtils.splitPreserveAllTokens(" a b c ", ' ') = ["", a", "b", "c", ""]
str
- the String to parse, may be null
separatorChar
- the character used as the delimiter,
null
splits on whitespacenull
if null String inputpublic static String[] splitPreserveAllTokens(String str, String separatorChars)
Splits the provided text into an array, separators specified, preserving all tokens, including empty tokens created by adjacent separators. This is an alternative to using StringTokenizer.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. For more control over the split use the StrTokenizer class.
A null
input String returns null
.
A null
separatorChars splits on whitespace.
StringUtils.splitPreserveAllTokens(null, *) = null StringUtils.splitPreserveAllTokens("", *) = [] StringUtils.splitPreserveAllTokens("abc def", null) = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "def"] StringUtils.splitPreserveAllTokens("abc def", " ") = ["abc", "", def"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":") = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef:", ":") = ["ab", "cd", "ef", ""] StringUtils.splitPreserveAllTokens("ab:cd:ef::", ":") = ["ab", "cd", "ef", "", ""] StringUtils.splitPreserveAllTokens("ab::cd:ef", ":") = ["ab", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef", ":") = ["", cd", "ef"] StringUtils.splitPreserveAllTokens("::cd:ef", ":") = ["", "", cd", "ef"] StringUtils.splitPreserveAllTokens(":cd:ef:", ":") = ["", cd", "ef", ""]
str
- the String to parse, may be null
separatorChars
- the characters used as the delimiters,
null
splits on whitespacenull
if null String inputpublic static String[] splitPreserveAllTokens(String str, String separatorChars, int max)
Splits the provided text into an array with a maximum length, separators specified, preserving all tokens, including empty tokens created by adjacent separators.
The separator is not included in the returned String array. Adjacent separators are treated as separators for empty tokens. 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.splitPreserveAllTokens(null, *, *) = null StringUtils.splitPreserveAllTokens("", *, *) = [] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 0) = ["ab", "cd", "ef"] StringUtils.splitPreserveAllTokens("ab:cd:ef", ":", 2) = ["ab", "cd:ef"] StringUtils.splitPreserveAllTokens("ab de fg", null, 2) = ["ab", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 3) = ["ab", "", " de fg"] StringUtils.splitPreserveAllTokens("ab de fg", null, 4) = ["ab", "", "", "de fg"]
str
- the String to parse, may be null
separatorChars
- the characters used as the delimiters,
null
splits on whitespacemax
- the maximum number of elements to include in the
array. A zero or negative value implies no limitnull
if null String inputpublic static String join(Object[] array)
Joins the elements of the provided array into a single String containing the provided list of elements.
No separator is added to the joined String. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null) = null StringUtils.join([]) = "" StringUtils.join([null]) = "" StringUtils.join(["a", "b", "c"]) = "abc" StringUtils.join([null, "", "a"]) = "a"
array
- the array of values to join together, may be nullnull
if null array inputpublic static String join(Object[] array, char separator)
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list. Null objects or empty strings within the array are represented by empty strings.
StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], ';') = "a;b;c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join([null, "", "a"], ';') = ";;a"
array
- the array of values to join together, may be nullseparator
- the separator character to usenull
if null array inputpublic static String join(Object[] array, String separator)
Joins the elements of the provided array into a single String containing the provided list of elements.
No delimiter is added before or after the list.
A null
separator is the same as an empty String ("").
Null objects or empty strings within the array are represented by
empty strings.
StringUtils.join(null, *) = null StringUtils.join([], *) = "" StringUtils.join([null], *) = "" StringUtils.join(["a", "b", "c"], "--") = "a--b--c" StringUtils.join(["a", "b", "c"], null) = "abc" StringUtils.join(["a", "b", "c"], "") = "abc" StringUtils.join([null, "", "a"], ',') = ",,a"
array
- the array of values to join together, may be nullseparator
- the separator character to use, null treated as ""null
if null array inputpublic static String join(Iterator iterator, char separator)
Joins the elements of the provided Iterator
into
a single String containing the provided elements.
No delimiter is added before or after the list. Null objects or empty strings within the iteration are represented by empty strings.
See the examples here: join(Object[],char)
.
iterator
- the Iterator
of values to join together, may be nullseparator
- the separator character to usenull
if null iterator inputpublic static String join(Iterator iterator, String separator)
Joins the elements of the provided Iterator
into
a single String containing the provided elements.
No delimiter is added before or after the list.
A null
separator is the same as an empty String ("").
See the examples here: join(Object[],String)
.
iterator
- the Iterator
of values to join together, may be nullseparator
- the separator character to use, null treated as ""null
if null iterator inputpublic static String defaultString(String str)
Returns either the passed in String,
or if the String is null
, an empty String ("").
StringUtils.defaultString(null) = "" StringUtils.defaultString("") = "" StringUtils.defaultString("bat") = "bat"
str
- the String to check, may be nullnull
String.valueOf(Object)
public static String defaultString(String str, String defaultStr)
Returns either the passed in String, or if the String is
null
, the value of defaultStr
.
StringUtils.defaultString(null, "NULL") = "NULL" StringUtils.defaultString("", "NULL") = "" StringUtils.defaultString("bat", "NULL") = "bat"
str
- the String to check, may be nulldefaultStr
- the default String to return
if the input is null
, may be nullnull
String.valueOf(Object)
public static String defaultIfEmpty(String str, String defaultStr)
Returns either the passed in String, or if the String is
empty or null
, the value of defaultStr
.
StringUtils.defaultIfEmpty(null, "NULL") = "NULL" StringUtils.defaultIfEmpty("", "NULL") = "NULL" StringUtils.defaultIfEmpty("bat", "NULL") = "bat"
str
- the String to check, may be nulldefaultStr
- the default String to return
if the input is empty ("") or null
, may be nullpublic static String capitalize(String str)
Capitalizes a String changing the first letter to title case as
per Character.toTitleCase(char)
. No other letters are changed.
null
input String returns null
.
StringUtils.capitalize(null) = null StringUtils.capitalize("") = "" StringUtils.capitalize("cat") = "Cat" StringUtils.capitalize("cAt") = "CAt"
str
- the String to capitalize, may be nullnull
if null String inputpublic static boolean contains(String str, char searchChar)
Checks if String contains a search character, handling null
.
This method uses String.indexOf(int)
.
A null
or empty ("") String will return false
.
StringUtils.contains(null, *) = false StringUtils.contains("", *) = false StringUtils.contains("abc", 'a') = true StringUtils.contains("abc", 'z') = false
str
- the String to check, may be nullsearchChar
- the character to findnull
string inputpublic static boolean contains(String str, String searchStr)
Checks if String contains a search String, handling null
.
This method uses String.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
str
- the String to check, may be nullsearchStr
- the String to find, may be nullnull
string inputpublic static boolean equals(Object object1, Object object2)
Compares two objects for equality, where either one or both
objects may be null
.
ObjectUtils.equals(null, null) = true ObjectUtils.equals(null, "") = false ObjectUtils.equals("", null) = false ObjectUtils.equals("", "") = true ObjectUtils.equals(Boolean.TRUE, null) = false ObjectUtils.equals(Boolean.TRUE, "true") = false ObjectUtils.equals(Boolean.TRUE, Boolean.TRUE) = true ObjectUtils.equals(Boolean.TRUE, Boolean.FALSE) = false
object1
- the first object, may be null
object2
- the second object, may be null
true
if the values of both objects are the samepublic static String getFullStackTrace(Throwable throwable)
A way to get the entire nested stack-trace of an throwable.
throwable
- the Throwable
to be examinedpublic 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.
throwable
- the throwable to inspect, may be nullpublic 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.
throwable
- the Throwable
to examine, may be nulltrue
if nested otherwise false
public static boolean isThrowableNested()
Checks if the Throwable class has a getCause
method.
This is true for JDK 1.4 and above.
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 default list searched for are:
getCause()
getNextException()
getTargetException()
getException()
getSourceException()
getRootCause()
getCausedByException()
getNested()
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
.
throwable
- the throwable to introspect for a cause, may be nullThrowable
,
null
if none found or null throwable inputpublic static Throwable getCause(Throwable throwable, String[] methodNames)
Introspects the Throwable
to obtain the cause.
A null
set of method names means use the default set.
A null
in the set of method names will be ignored.
throwable
- the throwable to introspect for a cause, may be nullmethodNames
- the method names, null treated as default setThrowable
,
null
if none found or null throwable inputpublic static String argKey(String option)
option
- public static String argValue(String option)
option
- public static Map<String,String> argMap(String[] args)
args
- public static String argMapString(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required)
argMap
- argMapNotUsed
- key
- required
- public static boolean argMapBoolean(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required, boolean defaultValue)
argMap
- argMapNotUsed
- key
- required
- defaultValue
- public static Timestamp argMapTimestamp(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key)
argMap
- argMapNotUsed
- key
- public static Boolean argMapBoolean(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key)
argMap
- argMapNotUsed
- key
- public static Set<String> argMapSet(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required)
argMap
- argMapNotUsed
- key
- required
- public static List<String> argMapList(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required)
argMap
- argMapNotUsed
- key
- required
- public static List<String> argMapFileList(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required)
argMap
- argMapNotUsed
- key
- required
- public static void copy(InputStream input, Writer output) throws IOException
InputStream
to chars on a
Writer
using the default character encoding of the platform.
This method buffers the input internally, so there is no need to use a
BufferedInputStream
.
This method uses InputStreamReader
.
input
- the InputStream
to read fromoutput
- the Writer
to write toNullPointerException
- if the input or output is nullIOException
- if an I/O error occurspublic static int copy(InputStream input, OutputStream output) throws IOException
InputStream
to an
OutputStream
.
This method buffers the input internally, so there is no need to use a
BufferedInputStream
.
Large streams (over 2GB) will return a bytes copied value of
-1
after the copy has completed since the correct
number of bytes cannot be returned as an int. For large streams
use the copyLarge(InputStream, OutputStream)
method.
input
- the InputStream
to read fromoutput
- the OutputStream
to write toNullPointerException
- if the input or output is nullIOException
- if an I/O error occursArithmeticException
- if the byte count is too largepublic static long copyLarge(InputStream input, OutputStream output) throws IOException
InputStream
to an
OutputStream
.
This method buffers the input internally, so there is no need to use a
BufferedInputStream
.
input
- the InputStream
to read fromoutput
- the OutputStream
to write toNullPointerException
- if the input or output is nullIOException
- if an I/O error occurspublic static File jarFile(Class sampleClass)
sampleClass
- public static String stripLastSlashIfExists(String input)
input
- public static String retrievePasswordFromStdin(boolean dontMask, String prompt)
dontMask
- prompt
- to print to userpublic static final char[] retrievePasswordFromStdin(InputStream in, String prompt) throws IOException
in
- stream to be used (e.g. System.in)prompt
- The prompt to display to the user.IOException
public static boolean propertyValidateValueRequired(String resourceName, Properties properties, Map<String,String> overrideMap, String key, boolean exceptionOnError)
resourceName
- properties
- overrideMap
- key
- exceptionOnError
- public static boolean propertyValidateValueBoolean(String resourceName, Properties properties, Map<String,String> overrideMap, String key, boolean required, boolean exceptionOnError)
resourceName
- properties
- overrideMap
- key
- required
- exceptionOnError
- public static boolean propertyValidateValueInt(String resourceName, Properties properties, Map<String,String> overrideMap, String key, boolean required, boolean exceptionOnError)
resourceName
- properties
- overrideMap
- key
- required
- exceptionOnError
- public static boolean propertyValidateValueClass(String resourceName, Properties properties, Map<String,String> overrideMap, String key, Class<?> classType, boolean required, boolean exceptionOnError)
resourceName
- properties
- overrideMap
- key
- classType
- required
- exceptionOnError
- public static String stripStart(String str, String stripChars)
Strips any of a set of characters from the start of a String.
A null
input String returns null
.
An empty string ("") input returns the empty string.
If the stripChars String is null
, whitespace is
stripped as defined by Character.isWhitespace(char)
.
StringUtils.stripStart(null, *) = null StringUtils.stripStart("", *) = "" StringUtils.stripStart("abc", "") = "abc" StringUtils.stripStart("abc", null) = "abc" StringUtils.stripStart(" abc", null) = "abc" StringUtils.stripStart("abc ", null) = "abc " StringUtils.stripStart(" abc ", null) = "abc " StringUtils.stripStart("yxabc ", "xyz") = "abc "
str
- the String to remove characters from, may be nullstripChars
- the characters to remove, null treated as whitespacenull
if null String inputpublic static String stripEnd(String str, String stripChars)
Strips any of a set of characters from the end of a String.
A null
input String returns null
.
An empty string ("") input returns the empty string.
If the stripChars String is null
, whitespace is
stripped as defined by Character.isWhitespace(char)
.
StringUtils.stripEnd(null, *) = null StringUtils.stripEnd("", *) = "" StringUtils.stripEnd("abc", "") = "abc" StringUtils.stripEnd("abc", null) = "abc" StringUtils.stripEnd(" abc", null) = " abc" StringUtils.stripEnd("abc ", null) = "abc" StringUtils.stripEnd(" abc ", null) = " abc" StringUtils.stripEnd(" abcyx", "xyz") = " abc"
str
- the String to remove characters from, may be nullstripChars
- the characters to remove, null treated as whitespacenull
if null String inputpublic static String repeat(String str, int repeat)
Repeat a String repeat
times to form a
new String.
StringUtils.repeat(null, 2) = null StringUtils.repeat("", 0) = "" StringUtils.repeat("", 2) = "" StringUtils.repeat("a", 3) = "aaa" StringUtils.repeat("ab", 2) = "abab" StringUtils.repeat("a", -2) = ""
str
- the String to repeat, may be nullrepeat
- number of times to repeat str, negative treated as zeronull
if null String inputpublic static String rightPad(String str, int size)
Right pad a String with spaces (' ').
The String is padded to the size of size
.
StringUtils.rightPad(null, *) = null StringUtils.rightPad("", 3) = " " StringUtils.rightPad("bat", 3) = "bat" StringUtils.rightPad("bat", 5) = "bat " StringUtils.rightPad("bat", 1) = "bat" StringUtils.rightPad("bat", -1) = "bat"
str
- the String to pad out, may be nullsize
- the size to pad tonull
if null String inputpublic static String rightPad(String str, int size, char padChar)
Right pad a String with a specified character.
The String is padded to the size of size
.
StringUtils.rightPad(null, *, *) = null StringUtils.rightPad("", 3, 'z') = "zzz" StringUtils.rightPad("bat", 3, 'z') = "bat" StringUtils.rightPad("bat", 5, 'z') = "batzz" StringUtils.rightPad("bat", 1, 'z') = "bat" StringUtils.rightPad("bat", -1, 'z') = "bat"
str
- the String to pad out, may be nullsize
- the size to pad topadChar
- the character to pad withnull
if null String inputpublic static String rightPad(String str, int size, String padStr)
Right pad a String with a specified String.
The String is padded to the size of size
.
StringUtils.rightPad(null, *, *) = null StringUtils.rightPad("", 3, "z") = "zzz" StringUtils.rightPad("bat", 3, "yz") = "bat" StringUtils.rightPad("bat", 5, "yz") = "batyz" StringUtils.rightPad("bat", 8, "yz") = "batyzyzy" StringUtils.rightPad("bat", 1, "yz") = "bat" StringUtils.rightPad("bat", -1, "yz") = "bat" StringUtils.rightPad("bat", 5, null) = "bat " StringUtils.rightPad("bat", 5, "") = "bat "
str
- the String to pad out, may be nullsize
- the size to pad topadStr
- the String to pad with, null or empty treated as single spacenull
if null String inputpublic static String leftPad(String str, int size)
Left pad a String with spaces (' ').
The String is padded to the size of size
.
StringUtils.leftPad(null, *) = null StringUtils.leftPad("", 3) = " " StringUtils.leftPad("bat", 3) = "bat" StringUtils.leftPad("bat", 5) = " bat" StringUtils.leftPad("bat", 1) = "bat" StringUtils.leftPad("bat", -1) = "bat"
str
- the String to pad out, may be nullsize
- the size to pad tonull
if null String inputpublic static String leftPad(String str, int size, char padChar)
Left pad a String with a specified character.
Pad to a size of size
.
StringUtils.leftPad(null, *, *) = null StringUtils.leftPad("", 3, 'z') = "zzz" StringUtils.leftPad("bat", 3, 'z') = "bat" StringUtils.leftPad("bat", 5, 'z') = "zzbat" StringUtils.leftPad("bat", 1, 'z') = "bat" StringUtils.leftPad("bat", -1, 'z') = "bat"
str
- the String to pad out, may be nullsize
- the size to pad topadChar
- the character to pad withnull
if null String inputpublic static String leftPad(String str, int size, String padStr)
Left pad a String with a specified String.
Pad to a size of size
.
StringUtils.leftPad(null, *, *) = null StringUtils.leftPad("", 3, "z") = "zzz" StringUtils.leftPad("bat", 3, "yz") = "bat" StringUtils.leftPad("bat", 5, "yz") = "yzbat" StringUtils.leftPad("bat", 8, "yz") = "yzyzybat" StringUtils.leftPad("bat", 1, "yz") = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null) = " bat" StringUtils.leftPad("bat", 5, "") = " bat"
str
- the String to pad out, may be nullsize
- the size to pad topadStr
- the String to pad with, null or empty treated as single spacenull
if null String inputpublic static void convertToRuntimeException(Exception e)
e
- public static String substringBefore(String str, String separator)
Gets the substring before the first occurrence of a separator. The separator is not returned.
A null
string input will return null
.
An empty ("") string input will return the empty string.
A null
separator will return the input string.
StringUtils.substringBefore(null, *) = null StringUtils.substringBefore("", *) = "" StringUtils.substringBefore("abc", "a") = "" StringUtils.substringBefore("abcba", "b") = "a" StringUtils.substringBefore("abc", "c") = "ab" StringUtils.substringBefore("abc", "d") = "abc" StringUtils.substringBefore("abc", "") = "" StringUtils.substringBefore("abc", null) = "abc"
str
- the String to get a substring from, may be nullseparator
- the String to search for, may be nullnull
if null String inputpublic static String substringAfter(String str, String separator)
Gets the substring after the first occurrence of a separator. The separator is not returned.
A null
string input will return null
.
An empty ("") string input will return the empty string.
A null
separator will return the empty string if the
input string is not null
.
StringUtils.substringAfter(null, *) = null StringUtils.substringAfter("", *) = "" StringUtils.substringAfter(*, null) = "" StringUtils.substringAfter("abc", "a") = "bc" StringUtils.substringAfter("abcba", "b") = "cba" StringUtils.substringAfter("abc", "c") = "" StringUtils.substringAfter("abc", "d") = "" StringUtils.substringAfter("abc", "") = "abc"
str
- the String to get a substring from, may be nullseparator
- the String to search for, may be nullnull
if null String inputpublic static String substringBeforeLast(String str, String separator)
Gets the substring before the last occurrence of a separator. The separator is not returned.
A null
string input will return null
.
An empty ("") string input will return the empty string.
An empty or null
separator will return the input string.
StringUtils.substringBeforeLast(null, *) = null StringUtils.substringBeforeLast("", *) = "" StringUtils.substringBeforeLast("abcba", "b") = "abc" StringUtils.substringBeforeLast("abc", "c") = "ab" StringUtils.substringBeforeLast("a", "a") = "" StringUtils.substringBeforeLast("a", "z") = "a" StringUtils.substringBeforeLast("a", null) = "a" StringUtils.substringBeforeLast("a", "") = "a"
str
- the String to get a substring from, may be nullseparator
- the String to search for, may be nullnull
if null String inputpublic static String substringAfterLast(String str, String separator)
Gets the substring after the last occurrence of a separator. The separator is not returned.
A null
string input will return null
.
An empty ("") string input will return the empty string.
An empty or null
separator will return the empty string if
the input string is not null
.
StringUtils.substringAfterLast(null, *) = null StringUtils.substringAfterLast("", *) = "" StringUtils.substringAfterLast(*, "") = "" StringUtils.substringAfterLast(*, null) = "" StringUtils.substringAfterLast("abc", "a") = "bc" StringUtils.substringAfterLast("abcba", "b") = "a" StringUtils.substringAfterLast("abc", "c") = "" StringUtils.substringAfterLast("a", "a") = "" StringUtils.substringAfterLast("a", "z") = ""
str
- the String to get a substring from, may be nullseparator
- the String to search for, may be nullnull
if null String inputpublic static Integer argMapInteger(Map<String,String> argMap, Map<String,String> argMapNotUsed, String key, boolean required, Integer defaultValue)
argMap
- argMapNotUsed
- key
- required
- defaultValue
- public static Date toSqlDate(Date date)
date
- 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.
array
- the array to search through for the object, may be null
objectToFind
- the object to find, may be null
-1
if not found or null
array inputpublic static boolean contains(Object[] array, Object objectToFind)
Checks if the object is in the given array.
The method returns false
if a null
array is passed in.
array
- the array to search throughobjectToFind
- the object to findtrue
if the array contains the objectpublic 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
.
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-1
if not found or null
array inputpublic static String dateToString(Date date)
date
- public static Date stringToDate(String dateString)
dateString
- public static Date stringToDate2(String input)
input
- public static int monthInt(String mon)
mon
- public static Map<String,String> propertiesThreadLocalOverrideMap(String propertiesFileName)
propertiesFileName
- public static void execCommand(String command)
command
- public static ConfigPropertiesCascadeCommonUtils.CommandResult execCommand(String[] arguments)
This will execute a command (with args). In this method, if the exit code of the command is not zero, an exception will be thrown. Example call: execCommand(new String[]{"/bin/bash", "-c", "cd /someFolder; runSomeScript.sh"}, true);
arguments
- are the commandspublic static ExecutorService retrieveExecutorService()
public static ConfigPropertiesCascadeCommonUtils.CommandResult execCommand(String[] arguments, boolean exceptionOnExitValueNeZero)
This will execute a command (with args). Under normal operation, if the exit code of the command is not zero, an exception will be thrown. If the parameter exceptionOnExitValueNeZero is set to true, the results of the call will be returned regardless of the exit status. Example call: execCommand(new String[]{"/bin/bash", "-c", "cd /someFolder; runSomeScript.sh"}, true);
arguments
- are the commandsexceptionOnExitValueNeZero
- if this is set to false, the
results of the call will be returned regardless of the exit statuspublic static void serializeObjectToFile(Serializable object, File file)
object
- file
- public static Serializable unserializeObjectFromFile(File file, boolean nullIfException, boolean deleteFileOnException)
file
- nullIfException
- true if null should be returned instead of exceptiondeleteFileOnException
- true if file should be deleted on exceptionpublic static void deleteCreateFile(File file)
file
- is the file to delete and createpublic static void deleteFile(File file)
file
- public static void copy(File fromFile, File toFile)
fromFile
- toFile
- public static void renameTo(File fromFile, File toFile)
fromFile
- toFile
- public static void deleteRecursiveDirectory(String dirName)
dirName
- RuntimeException
- when something goes wrongpublic static String absolutePath(File file)
file
- public static InputStream fileOrClasspathInputstream(String typeAndLocation, String logHint)
typeAndLocation
- Copyright © 2016 Internet2. All rights reserved.