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:
      false if any args are not null with a null safe toString().trim().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)
    • ex

      public static RuntimeException ex(Throwable ex)
    • ex

      public static RuntimeException ex(String messageFormat, Object... args)
    • ex

      public static RuntimeException ex(Throwable cause, String messageFormat, Object... args)
    • 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 Map addToMap(Map map, Object... 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 LinkedHashMap 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
    • disjunction

      public static Set disjunction(Collection a, Collection b)
      Returns the items of 'a' that are not in 'b' and the items of 'b' that are not in 'a'.
    • replaceVars

      public static String replaceVars(String string, Map<String,Object> replacements)
      Replaces '{mapKeyName}' with 'mapValue' in the supplied string.
      Parameters:
      string -
      replacements -
      Returns:
    • 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
    • filter

      public static <M extends Map<String, ?>> M filter(M map, String... tokensToRemove)
      Removes any keys that contain a whole word token contained in tokensToRemove
      Type Parameters:
      M -
      Parameters:
      map -
      tokensToRemove -
      Returns:
      the same map instance, filtered
    • 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. EEE MMM dd HH:mm:ss zzz yyyy
      3. then yyyy-MM-dd
      4. then MM/dd/yy
      5. then MM/dd/yyyy
      6. then yyyyMMdd
      Parameters:
      date - the date string to parse
      Returns:
      the parsed date
    • 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)
    • checkSame

      public static boolean checkSame(String str1, String str2)
    • cast

      public static Object cast(Class clazz, String string)
    • 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
    • getProperty

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

      public static String read(Object caller, String... fileOrUrls)
      Finds an input stream for fileOrUrl and reads it into a string
      Parameters:
      fileOrUrls - 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
    • pipe

      public static void pipe(InputStream in, OutputStream out, boolean closeInputStream, boolean closeOutputStream) throws IOException
      Throws:
      IOException
    • createTempFile

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

      public static InputStream findInputStream(Object caller, String... fileOrUrls) throws RuntimeException
      Attempts to locate the stream as a file, url, or classpath resource
      Parameters:
      fileOrUrls - a stream resource identifier, the first one found will be returned
      Returns:
      an input stream reading fileOrUrl
      Throws:
      RuntimeException - when and IOException is thrown
    • isRegex

      public static boolean isRegex(String string)
      Checks string for wildcard control characters.
      Parameters:
      string -
      Returns:
      true when string contains a regex control character
    • 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)
    • getSysEnvProp

      public static String getSysEnvProp(String name, String defaultValue)
    • getSysEnvProp

      public static String getSysEnvProp(String name)
    • 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.
    • toSingularForm

      public static String toSingularForm(String str)
    • toPluralForm

      public static String toPluralForm(String str)
    • capitalize

      public static String capitalize(String str)
    • bytesToHex

      public static String bytesToHex(byte[] bytes)
    • hexToBytes

      public static byte[] hexToBytes(String hexString)
    • beautifyName

      public static String beautifyName(String name)
      Try to make an attractive camelCase valid javascript variable name.

      Lots of sql db designers use things like SNAKE_CASE_COLUMN_NAMES that look terrible as json property names.

      Parameters:
      name - the to beautify
      Returns:
      a camelCased version of name
      See Also:
    • printTable

      public static String printTable(List<List> table)
    • pad

      public static String pad(String input, int len)