Class Utils
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionstatic <T extends Collection>
TFluent override of Collections.addAll()static org.apache.commons.collections4.multimap.ArrayListValuedHashMapaddToMap(org.apache.commons.collections4.multimap.ArrayListValuedHashMap<String, String> multiMap, String... kvPairs) static ArrayListSimilar to Arrays.asList but with raw ArrayList return type assuming that all objects don't have to be the same type.static HashMapAdds each even and old object as a key/value pair to a HashMapstatic HashSetSimilar to Arrays.asList but returning a raw HashSet assuming that all objects don't have to be the same type.static booleanConverst a string to a boolean.static doubleConvert a string to a double.static floatConvert a string to a float.static intConvert a string to an integer.static longConvert a string to a long.static ObjectcastDbOutput(String type, Object value) static ObjectcastJsonInput(String type, Object value) static voidUtility to call a close() method on supplied objects if it exists and completely ignore any exceptions.static booleancontainsToken(String findThisToken, String inThisString) Checks for a whole word case insensitive match offindThisTokenininThisStringstatic FilecreateTempFile(String fileName) static DateAttempts to parse a date with several usual formats.static DateFaster way to apply a SimpleDateFormat without having to catch ParseExceptionstatic StringRemoves all matching pairs of '"` characters from the start and end of a string.static StringRemoves all matching pairs of leading/trailingquoteCharsfrom the start and end of a string.static booleanstatic booleanendsWith(CharSequence seq, String end) String.endsWith surrogate for StringBuffer and StringBuilderstatic booleanA null safe loose equality checker.static voidShortcut for throw new RuntimeException(message);Similar to String.split but trims whitespace and excludes empty stringsstatic InputStreamfindInputStream(String fileOrUrl) Attempts to locate the stream as a file, url, or classpath resourcestatic StringfindSysEnvProp(String... names) static Objectstatic StringA heroically forgiving message string formatter.static StringformatDate(Date date, String format) Simple one liner to avoid verbosity of using SimpleDateFormatstatic StringformatIso8601(Date date) static ObjectgetBeanProperty(String propertyName, Object bean) Tries to find a bean property getter then defaults to returning the Field valuestatic ThrowableTries to unwrap nested exceptions looking for the root causestatic FieldSearches the inheritance hierarchy for a field with the the given name and makes sure it is settable via Field.setAccessible().Gets all the fields from from all classes in the inheritance hierarchy EXCEPT for any class who's packages starts with "java*".static MethodSearches the inheritance hierarchy for the first method of the given name (ignores case).static Stringstatic StringgetShortCause(Throwable t, int lines) getStackTraceLines(Throwable stackTrace) static StringgetStackTraceString(Throwable stackTrace) static StringgetSysEnvProp(String name) static ObjectgetSysEnvProp(String name, Object defaultValue) static booleangetSysEnvPropBool(String name, Object defaultValue) static intgetSysEnvPropInt(String name, Object defaultValue) static StringgetSysEnvPropStr(String name, Object defaultValue) static Stringstatic StringConcatenates non emptypiecesseparated byglueand intelligently flattens collections.static booleanChecks to see iftoFindis invaluesarray using loose equality checkingstatic booleanisWildcard(String str) static Objectstatic StringlimitLines(String text, int limit) static Stringmd5(byte[] bytes) static DateparseIso8601(String date) static LinkedHashMap<String,String> parseQueryString(String query) static voidpipe(InputStream in, OutputStream out) Copy all data from src to dst and close the streamsstatic StringRead the contents of a file to a stringstatic Stringread(InputStream in) Read all of the stream to a string and close the stream.static StringFinds an input stream forfileOrUrland reads it into a stringstatic voidThrows the root cause of e as a RuntimeExceptionstatic voidThrows the root cause oferroras a RuntimeExceptionstatic introundUp(int num, int divisor) static Stringsha1(byte[] bytes) static voidsleep(long milliseconds) Easy way to call Thread.sleep(long) without worrying about try/catch for InterruptedExceptionstatic StringCreates a lowercase url safe string.Breaks the string onsplitOnbut not when inside aquoteCharsquoted string.static String[]splitLines(String text) static booleanstartsWith(CharSequence seq, String start) String.startsWith surrogate for StringBuffer and StringBuilderstatic StringsubstringAfter(String string, String breakAfterLast) static StringsubstringBefore(String string, String breakBefore) static booleantestCompare(String expected, String actual) static longtime()Less typing to call System.currentTimeMillis()static BigDecimaltoDollarAmount(double amount) Turns a double value into a rounded double with 2 digits of precision 12.3334 -@gt; 12.33 23.0 -@gt; 23.00 45.677 -@gt; 45.68static booleanwildcardMatch(String wildcard, String string) Pattern matches the string using ? to indicate any one single value and * to indicate any 0-n multiple valuestatic StringwildcardToRegex(String wildcard) Converts a * and ? wildcard style patterns into regex style patternstatic voidWrite the string value to a filestatic voidConvenience overloading of write(File, String)
-
Constructor Details
-
Utils
public Utils()
-
-
Method Details
-
equal
A null safe loose equality checker.- Parameters:
obj1- an objectobj2- an object to compare to obj1- Returns:
- true when args are strictly equal or toString equal
-
in
Checks to see iftoFindis invaluesarray using loose equality checking- Parameters:
toFind- the object to findvalues- where to try and find it- Returns:
- true if toFind is loosely equal to any of
values
-
empty
- Parameters:
arr- an array of objects to check and see if any are not empty- Returns:
- true if any args are not null with a toString().length() @gt; 0
-
first
-
last
-
add
Fluent override of Collections.addAll()- Type Parameters:
T- a subclass of Collection- Parameters:
collection- the collection to add items toitems- the items to add- Returns:
- the collection passed in
- See Also:
-
endsWith
String.endsWith surrogate for StringBuffer and StringBuilder- Parameters:
seq- the string to checkend- the ending to check for- Returns:
- true if seq ends with end
-
startsWith
String.startsWith surrogate for StringBuffer and StringBuilder- Parameters:
seq- the string to checkstart- the starting substring to check for- Returns:
- true if seq ends with end
-
implode
Concatenates non emptypiecesseparated byglueand intelligently flattens collections.- Parameters:
glue- the joining stringpieces- the pieces to join- Returns:
- a concatenation of pieces separated by glue
-
explode
Similar to String.split but trims whitespace and excludes empty strings- Parameters:
delimiter- the split delimiterpieces- the strings to split- Returns:
- all non empty strings from all pieces
-
split
Breaks the string onsplitOnbut not when inside aquoteCharsquoted string.- Parameters:
string- the string to splitsplitOn- the character to split onquoteChars- quote chars that invalidate the instance of slit char- Returns:
- the split parts
-
substringBefore
-
substringAfter
-
format
A heroically forgiving message string formatter.This method attempts to safely toString all of the args and replaces any "{}" characters with "%s" before formatting via String.format(String, Object[]).
Any Throwables in the args list will have their short cause string appended to the end of the formatted message.
If the format is invalid or contains too few or too many args, the method will make sure that all arg toStrings are in the output.
The goal here is to make sure that no matter what happens, you will get something useful out of this message if not exactly to the format spec.
- Parameters:
format- a string containing "{}" arg placeholders of formatted per java.util.Formatterargs- objects that will be replaced into theirformatplaceholders.- Returns:
- the formatted string
-
addToMap
-
addToMap
-
asList
Similar to Arrays.asList but with raw ArrayList return type assuming that all objects don't have to be the same type.- Parameters:
objects- the objects to add- Returns:
- a new ArrayList containing
objects
-
asSet
Similar to Arrays.asList but returning a raw HashSet assuming that all objects don't have to be the same type.- Parameters:
objects- the objects to add- Returns:
- a new HashSet containing
objects
-
asMap
Adds each even and old object as a key/value pair to a HashMap- Parameters:
keyValuePairs- a list of key/value pairs that should have an even number of elements- Returns:
- a new HashMap containing keyValuePairs
-
containsToken
Checks for a whole word case insensitive match offindThisTokenininThisStringhttps://www.baeldung.com/java-regexp-escape-char https://stackoverflow.com/questions/7459263/regex-whole-word
- Parameters:
findThisToken- the string to findinThisString- in this other string- Returns:
- true if findThisToken exists as a whole world in inThisString
-
dequote
Removes all matching pairs of '"` characters from the start and end of a string.- Parameters:
str- the string to dequote- Returns:
- str with matched pairs of leading/trailing '"` characters removed
-
dequote
Removes all matching pairs of leading/trailingquoteCharsfrom the start and end of a string.- Parameters:
str- the string to dequotequoteChars- characters to treat as quotes- Returns:
- str with matched pairs of leading/trailing quoteChars removed
-
toDollarAmount
Turns a double value into a rounded double with 2 digits of precision 12.3334 -@gt; 12.33 23.0 -@gt; 23.00 45.677 -@gt; 45.68- Parameters:
amount- the amount to round- Returns:
- the amount rounded to two decimal places
-
roundUp
public static int roundUp(int num, int divisor) -
atob
Converst a string to a boolean.Easier and null safe way to call Boolean.parseBoolean(str.trim()) that swallows exceptions.
- Parameters:
str- the string to parse as a boolean- Returns:
- true if the trimmed lower case str is "0" or "false"
-
atoi
Convert a string to an integer.Easier null safe way to call Integer.parseInt(str.trim()) that swallows exceptions.
- Parameters:
str- the string to parse- Returns:
- the parsed value or -1 if the string does not parse
-
atol
Convert a string to a long.Easier null safe way to call Long.parseLong(str.trim()) that swallows exceptions.
- Parameters:
str- the string to parse- Returns:
- the parsed value or -1 if the string does not parse
-
atof
Convert a string to a float.Easier null safe way to call Float.parseFloat(str.trim()) that swallows exceptions.
- Parameters:
str- the string to parse- Returns:
- the parsed value or -1 if the string does not parse
-
atod
Convert a string to a double.Easier null safe way to call Double.parseDouble(str.trim()) that swallows exceptions.
- Parameters:
str- the string to parse- Returns:
- the parsed value or -1 if the string does not parse
-
slugify
Creates a lowercase url safe string.- Parameters:
str- the string to slugify- Returns:
- the slugified string
-
sha1
- Parameters:
bytes- the bytes to hash- Returns:
- Hash the bytes with SHA-1
-
md5
- Parameters:
bytes- the bytes to hash- Returns:
- Hash the bytes with MD5
-
hash
- Parameters:
bytes- the bytes to hashalgorithm- the hash algorithm- Returns:
- Hash the bytes with the given algorithm
-
time
public static long time()Less typing to call System.currentTimeMillis()- Returns:
- the current time in milliseconds
-
parseIso8601
-
formatIso8601
-
formatDate
Simple one liner to avoid verbosity of using SimpleDateFormat- Parameters:
date- the date to formatformat- the format- Returns:
- the formatted date
-
date
Faster way to apply a SimpleDateFormat without having to catch ParseException- Parameters:
date- the date string to formatformat- the format string- Returns:
- the formatted date
-
date
Attempts to parse a date with several usual formats.Formats attempted:
- an ISO8601 data
- then yyyy-MM-dd
- then MM/dd/yy
- then MM/dd/yyyy
- then yyyyMMdd
- Parameters:
date- the date string to parse- Returns:
- the parsed date
- See Also:
-
testCompare
-
getCause
Tries to unwrap nested exceptions looking for the root cause- Parameters:
t- the error to investigate- Returns:
- the recursively root cause
-
error
Shortcut for throw new RuntimeException(message);- Parameters:
message- the error message- Throws:
RuntimeException- always
-
rethrow
Throws the root cause oferroras a RuntimeException- Parameters:
error- error to rethrow- Throws:
RuntimeException- always
-
rethrow
Throws the root cause of e as a RuntimeException- Parameters:
message- the optional message to include in the RuntimeExceptionerror- the error to rethrow- Throws:
RuntimeException- always
-
sleep
Easy way to call Thread.sleep(long) without worrying about try/catch for InterruptedException- Parameters:
milliseconds- the number of milliseconds to sleep- Throws:
RuntimeException- if InterruptedException is thrown
-
getShortCause
-
getShortCause
-
getStackTraceLines
-
getStackTraceString
-
splitLines
-
limitLines
-
getField
Searches the inheritance hierarchy for a field with the the given name and makes sure it is settable via Field.setAccessible().- Parameters:
fieldName- the field to findclazz- the class to find it in- Returns:
- the first Field found with name
-
getFields
Gets all the fields from from all classes in the inheritance hierarchy EXCEPT for any class who's packages starts with "java*".- Parameters:
clazz- the class to search- Returns:
- all Fields in the inheritance hierarchy other "java*" packages classes.
-
getMethod
Searches the inheritance hierarchy for the first method of the given name (ignores case).No distinction is made for overloaded method names.
- Parameters:
clazz- the class to searchname- the name of a method to find- Returns:
- the first method with name
-
getBeanProperty
Tries to find a bean property getter then defaults to returning the Field value- Parameters:
propertyName- the bean property value to findbean- the bean to find it in- Returns:
- the value of the bean property with propertyName
-
read
Finds an input stream forfileOrUrland reads it into a string- Parameters:
fileOrUrl- the resource to read- Returns:
- the content of
codeas a String - See Also:
-
read
Read all of the stream to a string and close the stream.- Parameters:
in- the data to stringify- Returns:
- the data from in as a string
- Throws:
RuntimeException- when an IOException is thrown
-
read
Read the contents of a file to a string- Parameters:
file- the file to read and stringify- Returns:
- the file text
- Throws:
IOException- when an IOException is thrown- See Also:
-
write
Write the string value to a file- Parameters:
file- the file to writetext- the content to write- Throws:
IOException- if unable to create the parent directory or when IO fails
-
write
Convenience overloading of write(File, String)- Parameters:
file- the file path to writetext- the text to write to the file- Throws:
IOException- when thrown- See Also:
-
pipe
Copy all data from src to dst and close the streams- Parameters:
in- the data to be writtenout- where the data should be written to- Throws:
IOException- when thrown
-
createTempFile
- Throws:
IOException
-
findInputStream
Attempts to locate the stream as a file, url, or classpath resource- Parameters:
fileOrUrl- a stream resource identifier- Returns:
- an input stream reading fileOrUrl
- Throws:
RuntimeException- when and IOException is thrown
-
isWildcard
- Parameters:
str- the string to chec to see if it is a wildcard pattern.- Returns:
- true if the string contains a * or a ?
-
wildcardMatch
Pattern matches the string using ? to indicate any one single value and * to indicate any 0-n multiple value- Parameters:
wildcard- a wildcard patternstring- the string to check to see if it matches the wildcard- Returns:
- true if string matches wildcard
-
wildcardToRegex
Converts a * and ? wildcard style patterns into regex style pattern- Parameters:
wildcard- the wildcard expression to convert to a regex- Returns:
- a wildcard pattern converted to a regex
- See Also:
-
parseQueryString
-
findSysEnvProp
-
getSysEnvPropStr
- Parameters:
name- - name to look for in sysprops and envpropsdefaultValue- - will be returned if prop not found- Returns:
- first not null of sysprop(name) || envprop(name) || defaultValue
-
getSysEnvPropInt
-
getSysEnvPropBool
-
getSysEnvProp
- Parameters:
name- - name to look for in sysprops and envprops if 'value' is null;defaultValue- - will be returned if not found on sys or env- Returns:
- first not null of sysprop(name) || envprop(name) || 'defaultValue'
-
getSysEnvProp
-
castDbOutput
-
castJsonInput
-
close
Utility to call a close() method on supplied objects if it exists and completely ignore any exceptions.- Parameters:
toClose- the object to close.
-