Class Tools


  • public abstract class Tools
    extends Object
    Miscellaneous utility methods.
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  Tools.LogLevel
      Log level for the customized logger.
    • Method Summary

      All Methods Static Methods Concrete Methods 
      Modifier and Type Method Description
      static <T> CompletableFuture<List<T>> allOf​(List<CompletableFuture<T>> futures)
      Returns a new CompletableFuture completed with a list of computed values when all of the given CompletableFuture complete.
      static <T> CompletableFuture<T> allOf​(List<CompletableFuture<T>> futures, BinaryOperator<T> reducer, T emptyValue)
      Returns a new CompletableFuture completed by reducing a list of computed values when all of the given CompletableFuture complete.
      static byte[] byteBuffertoArray​(ByteBuffer buffer)
      Returns the contents of ByteBuffer as byte array.
      static CompletableFuture<Void> completeAfter​(long timeout, TimeUnit unit)
      Returns a future that completes normally after given time period.
      static void copyDirectory​(File src, File dst)
      Copies the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in copy of unintended files.
      static void copyDirectory​(String src, String dst)
      Copies the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in copy of unintended files.
      static byte[] copyOf​(byte[] original)
      Returns a copy of the input byte array.
      static OffsetDateTime defaultOffsetDataTime​(long epochMillis)
      Creates OffsetDateTime instance from epoch milliseconds, using system default time zone.
      static void delay​(int ms)
      Suspends the current thread for a specified number of millis.
      static void delay​(int ms, int nanos)
      Suspends the current thread for a specified number of millis and nanos.
      static <T> Set<T> emptyIsNotFound​(Set<T> item, String message)
      Returns the specified set if the set is not null and not empty; otherwise throws a not found exception.
      static <T> CompletableFuture<T> exceptionalFuture​(Throwable t)
      Returns a future that is completed exceptionally.
      static <T> CompletableFuture<T> firstOf​(List<CompletableFuture<T>> futures)
      Returns a new CompletableFuture completed with the first result from a list of futures.
      static <T> CompletableFuture<T> firstOf​(List<CompletableFuture<T>> futures, Match<T> positiveResultMatcher, T negativeResult)
      Returns a new CompletableFuture completed by with the first positive result from a list of input CompletableFutures.
      static long fromHex​(String string)
      Converts a string from hex to long.
      static <T> T futureGetOrElse​(Future<T> future, long timeout, TimeUnit timeUnit, T defaultValue)
      Returns the future value when complete or if future completes exceptionally returns the defaultValue.
      static <T> T futureGetOrElse​(Future<T> future, T defaultValue)
      Returns the future value when complete or if future completes exceptionally returns the defaultValue.
      static String get​(Dictionary<?,​?> properties, String propertyName)
      Get property as a string value.
      static byte[] getBytesUtf8​(String input)
      Returns the UTF-8 encoded byte[] representation of a String.
      static Float getFloatProperty​(Dictionary<?,​?> properties, String propertyName)
      Get Float property from the propertyName Return null if propertyName is not found.
      static Integer getIntegerProperty​(Dictionary<?,​?> properties, String propertyName)
      Get Integer property from the propertyName Return null if propertyName is not found.
      static int getIntegerProperty​(Dictionary<?,​?> properties, String propertyName, int defaultValue)
      Get Integer property from the propertyName Return default value if propertyName is not found.
      static Long getLongProperty​(Dictionary<?,​?> properties, String propertyName)
      Get Long property from the propertyName Return null if propertyName is not found.
      static ThreadFactory groupedThreads​(String groupName, String pattern)
      Returns a thread factory that produces threads named according to the supplied name pattern and from the specified thread-group.
      static ThreadFactory groupedThreads​(String groupName, String pattern, org.slf4j.Logger logger)
      Returns a thread factory that produces threads named according to the supplied name pattern and from the specified thread-group.
      static boolean isNullOrEmpty​(Collection<?> collection)
      Returns true if the collection is null or is empty.
      static Boolean isPropertyEnabled​(Dictionary<?,​?> properties, String propertyName)
      Check property name is defined and set to true.
      static boolean isPropertyEnabled​(Dictionary<?,​?> properties, String propertyName, boolean defaultValue)
      Check property name is defined as set to true.
      static void log​(org.slf4j.Logger logger, Tools.LogLevel level, String format, Object... args)
      Wrapper function that enables logger invocation with log level as a parameter.
      static <C extends Comparable<? super C>>
      C
      max​(C l, C r)
      Returns larger of the two Comparable values.
      static ThreadFactory maxPriority​(ThreadFactory factory)
      Returns a thread factory that produces threads with MAX_PRIORITY.
      static <C extends Comparable<? super C>>
      C
      min​(C l, C r)
      Returns smaller of the two Comparable values.
      static ThreadFactory minPriority​(ThreadFactory factory)
      Returns a thread factory that produces threads with MIN_PRIORITY.
      static ThreadFactory namedThreads​(String pattern)
      Returns a thread factory that produces threads named according to the supplied name pattern.
      static <T> T nullIsIllegal​(T item, String message)
      Returns the specified item if that item is not null; otherwise throws bad argument exception.
      static <T> T nullIsNotFound​(T item, String message)
      Returns the specified item if that item is not null; otherwise throws not found exception.
      static <T> CompletableFuture<T> orderedFuture​(CompletableFuture<T> future, Executor orderedExecutor, Executor threadPoolExecutor)
      Returns a future that's completed using the given orderedExecutor if the future is not blocked or the given threadPoolExecutor if the future is blocked.
      static void randomDelay​(int ms)
      Suspends the current thread for a random number of millis between 0 and the indicated limit.
      static com.fasterxml.jackson.databind.node.ObjectNode readTreeFromStream​(com.fasterxml.jackson.databind.ObjectMapper mapper, InputStream stream)
      Utility to convert a mapper and an input stream into a JSON tree, and be tolerant of a null tree being returned.
      static void removeDirectory​(File dir)
      Purges the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in deletion of unintended files.
      static void removeDirectory​(String path)
      Purges the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in deletion of unintended files.
      static <U,​V>
      Function<U,​V>
      retryable​(Function<U,​V> base, Class<? extends Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
      Returns a function that retries execution on failure.
      static <V> Supplier<V> retryable​(Supplier<V> base, Class<? extends Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
      Returns a Supplier that retries execution on failure.
      static <T> Stream<T> stream​(Iterable<T> it)
      Converts an iterable to a stream.
      static <T> Stream<T> stream​(Optional<? extends T> optional)
      Converts an optional to a stream.
      static String timeAgo​(long unixTime)
      Returns a human friendly time ago string for a specified system time.
      static String toHex​(long value)
      Converts a long value to hex string; 16 wide and sans 0x.
      static String toHex​(long value, int width)
      Converts a long value to hex string; 16 wide and sans 0x.
      static String toHexWithPrefix​(long value)
      Returns a string encoding in hex of the given long value with prefix '0x'.
      static String toStringUtf8​(byte[] input)
      Returns the String representation of UTF-8 encoded byte[].
    • Method Detail

      • namedThreads

        public static ThreadFactory namedThreads​(String pattern)
        Returns a thread factory that produces threads named according to the supplied name pattern.
        Parameters:
        pattern - name pattern
        Returns:
        thread factory
      • groupedThreads

        public static ThreadFactory groupedThreads​(String groupName,
                                                   String pattern)
        Returns a thread factory that produces threads named according to the supplied name pattern and from the specified thread-group. The thread group name is expected to be specified in slash-delimited format, e.g. onos/intent. The thread names will be produced by converting the thread group name into dash-delimited format and pre-pended to the specified pattern.
        Parameters:
        groupName - group name in slash-delimited format to indicate hierarchy
        pattern - name pattern
        Returns:
        thread factory
      • groupedThreads

        public static ThreadFactory groupedThreads​(String groupName,
                                                   String pattern,
                                                   org.slf4j.Logger logger)
        Returns a thread factory that produces threads named according to the supplied name pattern and from the specified thread-group. The thread group name is expected to be specified in slash-delimited format, e.g. onos/intent. The thread names will be produced by converting the thread group name into dash-delimited format and pre-pended to the specified pattern. If a logger is specified, it will use the logger to print out the exception if it has any.
        Parameters:
        groupName - group name in slash-delimited format to indicate hierarchy
        pattern - name pattern
        logger - logger
        Returns:
        thread factory
      • minPriority

        public static ThreadFactory minPriority​(ThreadFactory factory)
        Returns a thread factory that produces threads with MIN_PRIORITY.
        Parameters:
        factory - backing ThreadFactory
        Returns:
        thread factory
      • maxPriority

        public static ThreadFactory maxPriority​(ThreadFactory factory)
        Returns a thread factory that produces threads with MAX_PRIORITY.
        Parameters:
        factory - backing ThreadFactory
        Returns:
        thread factory
      • isNullOrEmpty

        public static boolean isNullOrEmpty​(Collection<?> collection)
        Returns true if the collection is null or is empty.
        Parameters:
        collection - collection to test
        Returns:
        true if null or empty; false otherwise
      • nullIsNotFound

        public static <T> T nullIsNotFound​(T item,
                                           String message)
        Returns the specified item if that item is not null; otherwise throws not found exception.
        Type Parameters:
        T - item type
        Parameters:
        item - item to check
        message - not found message
        Returns:
        item if not null
        Throws:
        ItemNotFoundException - if item is null
      • emptyIsNotFound

        public static <T> Set<T> emptyIsNotFound​(Set<T> item,
                                                 String message)
        Returns the specified set if the set is not null and not empty; otherwise throws a not found exception.
        Type Parameters:
        T - Set item type
        Parameters:
        item - set to check
        message - not found message
        Returns:
        item if not null and not empty
        Throws:
        ItemNotFoundException - if set is null or empty
      • nullIsIllegal

        public static <T> T nullIsIllegal​(T item,
                                          String message)
        Returns the specified item if that item is not null; otherwise throws bad argument exception.
        Type Parameters:
        T - item type
        Parameters:
        item - item to check
        message - not found message
        Returns:
        item if not null
        Throws:
        IllegalArgumentException - if item is null
      • readTreeFromStream

        public static com.fasterxml.jackson.databind.node.ObjectNode readTreeFromStream​(com.fasterxml.jackson.databind.ObjectMapper mapper,
                                                                                        InputStream stream)
                                                                                 throws IOException
        Utility to convert a mapper and an input stream into a JSON tree, and be tolerant of a null tree being returned.
        Parameters:
        mapper - JSON object mapper
        stream - IO stream containing the JSON
        Returns:
        object node for the given
        Throws:
        IOException - if JSON parsing fails
      • fromHex

        public static long fromHex​(String string)
        Converts a string from hex to long.
        Parameters:
        string - hex number in string form; sans 0x
        Returns:
        long value
      • toHex

        public static String toHex​(long value)
        Converts a long value to hex string; 16 wide and sans 0x.
        Parameters:
        value - long value
        Returns:
        hex string
      • toHex

        public static String toHex​(long value,
                                   int width)
        Converts a long value to hex string; 16 wide and sans 0x.
        Parameters:
        value - long value
        width - string width; zero padded
        Returns:
        hex string
      • toHexWithPrefix

        public static String toHexWithPrefix​(long value)
        Returns a string encoding in hex of the given long value with prefix '0x'.
        Parameters:
        value - long value to encode as hex string
        Returns:
        hex string
      • getBytesUtf8

        public static byte[] getBytesUtf8​(String input)
        Returns the UTF-8 encoded byte[] representation of a String.
        Parameters:
        input - input string
        Returns:
        UTF-8 encoded byte array
      • toStringUtf8

        public static String toStringUtf8​(byte[] input)
        Returns the String representation of UTF-8 encoded byte[].
        Parameters:
        input - input byte array
        Returns:
        UTF-8 encoded string
      • copyOf

        public static byte[] copyOf​(byte[] original)
        Returns a copy of the input byte array.
        Parameters:
        original - input
        Returns:
        copy of original
      • get

        public static String get​(Dictionary<?,​?> properties,
                                 String propertyName)
        Get property as a string value.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        Returns:
        value when the propertyName is defined or return null
      • getIntegerProperty

        public static Integer getIntegerProperty​(Dictionary<?,​?> properties,
                                                 String propertyName)
        Get Integer property from the propertyName Return null if propertyName is not found.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        Returns:
        value when the propertyName is defined or return null
      • getIntegerProperty

        public static int getIntegerProperty​(Dictionary<?,​?> properties,
                                             String propertyName,
                                             int defaultValue)
        Get Integer property from the propertyName Return default value if propertyName is not found.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        defaultValue - the default value that to be assigned
        Returns:
        value when the propertyName is defined or return default value
      • isPropertyEnabled

        public static Boolean isPropertyEnabled​(Dictionary<?,​?> properties,
                                                String propertyName)
        Check property name is defined and set to true.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        Returns:
        value when the propertyName is defined or return null
      • isPropertyEnabled

        public static boolean isPropertyEnabled​(Dictionary<?,​?> properties,
                                                String propertyName,
                                                boolean defaultValue)
        Check property name is defined as set to true.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        defaultValue - the default value that to be assigned
        Returns:
        value when the propertyName is defined or return the default value
      • delay

        public static void delay​(int ms)
        Suspends the current thread for a specified number of millis.
        Parameters:
        ms - number of millis
      • getLongProperty

        public static Long getLongProperty​(Dictionary<?,​?> properties,
                                           String propertyName)
        Get Long property from the propertyName Return null if propertyName is not found.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        Returns:
        value when the propertyName is defined or return null
      • getFloatProperty

        public static Float getFloatProperty​(Dictionary<?,​?> properties,
                                             String propertyName)
        Get Float property from the propertyName Return null if propertyName is not found.
        Parameters:
        properties - properties to be looked up
        propertyName - the name of the property to look up
        Returns:
        value when the propertyName is defined or return null
      • retryable

        public static <U,​V> Function<U,​V> retryable​(Function<U,​V> base,
                                                                Class<? extends Throwable> exceptionClass,
                                                                int maxRetries,
                                                                int maxDelayBetweenRetries)
        Returns a function that retries execution on failure.
        Type Parameters:
        U - type of function input
        V - type of function output
        Parameters:
        base - base function
        exceptionClass - type of exception for which to retry
        maxRetries - max number of retries before giving up
        maxDelayBetweenRetries - max delay between successive retries. The actual delay is randomly picked from the interval (0, maxDelayBetweenRetries]
        Returns:
        function
      • retryable

        public static <V> Supplier<V> retryable​(Supplier<V> base,
                                                Class<? extends Throwable> exceptionClass,
                                                int maxRetries,
                                                int maxDelayBetweenRetries)
        Returns a Supplier that retries execution on failure.
        Type Parameters:
        V - type of supplied result
        Parameters:
        base - base supplier
        exceptionClass - type of exception for which to retry
        maxRetries - max number of retries before giving up
        maxDelayBetweenRetries - max delay between successive retries. The actual delay is randomly picked from the interval (0, maxDelayBetweenRetries]
        Returns:
        supplier
      • randomDelay

        public static void randomDelay​(int ms)
        Suspends the current thread for a random number of millis between 0 and the indicated limit.
        Parameters:
        ms - max number of millis
      • delay

        public static void delay​(int ms,
                                 int nanos)
        Suspends the current thread for a specified number of millis and nanos.
        Parameters:
        ms - number of millis
        nanos - number of nanos
      • removeDirectory

        public static void removeDirectory​(String path)
                                    throws IOException
        Purges the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in deletion of unintended files.
        Parameters:
        path - directory to be removed
        Throws:
        IOException - if unable to remove contents
      • removeDirectory

        public static void removeDirectory​(File dir)
                                    throws IOException
        Purges the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in deletion of unintended files.
        Parameters:
        dir - directory to be removed
        Throws:
        IOException - if unable to remove contents
      • timeAgo

        public static String timeAgo​(long unixTime)
        Returns a human friendly time ago string for a specified system time.
        Parameters:
        unixTime - system time in millis
        Returns:
        human friendly time ago
      • copyDirectory

        public static void copyDirectory​(String src,
                                         String dst)
                                  throws IOException
        Copies the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in copy of unintended files.
        Parameters:
        src - directory to be copied
        dst - destination directory to be removed
        Throws:
        IOException - if unable to remove contents
      • copyDirectory

        public static void copyDirectory​(File src,
                                         File dst)
                                  throws IOException
        Copies the specified directory path. Use with great caution since no attempt is made to check for symbolic links, which could result in copy of unintended files.
        Parameters:
        src - directory to be copied
        dst - destination directory to be removed
        Throws:
        IOException - if unable to remove contents
      • futureGetOrElse

        public static <T> T futureGetOrElse​(Future<T> future,
                                            T defaultValue)
        Returns the future value when complete or if future completes exceptionally returns the defaultValue.
        Type Parameters:
        T - future value type
        Parameters:
        future - future
        defaultValue - default value
        Returns:
        future value when complete or if future completes exceptionally returns the defaultValue.
      • futureGetOrElse

        public static <T> T futureGetOrElse​(Future<T> future,
                                            long timeout,
                                            TimeUnit timeUnit,
                                            T defaultValue)
        Returns the future value when complete or if future completes exceptionally returns the defaultValue.
        Type Parameters:
        T - future value type
        Parameters:
        future - future
        timeout - time to wait for successful completion
        timeUnit - time unit
        defaultValue - default value
        Returns:
        future value when complete or if future completes exceptionally returns the defaultValue.
      • exceptionalFuture

        public static <T> CompletableFuture<T> exceptionalFuture​(Throwable t)
        Returns a future that is completed exceptionally.
        Type Parameters:
        T - future value type
        Parameters:
        t - exception
        Returns:
        future
      • completeAfter

        public static CompletableFuture<Void> completeAfter​(long timeout,
                                                            TimeUnit unit)
        Returns a future that completes normally after given time period.
        Parameters:
        timeout - amount of time to wait before completing the future
        unit - Time unit
        Returns:
        a future that completes after given time period
      • orderedFuture

        public static <T> CompletableFuture<T> orderedFuture​(CompletableFuture<T> future,
                                                             Executor orderedExecutor,
                                                             Executor threadPoolExecutor)
        Returns a future that's completed using the given orderedExecutor if the future is not blocked or the given threadPoolExecutor if the future is blocked.

        This method allows futures to maintain single-thread semantics via the provided orderedExecutor while ensuring user code can block without blocking completion of futures. When the returned future or any of its descendants is blocked on a CompletableFuture.get() or CompletableFuture.join() call, completion of the returned future will be done using the provided threadPoolExecutor.

        Type Parameters:
        T - future value type
        Parameters:
        future - the future to convert into an asynchronous future
        orderedExecutor - the ordered executor with which to attempt to complete the future
        threadPoolExecutor - the backup executor with which to complete blocked futures
        Returns:
        a new completable future to be completed using the provided executor once the provided future is complete
      • allOf

        public static <T> CompletableFuture<List<T>> allOf​(List<CompletableFuture<T>> futures)
        Returns a new CompletableFuture completed with a list of computed values when all of the given CompletableFuture complete.
        Type Parameters:
        T - value type of CompletableFuture
        Parameters:
        futures - the CompletableFutures
        Returns:
        a new CompletableFuture that is completed when all of the given CompletableFutures complete
      • allOf

        public static <T> CompletableFuture<T> allOf​(List<CompletableFuture<T>> futures,
                                                     BinaryOperator<T> reducer,
                                                     T emptyValue)
        Returns a new CompletableFuture completed by reducing a list of computed values when all of the given CompletableFuture complete.
        Type Parameters:
        T - value type of CompletableFuture
        Parameters:
        futures - the CompletableFutures
        reducer - reducer for computing the result
        emptyValue - zero value to be returned if the input future list is empty
        Returns:
        a new CompletableFuture that is completed when all of the given CompletableFutures complete
      • firstOf

        public static <T> CompletableFuture<T> firstOf​(List<CompletableFuture<T>> futures)
        Returns a new CompletableFuture completed with the first result from a list of futures. If no future is completed successfully, the returned future will be completed with the first exception.
        Type Parameters:
        T - future result type
        Parameters:
        futures - the input futures
        Returns:
        a new CompletableFuture
      • firstOf

        public static <T> CompletableFuture<T> firstOf​(List<CompletableFuture<T>> futures,
                                                       Match<T> positiveResultMatcher,
                                                       T negativeResult)
        Returns a new CompletableFuture completed by with the first positive result from a list of input CompletableFutures.
        Type Parameters:
        T - value type of CompletableFuture
        Parameters:
        futures - the input list of CompletableFutures
        positiveResultMatcher - matcher to identify a positive result
        negativeResult - value to complete with if none of the futures complete with a positive result
        Returns:
        a new CompletableFuture
      • byteBuffertoArray

        public static byte[] byteBuffertoArray​(ByteBuffer buffer)
        Returns the contents of ByteBuffer as byte array.

        WARNING: There is a performance cost due to array copy when using this method.

        Parameters:
        buffer - byte buffer
        Returns:
        byte array containing the byte buffer contents
      • stream

        public static <T> Stream<T> stream​(Iterable<T> it)
        Converts an iterable to a stream.
        Type Parameters:
        T - type if item
        Parameters:
        it - iterable to convert
        Returns:
        iterable as a stream
      • stream

        public static <T> Stream<T> stream​(Optional<? extends T> optional)
        Converts an optional to a stream.
        Type Parameters:
        T - type of enclosed value
        Parameters:
        optional - optional to convert
        Returns:
        optional as a stream
      • defaultOffsetDataTime

        public static OffsetDateTime defaultOffsetDataTime​(long epochMillis)
        Creates OffsetDateTime instance from epoch milliseconds, using system default time zone.
        Parameters:
        epochMillis - to convert
        Returns:
        OffsetDateTime
      • min

        public static <C extends Comparable<? super C>> C min​(C l,
                                                              C r)
        Returns smaller of the two Comparable values.
        Type Parameters:
        C - Comparable type
        Parameters:
        l - an argument
        r - another argument
        Returns:
        the smaller of l or r
        Throws:
        NullPointerException - if any of the arguments were null.
      • max

        public static <C extends Comparable<? super C>> C max​(C l,
                                                              C r)
        Returns larger of the two Comparable values.
        Type Parameters:
        C - Comparable type
        Parameters:
        l - an argument
        r - another argument
        Returns:
        the larger of l or r
        Throws:
        NullPointerException - if any of the arguments were null.
      • log

        public static void log​(org.slf4j.Logger logger,
                               Tools.LogLevel level,
                               String format,
                               Object... args)
        Wrapper function that enables logger invocation with log level as a parameter.
        Parameters:
        logger - logger
        level - log level
        format - format string
        args - objects