Class CoreUtils
-
Method Summary
Modifier and TypeMethodDescriptionstatic ThreadaddShutdownHookSafely(Thread shutdownThread) Helper method that safely adds aRuntime.addShutdownHook(Thread)to the JVM that will run when the JVM is shutting down.static ExecutorServiceaddShutdownHookSafely(ExecutorService executorService, Duration shutdownTimeout) Helper method that safely adds aRuntime.addShutdownHook(Thread)to the JVM that will close theexecutorServicewhen the JVM is shutting down.static <T> StringarrayToString(T[] array, Function<T, String> mapper) Turns an array into a string mapping each element to a string and delimits them using a coma.static StringbomAwareToString(byte[] bytes, String contentType) Attempts to convert a byte stream into the properly encoded String.static StringbytesToHexString(byte[] bytes) Converts a byte array into a hex string.static byte[]clone(byte[] source) Creates a copy of the source byte array.static int[]clone(int[] source) Creates a copy of the source int array.static <T> T[]clone(T[] source) Creates a copy of the source array.static HttpHeaderscreateHttpHeadersFromClientOptions(ClientOptions clientOptions) CreatesHttpHeadersfrom the providedClientOptions.static StringdurationToStringWithDays(Duration duration) Converts aDurationto a string in ISO-8601 format with support for a day component.static <T> org.reactivestreams.Publisher<T> extractAndFetch(PagedResponse<T> page, Context context, BiFunction<String, Context, org.reactivestreams.Publisher<T>> content) Deprecated.Use localized implementation.static longextractSizeFromContentRange(String contentRange) Extracts the size from aContent-Rangeheader.static <T> TfindFirstOfType(Object[] args, Class<T> clazz) Returns the first instance of the given class from an array of Objects.static StringgetApplicationId(ClientOptions clientOptions, HttpLogOptions logOptions) Retrieves the application ID from either aClientOptionsorHttpLogOptions.static DurationgetDefaultTimeoutFromEnvironment(Configuration configuration, String timeoutPropertyName, Duration defaultTimeout, ClientLogger logger) Attempts to load an environment configured default timeout.getProperties(String propertiesFileName) Helper method that returns an immutableMapof properties defined inpropertiesFileName.static <T> TgetResultWithTimeout(Future<T> future, Duration timeout) CallsFuture.get(long, TimeUnit)and returns the value if thefuturecompletes before the timeout is triggered.static booleanisNullOrEmpty(CharSequence charSequence) Checks if the character sequence is null or empty.static booleanisNullOrEmpty(Object[] array) Checks if the array is null or empty.static booleanisNullOrEmpty(Collection<?> collection) Checks if the collection is null or empty.static booleanisNullOrEmpty(Map<?, ?> map) Checks if the map is null or empty.static ContextmergeContexts(Context into, Context from) static List<AuthenticateChallenge> parseAuthenticateHeader(String authenticateHeader) Processes an authenticate header, such asHttpHeaderName.WWW_AUTHENTICATEorHttpHeaderName.PROXY_AUTHENTICATE, into a list ofAuthenticateChallenge.static OffsetDateTimeparseBestOffsetDateTime(String dateString) Parses a string into anOffsetDateTime.parseQueryParameters(String queryParameters) Utility method for parsing query parameters one-by-one without the use of string splitting.static UUIDCreates a type 4 (pseudo randomly generated) UUID.static StringstringJoin(String delimiter, List<String> values) Optimized version ofString.join(CharSequence, Iterable)when thevalueshas a small set of object.
-
Method Details
-
clone
public static byte[] clone(byte[] source) Creates a copy of the source byte array.- Parameters:
source- Array to make copy of- Returns:
- A copy of the array, or null if source was null.
-
clone
public static int[] clone(int[] source) Creates a copy of the source int array.- Parameters:
source- Array to make copy of- Returns:
- A copy of the array, or null if source was null.
-
clone
public static <T> T[] clone(T[] source) Creates a copy of the source array.- Type Parameters:
T- Generic representing the type of the source array.- Parameters:
source- Array being copied.- Returns:
- A copy of the array or null if source was null.
-
isNullOrEmpty
Checks if the array is null or empty.- Parameters:
array- Array being checked for nullness or emptiness.- Returns:
- True if the array is null or empty, false otherwise.
-
isNullOrEmpty
Checks if the collection is null or empty.- Parameters:
collection- Collection being checked for nullness or emptiness.- Returns:
- True if the collection is null or empty, false otherwise.
-
isNullOrEmpty
Checks if the map is null or empty.- Parameters:
map- Map being checked for nullness or emptiness.- Returns:
- True if the map is null or empty, false otherwise.
-
isNullOrEmpty
Checks if the character sequence is null or empty.- Parameters:
charSequence- Character sequence being checked for nullness or emptiness.- Returns:
- True if the character sequence is null or empty, false otherwise.
-
arrayToString
Turns an array into a string mapping each element to a string and delimits them using a coma.- Type Parameters:
T- Generic representing the type of the array.- Parameters:
array- Array being formatted to a string.mapper- Function that maps each element to a string.- Returns:
- Array with each element mapped and delimited, otherwise null if the array is empty or null.
-
findFirstOfType
Returns the first instance of the given class from an array of Objects.- Type Parameters:
T- Generic type- Parameters:
args- Array of objects to search through to find the first instance of the given `clazz` type.clazz- The type trying to be found.- Returns:
- The first object of the desired type, otherwise null.
-
extractAndFetch
@Deprecated public static <T> org.reactivestreams.Publisher<T> extractAndFetch(PagedResponse<T> page, Context context, BiFunction<String, Context, org.reactivestreams.Publisher<T>> content) Deprecated.Use localized implementation.Extracts and combines the generic items from all the pages linked together.- Type Parameters:
T- The type of the item being returned by the paged response.- Parameters:
page- The paged response from server holding generic items.context- Metadata that is passed into the function that fetches the items from the next page.content- The function which fetches items from the next page.- Returns:
- The publisher holding all the generic items combined.
-
getProperties
Helper method that returns an immutableMapof properties defined inpropertiesFileName.- Parameters:
propertiesFileName- The file name defining the properties.- Returns:
- an immutable
Map.
-
bomAwareToString
Attempts to convert a byte stream into the properly encoded String.This utility method will attempt to find the encoding for the String in this order.
- Find the byte order mark in the byte array.
- Find the
charsetin theContent-Typeheader. - Default to
UTF-8.
- Parameters:
bytes- Byte array.contentType-Content-Typeheader value.- Returns:
- A string representation of the byte array encoded to the found encoding.
-
getApplicationId
Retrieves the application ID from either aClientOptionsorHttpLogOptions.This method first checks
clientOptionsfor having an application ID thenlogOptions, finally returning null if neither are set.clientOptionsis checked first aslogOptionsapplication ID is deprecated.- Parameters:
clientOptions- TheClientOptions.logOptions- TheHttpLogOptions.- Returns:
- The application ID from either
clientOptionsorlogOptions, if neither are set null.
-
createHttpHeadersFromClientOptions
CreatesHttpHeadersfrom the providedClientOptions.If
clientOptionsis null orClientOptions.getHeaders()doesn't return anyHeadervalues null will be returned.- Parameters:
clientOptions- TheClientOptionsused to create theHttpHeaders.- Returns:
HttpHeaderscontaining theHeadervalues fromClientOptions.getHeaders()ifclientOptionsisn't null and containsHeadervalues, otherwise null.
-
getDefaultTimeoutFromEnvironment
public static Duration getDefaultTimeoutFromEnvironment(Configuration configuration, String timeoutPropertyName, Duration defaultTimeout, ClientLogger logger) Attempts to load an environment configured default timeout.If the environment default timeout isn't configured,
defaultTimeoutwill be returned. If the environment default timeout is a string that isn't parseable byLong.parseLong(String),defaultTimeoutwill be returned. If the environment default timeout is less than 0,Duration.ZEROwill be returned indicated that there is no timeout period.- Parameters:
configuration- The environment configurations.timeoutPropertyName- The default timeout property name.defaultTimeout- The fallback timeout to be used.logger- AClientLoggerto log exceptions.- Returns:
- Either the environment configured default timeout,
defaultTimeoutMillis, or 0.
-
mergeContexts
- Parameters:
into- Context being merged into.from- Context being merged.- Returns:
- A new Context that is the merged Contexts.
- Throws:
NullPointerException- If eitherintoorfromis null.
-
stringJoin
Optimized version ofString.join(CharSequence, Iterable)when thevalueshas a small set of object.- Parameters:
delimiter- Delimiter between the values.values- The values to join.- Returns:
- The
valuesjoined delimited by thedelimiter. - Throws:
NullPointerException- Ifdelimiterorvaluesis null.
-
bytesToHexString
Converts a byte array into a hex string.The hex string returned uses characters
0123456789abcdef, if uppercaseABCDEFis required the returned string will need to beuppercased.If
bytesis null, null will be returned. Ifbyteswas an empty array an empty string is returned.- Parameters:
bytes- The byte array to convert into a hex string.- Returns:
- A hex string representing the
bytesthat were passed, or null ifbyteswere null.
-
extractSizeFromContentRange
Extracts the size from aContent-Rangeheader.The
Content-Rangeheader can take the following forms:<unit> <start>-<end>/<size><unit> <start>-<end>/*<unit>*/<size>
<size>is represented by * this method will return -1.If
contentRangeis null aNullPointerExceptionwill be thrown, if it doesn't contain a size segment (/<size>or /*) anIllegalArgumentExceptionwill be thrown.- Parameters:
contentRange- TheContent-Rangeheader to extract the size from.- Returns:
- The size contained in the
Content-Range, or -1 if the size was *. - Throws:
NullPointerException- IfcontentRangeis null.IllegalArgumentException- IfcontentRangedoesn't contain a<size>segment.NumberFormatException- If the<size>segment of thecontentRangeisn't a valid number.
-
parseQueryParameters
Utility method for parsing query parameters one-by-one without the use of string splitting.This method provides an optimization over parsing query parameters with
String.split(String)or aPatternas it doesn't allocate any arrays to maintain values, instead it parses the query parameters linearly.Query parameter parsing works the following way,
key=valuewill turn into an immutableMap.Entrywhere theMap.Entry.getKey()iskeyand theMap.Entry.getValue()isvalue. For query parameters without a value,key=or justkey, the value will be an empty string.- Parameters:
queryParameters- The query parameter string.- Returns:
- An
Iteratorover the query parameter key-value pairs.
-
randomUuid
Creates a type 4 (pseudo randomly generated) UUID.The
UUIDis generated using a non-cryptographically strong pseudo random number generator.- Returns:
- A randomly generated
UUID.
-
getResultWithTimeout
public static <T> T getResultWithTimeout(Future<T> future, Duration timeout) throws InterruptedException, ExecutionException, TimeoutException CallsFuture.get(long, TimeUnit)and returns the value if thefuturecompletes before the timeout is triggered. If the timeout is triggered, thefutureiscancelledinterrupting the execution of the task that theFuturerepresented.If the timeout is
Duration.isZero()or isDuration.isNegative()then the timeout will be ignored and an infinite timeout will be used.- Type Parameters:
T- The type of value returned by thefuture.- Parameters:
future- TheFutureto get the value from.timeout- The timeout value. If the timeout isDuration.isZero()or isDuration.isNegative()then the timeout will be ignored and an infinite timeout will be used.- Returns:
- The value from the
future. - Throws:
NullPointerException- Iffutureis null.CancellationException- If the computation was cancelled.ExecutionException- If the computation threw an exception.InterruptedException- If the current thread was interrupted while waiting.TimeoutException- If the wait timed out.RuntimeException- If thefuturethrew an exception during processing.Error- If thefuturethrew anErrorduring processing.
-
addShutdownHookSafely
public static ExecutorService addShutdownHookSafely(ExecutorService executorService, Duration shutdownTimeout) Helper method that safely adds aRuntime.addShutdownHook(Thread)to the JVM that will close theexecutorServicewhen the JVM is shutting down.Runtime.addShutdownHook(Thread)checks for security privileges and will throw an exception if the proper security isn't available. So, if running with a security manager, settingAZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGEto true will have this method use access controller to add the shutdown hook with privileged permissions.If
executorServiceis null, no shutdown hook will be added and this method will return null.The
shutdownTimeoutis the amount of time to wait for theexecutorServiceto shutdown. If theexecutorServicedoesn't shutdown within half the timeout, it will be forcefully shutdown.- Parameters:
executorService- TheExecutorServiceto shutdown when the JVM is shutting down.shutdownTimeout- The amount of time to wait for theexecutorServiceto shutdown.- Returns:
- The
executorServicethat was passed in. - Throws:
NullPointerException- IfshutdownTimeoutis null.IllegalArgumentException- IfshutdownTimeoutis zero or negative.
-
addShutdownHookSafely
Helper method that safely adds aRuntime.addShutdownHook(Thread)to the JVM that will run when the JVM is shutting down.Runtime.addShutdownHook(Thread)checks for security privileges and will throw an exception if the proper security isn't available. So, if running with a security manager, settingAZURE_ENABLE_SHUTDOWN_HOOK_WITH_PRIVILEGEto true will have this method use access controller to add the shutdown hook with privileged permissions.If
shutdownThreadis null, no shutdown hook will be added and this method will return null.- Parameters:
shutdownThread- TheThreadthat will be added as ashutdown hook.- Returns:
- The
Threadthat was passed in.
-
durationToStringWithDays
Converts aDurationto a string in ISO-8601 format with support for a day component.Duration.toString()doesn't use a day component, so if the duration is greater than 24 hours it would return an ISO-8601 duration string likePT48H. This method returns an ISO-8601 duration string with a day component if the duration is greater than 24 hours, such asP2Dinstead ofPT48H. -
parseBestOffsetDateTime
Parses a string into anOffsetDateTime.If
dateStringis null, null will be returned.This method attempts to parse the
dateStringusingDateTimeFormatter.parseBest(CharSequence, TemporalQuery[]). This will useOffsetDateTime.from(TemporalAccessor)as the first attempt and will fall back toLocalDateTime.from(TemporalAccessor)with setting the offset asZoneOffset.UTC.- Parameters:
dateString- The string to parse into anOffsetDateTime.- Returns:
- The parsed
OffsetDateTime, or null ifdateStringwas null. - Throws:
DateTimeException- If thedateStringcannot be parsed by eitherOffsetDateTime.from(TemporalAccessor)orLocalDateTime.from(TemporalAccessor).
-
parseAuthenticateHeader
Processes an authenticate header, such asHttpHeaderName.WWW_AUTHENTICATEorHttpHeaderName.PROXY_AUTHENTICATE, into a list ofAuthenticateChallenge.If the
authenticateHeaderis null or empty an empty list will be returned.This method will parse the authenticate header as plainly as possible, meaning no casing will be changed on the scheme and no decoding will be done on the parameters. The only processing done is removal of quotes around parameter values and backslashes escaping values. Ex,
"va\"lue"will be parsed asva"lue.In addition to processing as plainly as possible, this method will not validate the authenticate header, it will only parse it. Though, if the authenticate header has syntax errors an
IllegalStateExceptionwill be thrown.A list of
AuthenticateChallengewill be returned as it is valid for multiple authenticate challenges to use the same scheme, therefore a map cannot be used as the scheme would be the key and only one challenge would be stored.- Parameters:
authenticateHeader- The authenticate header to be parsed.- Returns:
- A list of authenticate challenges.
- Throws:
IllegalArgumentException- If theauthenticateHeaderhas syntax errors.
-