Class Utils

java.lang.Object
io.inversion.utils.Utils

public class Utils extends Object
Collection of utility methods designed to make java programming less verbose
  • Constructor Details

    • Utils

      public Utils()
  • Method Details

    • equal

      public static boolean equal(Object obj1, Object obj2)
      A null safe loose equality checker.
      Parameters:
      obj1 - an object
      obj2 - an object to compare to obj1
      Returns:
      true when args are strictly equal or toString equal
    • in

      public static boolean in(Object toFind, Object... values)
      Checks to see if toFind is in values array using loose equality checking
      Parameters:
      toFind - the object to find
      values - where to try and find it
      Returns:
      true if toFind is loosely equal to any of values
    • empty

      public static boolean empty(Object... arr)
      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

      public static Object first(List list)
    • last

      public static Object last(List list)
    • add

      public static <T extends Collection> T add(T collection, Object... items)
      Fluent override of Collections.addAll()
      Type Parameters:
      T - a subclass of Collection
      Parameters:
      collection - the collection to add items to
      items - the items to add
      Returns:
      the collection passed in
      See Also:
    • endsWith

      public static boolean endsWith(CharSequence seq, String end)
      String.endsWith surrogate for StringBuffer and StringBuilder
      Parameters:
      seq - the string to check
      end - the ending to check for
      Returns:
      true if seq ends with end
    • startsWith

      public static boolean startsWith(CharSequence seq, String start)
      String.startsWith surrogate for StringBuffer and StringBuilder
      Parameters:
      seq - the string to check
      start - the starting substring to check for
      Returns:
      true if seq ends with end
    • implode

      public static String implode(String glue, Object... pieces)
      Concatenates non empty pieces separated by glue and intelligently flattens collections.
      Parameters:
      glue - the joining string
      pieces - the pieces to join
      Returns:
      a concatenation of pieces separated by glue
    • explode

      public static List<String> explode(String delimiter, String... pieces)
      Similar to String.split but trims whitespace and excludes empty strings
      Parameters:
      delimiter - the split delimiter
      pieces - the strings to split
      Returns:
      all non empty strings from all pieces
    • split

      public static List<String> split(String string, char splitOn, char... quoteChars)
      Breaks the string on splitOn but not when inside a quoteChars quoted string.
      Parameters:
      string - the string to split
      splitOn - the character to split on
      quoteChars - quote chars that invalidate the instance of slit char
      Returns:
      the split parts
    • substringBefore

      public static String substringBefore(String string, String breakBefore)
    • substringAfter

      public static String substringAfter(String string, String breakAfterLast)
    • format

      public static String format(String format, Object... args)
      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.Formatter
      args - objects that will be replaced into their format placeholders.
      Returns:
      the formatted string
    • addToMap

      public static org.apache.commons.collections4.multimap.ArrayListValuedHashMap addToMap(org.apache.commons.collections4.multimap.ArrayListValuedHashMap<String,String> multiMap, String... kvPairs)
    • addToMap

      public static <M extends Map<String, String>> M addToMap(M map, String... keyValuePairs)
    • asList

      public static ArrayList asList(Object... objects)
      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

      public static HashSet asSet(Object... objects)
      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

      public static HashMap asMap(Object... keyValuePairs)
      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

      public static boolean containsToken(String findThisToken, String inThisString)
      Checks for a whole word case insensitive match of findThisToken in inThisString

      https://www.baeldung.com/java-regexp-escape-char https://stackoverflow.com/questions/7459263/regex-whole-word

      Parameters:
      findThisToken - the string to find
      inThisString - in this other string
      Returns:
      true if findThisToken exists as a whole world in inThisString
    • dequote

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

      public static String dequote(String str, char[] quoteChars)
      Removes all matching pairs of leading/trailing quoteChars from the start and end of a string.
      Parameters:
      str - the string to dequote
      quoteChars - characters to treat as quotes
      Returns:
      str with matched pairs of leading/trailing quoteChars removed
    • toDollarAmount

      public static BigDecimal toDollarAmount(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.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

      public static boolean atob(Object str)
      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

      public static int atoi(Object str)
      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

      public static long atol(Object str)
      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

      public static float atof(Object str)
      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

      public static double atod(Object str)
      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

      public static String slugify(String str)
      Creates a lowercase url safe string.
      Parameters:
      str - the string to slugify
      Returns:
      the slugified string
    • sha1

      public static String sha1(byte[] bytes)
      Parameters:
      bytes - the bytes to hash
      Returns:
      Hash the bytes with SHA-1
    • md5

      public static String md5(byte[] bytes)
      Parameters:
      bytes - the bytes to hash
      Returns:
      Hash the bytes with MD5
    • hash

      public static String hash(byte[] bytes, String algorithm)
      Parameters:
      bytes - the bytes to hash
      algorithm - 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

      public static Date parseIso8601(String date)
    • formatIso8601

      public static String formatIso8601(Date date)
    • formatDate

      public static String formatDate(Date date, String format)
      Simple one liner to avoid verbosity of using SimpleDateFormat
      Parameters:
      date - the date to format
      format - the format
      Returns:
      the formatted date
    • date

      public static Date date(String date, String format)
      Faster way to apply a SimpleDateFormat without having to catch ParseException
      Parameters:
      date - the date string to format
      format - the format string
      Returns:
      the formatted date
    • date

      public static Date date(String date)
      Attempts to parse a date with several usual formats.

      Formats attempted:

      1. an ISO8601 data
      2. then yyyy-MM-dd
      3. then MM/dd/yy
      4. then MM/dd/yyyy
      5. then yyyyMMdd
      Parameters:
      date - the date string to parse
      Returns:
      the parsed date
      See Also:
    • testCompare

      public static boolean testCompare(String expected, String actual)
    • getCause

      public static Throwable getCause(Throwable t)
      Tries to unwrap nested exceptions looking for the root cause
      Parameters:
      t - the error to investigate
      Returns:
      the recursively root cause
    • error

      public static void error(String message) throws RuntimeException
      Shortcut for throw new RuntimeException(message);
      Parameters:
      message - the error message
      Throws:
      RuntimeException - always
    • rethrow

      public static void rethrow(Throwable error) throws RuntimeException
      Throws the root cause of error as a RuntimeException
      Parameters:
      error - error to rethrow
      Throws:
      RuntimeException - always
    • rethrow

      public static void rethrow(String message, Throwable error) throws RuntimeException
      Throws the root cause of e as a RuntimeException
      Parameters:
      message - the optional message to include in the RuntimeException
      error - the error to rethrow
      Throws:
      RuntimeException - always
    • sleep

      public static void sleep(long milliseconds) throws RuntimeException
      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

      public static String getShortCause(Throwable t)
    • getShortCause

      public static String getShortCause(Throwable t, int lines)
    • getStackTraceLines

      public static List<String> getStackTraceLines(Throwable stackTrace)
    • getStackTraceString

      public static String getStackTraceString(Throwable stackTrace)
    • splitLines

      public static String[] splitLines(String text)
    • limitLines

      public static String limitLines(String text, int limit)
    • getField

      public static Field getField(String fieldName, Class clazz)
      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 find
      clazz - the class to find it in
      Returns:
      the first Field found with name
    • getFields

      public static List<Field> getFields(Class clazz)
      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

      public static Method getMethod(Class clazz, String name)
      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 search
      name - the name of a method to find
      Returns:
      the first method with name
    • getBeanProperty

      public static Object getBeanProperty(String propertyName, Object bean)
      Tries to find a bean property getter then defaults to returning the Field value
      Parameters:
      propertyName - the bean property value to find
      bean - the bean to find it in
      Returns:
      the value of the bean property with propertyName
    • read

      public static String read(String fileOrUrl)
      Finds an input stream for fileOrUrl and reads it into a string
      Parameters:
      fileOrUrl - the resource to read
      Returns:
      the content of code as a String
      See Also:
    • read

      public static String read(InputStream in) throws RuntimeException
      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

      public static String read(File file) throws IOException
      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

      public static void write(File file, String text) throws IOException
      Write the string value to a file
      Parameters:
      file - the file to write
      text - the content to write
      Throws:
      IOException - if unable to create the parent directory or when IO fails
    • write

      public static void write(String file, String text) throws IOException
      Convenience overloading of write(File, String)
      Parameters:
      file - the file path to write
      text - the text to write to the file
      Throws:
      IOException - when thrown
      See Also:
    • pipe

      public static void pipe(InputStream in, OutputStream out) throws IOException
      Copy all data from src to dst and close the streams
      Parameters:
      in - the data to be written
      out - where the data should be written to
      Throws:
      IOException - when thrown
    • createTempFile

      public static File createTempFile(String fileName) throws IOException
      Throws:
      IOException
    • findInputStream

      public static InputStream findInputStream(String fileOrUrl) throws RuntimeException
      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

      public static boolean isWildcard(String str)
      Parameters:
      str - the string to chec to see if it is a wildcard pattern.
      Returns:
      true if the string contains a * or a ?
    • wildcardMatch

      public static boolean wildcardMatch(String wildcard, String string)
      Pattern matches the string using ? to indicate any one single value and * to indicate any 0-n multiple value
      Parameters:
      wildcard - a wildcard pattern
      string - the string to check to see if it matches the wildcard
      Returns:
      true if string matches wildcard
    • wildcardToRegex

      public static String wildcardToRegex(String wildcard)
      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

      public static LinkedHashMap<String,String> parseQueryString(String query)
    • findSysEnvProp

      public static String findSysEnvProp(String... names)
    • getSysEnvPropStr

      public static String getSysEnvPropStr(String name, Object defaultValue)
      Parameters:
      name - - name to look for in sysprops and envprops
      defaultValue - - will be returned if prop not found
      Returns:
      first not null of sysprop(name) || envprop(name) || defaultValue
    • getSysEnvPropInt

      public static int getSysEnvPropInt(String name, Object defaultValue)
    • getSysEnvPropBool

      public static boolean getSysEnvPropBool(String name, Object defaultValue)
    • getSysEnvProp

      public static Object getSysEnvProp(String name, Object defaultValue)
      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

      public static String getSysEnvProp(String name)
    • castDbOutput

      public static Object castDbOutput(String type, Object value)
    • castJsonInput

      public static Object castJsonInput(String type, Object value)
    • close

      public static void close(Object... toClose)
      Utility to call a close() method on supplied objects if it exists and completely ignore any exceptions.
      Parameters:
      toClose - the object to close.