Package org.onlab.util
Class Tools
- java.lang.Object
-
- org.onlab.util.Tools
-
public abstract class Tools extends java.lang.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> java.util.concurrent.CompletableFuture<java.util.List<T>>
allOf(java.util.List<java.util.concurrent.CompletableFuture<T>> futures)
Returns a new CompletableFuture completed with a list of computed values when all of the given CompletableFuture complete.static <T> java.util.concurrent.CompletableFuture<T>
allOf(java.util.List<java.util.concurrent.CompletableFuture<T>> futures, java.util.function.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(java.nio.ByteBuffer buffer)
Returns the contents ofByteBuffer
as byte array.static void
copyDirectory(java.io.File src, java.io.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(java.lang.String src, java.lang.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 java.time.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> java.util.Set<T>
emptyIsNotFound(java.util.Set<T> item, java.lang.String message)
Returns the specified set if the set is not null and not empty; otherwise throws a not found exception.static <T> java.util.concurrent.CompletableFuture<T>
exceptionalFuture(java.lang.Throwable t)
Returns a future that is completed exceptionally.static <T> java.util.concurrent.CompletableFuture<T>
firstOf(java.util.List<java.util.concurrent.CompletableFuture<T>> futures)
Returns a new CompletableFuture completed with the first result from a list of futures.static <T> java.util.concurrent.CompletableFuture<T>
firstOf(java.util.List<java.util.concurrent.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(java.lang.String string)
Converts a string from hex to long.static <T> T
futureGetOrElse(java.util.concurrent.Future<T> future, long timeout, java.util.concurrent.TimeUnit timeUnit, T defaultValue)
Returns the future value when complete or if future completes exceptionally returns the defaultValue.static <T> T
futureGetOrElse(java.util.concurrent.Future<T> future, T defaultValue)
Returns the future value when complete or if future completes exceptionally returns the defaultValue.static java.lang.String
get(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get property as a string value.static byte[]
getBytesUtf8(java.lang.String input)
Returns the UTF-8 encoded byte[] representation of a String.static java.lang.Float
getFloatProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Float property from the propertyName Return null if propertyName is not found.static java.lang.Integer
getIntegerProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Integer property from the propertyName Return null if propertyName is not found.static int
getIntegerProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName, int defaultValue)
Get Integer property from the propertyName Return default value if propertyName is not found.static java.lang.Long
getLongProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Long property from the propertyName Return null if propertyName is not found.static java.util.concurrent.ThreadFactory
groupedThreads(java.lang.String groupName, java.lang.String pattern)
Returns a thread factory that produces threads named according to the supplied name pattern and from the specified thread-group.static java.util.concurrent.ThreadFactory
groupedThreads(java.lang.String groupName, java.lang.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(java.util.Collection<?> collection)
Returns true if the collection is null or is empty.static java.lang.Boolean
isPropertyEnabled(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Check property name is defined and set to true.static boolean
isPropertyEnabled(java.util.Dictionary<?,?> properties, java.lang.String propertyName, boolean defaultValue)
Check property name is defined as set to true.static void
log(org.slf4j.Logger logger, Tools.LogLevel level, java.lang.String format, java.lang.Object... args)
Wrapper function that enables logger invocation with log level as a parameter.static <C extends java.lang.Comparable<? super C>>
Cmax(C l, C r)
Returns larger of the two Comparable values.static java.util.concurrent.ThreadFactory
maxPriority(java.util.concurrent.ThreadFactory factory)
Returns a thread factory that produces threads with MAX_PRIORITY.static <C extends java.lang.Comparable<? super C>>
Cmin(C l, C r)
Returns smaller of the two Comparable values.static java.util.concurrent.ThreadFactory
minPriority(java.util.concurrent.ThreadFactory factory)
Returns a thread factory that produces threads with MIN_PRIORITY.static java.util.concurrent.ThreadFactory
namedThreads(java.lang.String pattern)
Returns a thread factory that produces threads named according to the supplied name pattern.static <T> T
nullIsIllegal(T item, java.lang.String message)
Returns the specified item if that item is not null; otherwise throws bad argument exception.static <T> T
nullIsNotFound(T item, java.lang.String message)
Returns the specified item if that item is not null; otherwise throws not found exception.static <T> java.util.concurrent.CompletableFuture<T>
orderedFuture(java.util.concurrent.CompletableFuture<T> future, java.util.concurrent.Executor orderedExecutor, java.util.concurrent.Executor threadPoolExecutor)
Returns a future that's completed using the givenorderedExecutor
if the future is not blocked or the giventhreadPoolExecutor
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, java.io.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(java.io.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(java.lang.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>
java.util.function.Function<U,V>retryable(java.util.function.Function<U,V> base, java.lang.Class<? extends java.lang.Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
Returns a function that retries execution on failure.static <V> java.util.function.Supplier<V>
retryable(java.util.function.Supplier<V> base, java.lang.Class<? extends java.lang.Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
Returns a Supplier that retries execution on failure.static <T> java.util.stream.Stream<T>
stream(java.lang.Iterable<T> it)
Converts an iterable to a stream.static <T> java.util.stream.Stream<T>
stream(java.util.Optional<? extends T> optional)
Converts an optional to a stream.static java.lang.String
timeAgo(long unixTime)
Returns a human friendly time ago string for a specified system time.static java.lang.String
toHex(long value)
Converts a long value to hex string; 16 wide and sans 0x.static java.lang.String
toHex(long value, int width)
Converts a long value to hex string; 16 wide and sans 0x.static java.lang.String
toHexWithPrefix(long value)
Returns a string encoding in hex of the given long value with prefix '0x'.static java.lang.String
toStringUtf8(byte[] input)
Returns the String representation of UTF-8 encoded byte[].
-
-
-
Method Detail
-
namedThreads
public static java.util.concurrent.ThreadFactory namedThreads(java.lang.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 java.util.concurrent.ThreadFactory groupedThreads(java.lang.String groupName, java.lang.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 hierarchypattern
- name pattern- Returns:
- thread factory
-
groupedThreads
public static java.util.concurrent.ThreadFactory groupedThreads(java.lang.String groupName, java.lang.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 hierarchypattern
- name patternlogger
- logger- Returns:
- thread factory
-
minPriority
public static java.util.concurrent.ThreadFactory minPriority(java.util.concurrent.ThreadFactory factory)
Returns a thread factory that produces threads with MIN_PRIORITY.- Parameters:
factory
- backing ThreadFactory- Returns:
- thread factory
-
maxPriority
public static java.util.concurrent.ThreadFactory maxPriority(java.util.concurrent.ThreadFactory factory)
Returns a thread factory that produces threads with MAX_PRIORITY.- Parameters:
factory
- backing ThreadFactory- Returns:
- thread factory
-
isNullOrEmpty
public static boolean isNullOrEmpty(java.util.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, java.lang.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 checkmessage
- not found message- Returns:
- item if not null
- Throws:
ItemNotFoundException
- if item is null
-
emptyIsNotFound
public static <T> java.util.Set<T> emptyIsNotFound(java.util.Set<T> item, java.lang.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 checkmessage
- 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, java.lang.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 checkmessage
- not found message- Returns:
- item if not null
- Throws:
java.lang.IllegalArgumentException
- if item is null
-
readTreeFromStream
public static com.fasterxml.jackson.databind.node.ObjectNode readTreeFromStream(com.fasterxml.jackson.databind.ObjectMapper mapper, java.io.InputStream stream) throws java.io.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 mapperstream
- IO stream containing the JSON- Returns:
- object node for the given
- Throws:
java.io.IOException
- if JSON parsing fails
-
fromHex
public static long fromHex(java.lang.String string)
Converts a string from hex to long.- Parameters:
string
- hex number in string form; sans 0x- Returns:
- long value
-
toHex
public static java.lang.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 java.lang.String toHex(long value, int width)
Converts a long value to hex string; 16 wide and sans 0x.- Parameters:
value
- long valuewidth
- string width; zero padded- Returns:
- hex string
-
toHexWithPrefix
public static java.lang.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(java.lang.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 java.lang.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 java.lang.String get(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get property as a string value.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look up- Returns:
- value when the propertyName is defined or return null
-
getIntegerProperty
public static java.lang.Integer getIntegerProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Integer property from the propertyName Return null if propertyName is not found.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look up- Returns:
- value when the propertyName is defined or return null
-
getIntegerProperty
public static int getIntegerProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName, int defaultValue)
Get Integer property from the propertyName Return default value if propertyName is not found.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look updefaultValue
- the default value that to be assigned- Returns:
- value when the propertyName is defined or return default value
-
isPropertyEnabled
public static java.lang.Boolean isPropertyEnabled(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Check property name is defined and set to true.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look up- Returns:
- value when the propertyName is defined or return null
-
isPropertyEnabled
public static boolean isPropertyEnabled(java.util.Dictionary<?,?> properties, java.lang.String propertyName, boolean defaultValue)
Check property name is defined as set to true.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look updefaultValue
- 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 java.lang.Long getLongProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Long property from the propertyName Return null if propertyName is not found.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look up- Returns:
- value when the propertyName is defined or return null
-
getFloatProperty
public static java.lang.Float getFloatProperty(java.util.Dictionary<?,?> properties, java.lang.String propertyName)
Get Float property from the propertyName Return null if propertyName is not found.- Parameters:
properties
- properties to be looked uppropertyName
- the name of the property to look up- Returns:
- value when the propertyName is defined or return null
-
retryable
public static <U,V> java.util.function.Function<U,V> retryable(java.util.function.Function<U,V> base, java.lang.Class<? extends java.lang.Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
Returns a function that retries execution on failure.- Type Parameters:
U
- type of function inputV
- type of function output- Parameters:
base
- base functionexceptionClass
- type of exception for which to retrymaxRetries
- max number of retries before giving upmaxDelayBetweenRetries
- max delay between successive retries. The actual delay is randomly picked from the interval (0, maxDelayBetweenRetries]- Returns:
- function
-
retryable
public static <V> java.util.function.Supplier<V> retryable(java.util.function.Supplier<V> base, java.lang.Class<? extends java.lang.Throwable> exceptionClass, int maxRetries, int maxDelayBetweenRetries)
Returns a Supplier that retries execution on failure.- Type Parameters:
V
- type of supplied result- Parameters:
base
- base supplierexceptionClass
- type of exception for which to retrymaxRetries
- max number of retries before giving upmaxDelayBetweenRetries
- 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 millisnanos
- number of nanos
-
removeDirectory
public static void removeDirectory(java.lang.String path) throws java.io.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:
java.io.IOException
- if unable to remove contents
-
removeDirectory
public static void removeDirectory(java.io.File dir) throws java.io.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:
java.io.IOException
- if unable to remove contents
-
timeAgo
public static java.lang.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(java.lang.String src, java.lang.String dst) throws java.io.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 copieddst
- destination directory to be removed- Throws:
java.io.IOException
- if unable to remove contents
-
copyDirectory
public static void copyDirectory(java.io.File src, java.io.File dst) throws java.io.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 copieddst
- destination directory to be removed- Throws:
java.io.IOException
- if unable to remove contents
-
futureGetOrElse
public static <T> T futureGetOrElse(java.util.concurrent.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
- futuredefaultValue
- default value- Returns:
- future value when complete or if future completes exceptionally returns the defaultValue.
-
futureGetOrElse
public static <T> T futureGetOrElse(java.util.concurrent.Future<T> future, long timeout, java.util.concurrent.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
- futuretimeout
- time to wait for successful completiontimeUnit
- time unitdefaultValue
- default value- Returns:
- future value when complete or if future completes exceptionally returns the defaultValue.
-
exceptionalFuture
public static <T> java.util.concurrent.CompletableFuture<T> exceptionalFuture(java.lang.Throwable t)
Returns a future that is completed exceptionally.- Type Parameters:
T
- future value type- Parameters:
t
- exception- Returns:
- future
-
orderedFuture
public static <T> java.util.concurrent.CompletableFuture<T> orderedFuture(java.util.concurrent.CompletableFuture<T> future, java.util.concurrent.Executor orderedExecutor, java.util.concurrent.Executor threadPoolExecutor)
Returns a future that's completed using the givenorderedExecutor
if the future is not blocked or the giventhreadPoolExecutor
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 aCompletableFuture.get()
orCompletableFuture.join()
call, completion of the returned future will be done using the providedthreadPoolExecutor
.- Type Parameters:
T
- future value type- Parameters:
future
- the future to convert into an asynchronous futureorderedExecutor
- the ordered executor with which to attempt to complete the futurethreadPoolExecutor
- the backup executor with which to complete blocked futures- Returns:
- a new completable future to be completed using the provided
executor
once the providedfuture
is complete
-
allOf
public static <T> java.util.concurrent.CompletableFuture<java.util.List<T>> allOf(java.util.List<java.util.concurrent.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> java.util.concurrent.CompletableFuture<T> allOf(java.util.List<java.util.concurrent.CompletableFuture<T>> futures, java.util.function.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 CompletableFuturesreducer
- reducer for computing the resultemptyValue
- 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> java.util.concurrent.CompletableFuture<T> firstOf(java.util.List<java.util.concurrent.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> java.util.concurrent.CompletableFuture<T> firstOf(java.util.List<java.util.concurrent.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 CompletableFuturespositiveResultMatcher
- matcher to identify a positive resultnegativeResult
- value to complete with if none of the futures complete with a positive result- Returns:
- a new CompletableFuture
-
byteBuffertoArray
public static byte[] byteBuffertoArray(java.nio.ByteBuffer buffer)
Returns the contents ofByteBuffer
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> java.util.stream.Stream<T> stream(java.lang.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> java.util.stream.Stream<T> stream(java.util.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 java.time.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 java.lang.Comparable<? super C>> C min(C l, C r)
Returns smaller of the two Comparable values.- Type Parameters:
C
- Comparable type- Parameters:
l
- an argumentr
- another argument- Returns:
- the smaller of
l
orr
- Throws:
java.lang.NullPointerException
- if any of the arguments were null.
-
max
public static <C extends java.lang.Comparable<? super C>> C max(C l, C r)
Returns larger of the two Comparable values.- Type Parameters:
C
- Comparable type- Parameters:
l
- an argumentr
- another argument- Returns:
- the larger of
l
orr
- Throws:
java.lang.NullPointerException
- if any of the arguments were null.
-
log
public static void log(org.slf4j.Logger logger, Tools.LogLevel level, java.lang.String format, java.lang.Object... args)
Wrapper function that enables logger invocation with log level as a parameter.- Parameters:
logger
- loggerlevel
- log levelformat
- format stringargs
- objects
-
-