Class Util


  • public final class Util
    extends java.lang.Object
    Utility class providing helper methods for handling strings, files and so on.
    Since:
    v3.2.5 - 2020-12-28
    • Field Summary

      Fields 
      Modifier and Type Field Description
      private static org.slf4j.Logger LOGGER  
      private static char[] SYMBOLS
      Characters used for random strings
    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      private Util()  
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static java.lang.String abbreviate​(java.lang.String _str, int _length)
      Abbreviates a String using ellipses.
      static int checkIntInRange​(int _check, int _min, int _max)
      Checks if given value is greater or equal to the given minimum and less or equal to the given maximum.
      static <T> boolean collectionContainsAny​(java.util.Collection<T> _haystack, java.util.Collection<T> _needles)
      Checks if any of the 'needle' values are found in 'haystack'.
      static java.lang.String createDynamicSessionAddress​(boolean _listeningSocket, boolean _abstract)
      Creates a unix socket address using.
      static java.lang.String genGUID()
      Create a random GUID (used for connection addresses).
      static java.lang.String getCurrentUser()
      Determines the current logged on user.
      static java.lang.String getHostName()
      Gets the host name of the local machine.
      static int getJavaVersion()
      Get the java version of the current running JRE.
      static java.util.List<java.lang.String> getTextfileFromUrl​(java.lang.String _url, java.nio.charset.Charset _charset, boolean _silent)
      Reads a text file from the given URL using the provided charset.
      static boolean isBlank​(java.lang.String _str)
      Checks if the given String is either null or blank.
      static boolean isEmpty​(java.lang.String _str)
      Checks if the given String is either null or empty.
      static boolean isFreeBsd()  
      static boolean isInteger​(java.lang.String _str, boolean _allowNegative)
      Check if string is an either positive or negative integer.
      static boolean isMacOs()
      Checks if the running OS is a MacOS/MacOS X.
      static boolean isValidNetworkPort​(int _port, boolean _allowWellKnown)
      Check if the given value is a valid network port (1 - 65535).
      static boolean isValidNetworkPort​(java.lang.String _str, boolean _allowWellKnown)  
      static boolean isWindows()
      Checks if the running OS is a MS Windows OS.
      static java.lang.String randomString​(int _length)
      Generate a simple (cryptographic insecure) random string.
      static java.util.List<java.lang.String> readFileToList​(java.lang.String _fileName)
      Reads a file to a List<String> (each line is one entry in list).
      static java.lang.String readFileToString​(java.io.File _file)
      Reads a file to a String.
      static java.util.Properties readProperties​(java.io.File _file)
      Trys to read a properties file.
      static java.util.Properties readProperties​(java.io.InputStream _stream)
      Tries to read a properties file from an inputstream.
      static java.util.List<java.lang.String> readTextFileFromStream​(java.io.InputStream _input, java.nio.charset.Charset _charset, boolean _silent)
      Reads a text file from given InputStream using the given Charset.
      static void setFilePermissions​(java.nio.file.Path _path, java.lang.String _fileOwner, java.lang.String _fileGroup, java.util.Set<java.nio.file.attribute.PosixFilePermission> _fileUnixPermissions)
      Setup the unix socket file permissions.
      static java.lang.String snakeToCamelCase​(java.lang.String _input)
      Converts a snake-case-string to camel case string.
      static boolean strEquals​(java.lang.String _str1, java.lang.String _str2)
      Null-safe equals for two strings.
      static java.lang.String upperCaseFirstChar​(java.lang.String _str)
      Upper case the first letter of the given string.
      static <T extends java.lang.Throwable>
      void
      waitFor​(java.lang.String _lockName, IThrowingSupplier<java.lang.Boolean,​T> _wait, long _timeoutMs, long _sleepTime)
      Waits for the provided supplier to return true or throws an exception.
      static boolean writeTextFile​(java.lang.String _fileName, java.lang.String _fileContent, java.nio.charset.Charset _charset, boolean _append)
      Write String to file with the given charset.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Field Detail

      • LOGGER

        private static final org.slf4j.Logger LOGGER
      • SYMBOLS

        private static final char[] SYMBOLS
        Characters used for random strings
    • Constructor Detail

      • Util

        private Util()
    • Method Detail

      • readProperties

        public static java.util.Properties readProperties​(java.io.File _file)
        Trys to read a properties file. Returns null if properties file could not be loaded
        Parameters:
        _file - property file to read
        Returns:
        Properties Object or null
      • readProperties

        public static java.util.Properties readProperties​(java.io.InputStream _stream)
        Tries to read a properties file from an inputstream.
        Parameters:
        _stream - input stream providing property file content
        Returns:
        properties object/null
      • isBlank

        public static boolean isBlank​(java.lang.String _str)
        Checks if the given String is either null or blank. Blank means:
         " " - true
         "" - true
         null - true
         " xx" - false
         
        Parameters:
        _str - string to test
        Returns:
        true if string is blank or null, false otherwise
      • strEquals

        public static boolean strEquals​(java.lang.String _str1,
                                        java.lang.String _str2)
        Null-safe equals for two strings.
        Parameters:
        _str1 - first string
        _str2 - second string
        Returns:
        true if both are equal (also true if both are null)
      • isEmpty

        public static boolean isEmpty​(java.lang.String _str)
        Checks if the given String is either null or empty. Blank means:
         " " - false
         "" - true
         null - true
         " xx" - false
         
        Parameters:
        _str - string to test
        Returns:
        true if string is empty or null, false otherwise
      • randomString

        public static java.lang.String randomString​(int _length)
        Generate a simple (cryptographic insecure) random string.
        Parameters:
        _length - length of random string
        Returns:
        random string or empty string if _length <= 0
      • upperCaseFirstChar

        public static java.lang.String upperCaseFirstChar​(java.lang.String _str)
        Upper case the first letter of the given string.
        Parameters:
        _str - string
        Returns:
        uppercased string
      • snakeToCamelCase

        public static java.lang.String snakeToCamelCase​(java.lang.String _input)
        Converts a snake-case-string to camel case string.
        Eg. this_is_snake_case → thisIsSnakeCase
        Parameters:
        _input - string
        Returns:
        camel case string or input if nothing todo. Returns null if input was null.
      • abbreviate

        public static java.lang.String abbreviate​(java.lang.String _str,
                                                  int _length)
        Abbreviates a String using ellipses.
        Parameters:
        _str - string to abbrivate
        _length - max length
        Returns:
        abbreviated string, original string if string length is lower or equal then desired length or null if input was null
      • isValidNetworkPort

        public static boolean isValidNetworkPort​(int _port,
                                                 boolean _allowWellKnown)
        Check if the given value is a valid network port (1 - 65535).
        Parameters:
        _port - 'port' to check
        _allowWellKnown - allow ports below 1024 (aka reserved well known ports)
        Returns:
        true if int is a valid network port, false otherwise
      • isValidNetworkPort

        public static boolean isValidNetworkPort​(java.lang.String _str,
                                                 boolean _allowWellKnown)
        Parameters:
        _str - string to check
        _allowWellKnown - allow well known port
        Returns:
        true if valid port, false otherwise
        See Also:
        isValidNetworkPort(int, boolean)
      • isInteger

        public static boolean isInteger​(java.lang.String _str,
                                        boolean _allowNegative)
        Check if string is an either positive or negative integer.
        Parameters:
        _str - string to validate
        _allowNegative - negative integer allowed
        Returns:
        true if integer, false otherwise
      • readFileToList

        public static java.util.List<java.lang.String> readFileToList​(java.lang.String _fileName)
        Reads a file to a List<String> (each line is one entry in list). Line endings (line feed/carriage return) are NOT removed!
        Parameters:
        _fileName - file to read
        Returns:
        list containing text
      • readFileToString

        public static java.lang.String readFileToString​(java.io.File _file)
        Reads a file to a String. Line endings (line feed/carriage return) are NOT removed!
        Parameters:
        _file - file to read
        Returns:
        String containing content, maybe null
      • getTextfileFromUrl

        public static java.util.List<java.lang.String> getTextfileFromUrl​(java.lang.String _url,
                                                                          java.nio.charset.Charset _charset,
                                                                          boolean _silent)
        Reads a text file from the given URL using the provided charset. Using the _silent argument optionally disables all error logging.
        Parameters:
        _url - url providing the file to read
        _charset - charset to use
        _silent - true to not log exceptions, false otherwise
        Returns:
        list of string or null on error
      • readTextFileFromStream

        public static java.util.List<java.lang.String> readTextFileFromStream​(java.io.InputStream _input,
                                                                              java.nio.charset.Charset _charset,
                                                                              boolean _silent)
        Reads a text file from given InputStream using the given Charset.
        Parameters:
        _input - stream to read
        _charset - charset to use
        _silent - true to disable exception logging, false otherwise
        Returns:
        List of string or null on error
      • writeTextFile

        public static boolean writeTextFile​(java.lang.String _fileName,
                                            java.lang.String _fileContent,
                                            java.nio.charset.Charset _charset,
                                            boolean _append)
        Write String to file with the given charset. Optionally appends the data to the file.
        Parameters:
        _fileName - the file to write
        _fileContent - the content to write
        _charset - the charset to use
        _append - append content to file, if false file will be overwritten if existing
        Returns:
        true on successful write, false otherwise
      • getHostName

        public static java.lang.String getHostName()
        Gets the host name of the local machine.
        Returns:
        host name
      • collectionContainsAny

        public static <T> boolean collectionContainsAny​(java.util.Collection<T> _haystack,
                                                        java.util.Collection<T> _needles)
        Checks if any of the 'needle' values are found in 'haystack'.
        Type Parameters:
        T - type
        Parameters:
        _haystack - collection to check
        _needles - values to find
        Returns:
        true if any value found, false if any parameter null or no matching value found
      • getCurrentUser

        public static java.lang.String getCurrentUser()
        Determines the current logged on user.
        Returns:
        logged on user
      • isMacOs

        public static boolean isMacOs()
        Checks if the running OS is a MacOS/MacOS X.
        Returns:
        true if MacOS (or MacOS X), false otherwise
      • isFreeBsd

        public static boolean isFreeBsd()
      • isWindows

        public static boolean isWindows()
        Checks if the running OS is a MS Windows OS.
        Returns:
        true if Windows, false otherwise
      • getJavaVersion

        public static int getJavaVersion()
        Get the java version of the current running JRE.
        Returns:
        java major
      • genGUID

        public static java.lang.String genGUID()
        Create a random GUID (used for connection addresses).
        Returns:
        String
      • createDynamicSessionAddress

        public static java.lang.String createDynamicSessionAddress​(boolean _listeningSocket,
                                                                   boolean _abstract)
        Creates a unix socket address using.
        Parameters:
        _listeningSocket - true if the address should be used for a listing socket
        _abstract - true to create an abstract socket
        Returns:
        address String
      • checkIntInRange

        public static int checkIntInRange​(int _check,
                                          int _min,
                                          int _max)
        Checks if given value is greater or equal to the given minimum and less or equal to the given maximum.
        Parameters:
        _check - value to check
        _min - minimum allowed value (including)
        _max - maximum allowed value (including)
        Returns:
        given value if in range
        Throws:
        java.lang.IllegalArgumentException - when given value is out of range
        Since:
        4.2.0 - 2022-07-13
      • setFilePermissions

        public static void setFilePermissions​(java.nio.file.Path _path,
                                              java.lang.String _fileOwner,
                                              java.lang.String _fileGroup,
                                              java.util.Set<java.nio.file.attribute.PosixFilePermission> _fileUnixPermissions)
        Setup the unix socket file permissions. User and group can always be set, file permissions are only set on non-windows OSes.
        Parameters:
        _path - path to file which where permissions should be set
        _fileOwner - new owner for the file
        _fileGroup - new group for the file
        _fileUnixPermissions - unix permissions to set on file
      • waitFor

        public static <T extends java.lang.Throwable> void waitFor​(java.lang.String _lockName,
                                                                   IThrowingSupplier<java.lang.Boolean,​T> _wait,
                                                                   long _timeoutMs,
                                                                   long _sleepTime)
                                                            throws T extends java.lang.Throwable
        Waits for the provided supplier to return true or throws an exception.

        This method will call the provided supplier every _sleepTime milliseconds to check if the supplier returns true.
        If supplier returns true, method will return. If no value is present after the defined _timeoutMs a IllegalStateException is thrown.

        Type Parameters:
        T - exception type which might be thrown
        Parameters:
        _lockName - name for the lock (used in exception text and logging)
        _wait - supplier to wait for
        _timeoutMs - timeout in milliseconds when wait will fail
        _sleepTime - sleep time between each retries
        Throws:
        T - when timeout is reached
        T extends java.lang.Throwable