blob: 1246ec9e5d40aec35debbd1d7d980ea9fd884491 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
Thomas Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
Thomas Vachuska24c849c2014-10-27 09:53:05 -070015 */
tom5f38b3a2014-08-27 23:50:54 -070016package org.onlab.util;
17
Ray Milkey86ee5e82018-04-02 15:33:07 -070018import com.fasterxml.jackson.databind.ObjectMapper;
19import com.fasterxml.jackson.databind.node.ObjectNode;
Jonathan Hartcc962d82016-08-09 16:52:22 -070020import com.google.common.base.Charsets;
21import com.google.common.base.Strings;
22import com.google.common.collect.Lists;
23import com.google.common.primitives.UnsignedLongs;
24import com.google.common.util.concurrent.ThreadFactoryBuilder;
25import org.slf4j.Logger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080026
tom53efab52014-10-07 17:43:48 -070027import java.io.File;
tom53efab52014-10-07 17:43:48 -070028import java.io.IOException;
Ray Milkey86ee5e82018-04-02 15:33:07 -070029import java.io.InputStream;
Madan Jampani27b69c62015-05-15 15:49:02 -070030import java.nio.ByteBuffer;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080031import java.nio.file.FileVisitResult;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080032import java.nio.file.Files;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080033import java.nio.file.Path;
34import java.nio.file.Paths;
35import java.nio.file.SimpleFileVisitor;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080036import java.nio.file.StandardCopyOption;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080037import java.nio.file.attribute.BasicFileAttributes;
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080038import java.security.SecureRandom;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070039import java.time.Instant;
40import java.time.OffsetDateTime;
41import java.time.ZoneId;
Madan Jampani27b69c62015-05-15 15:49:02 -070042import java.util.Arrays;
Brian O'Connore2eac102015-02-12 18:30:22 -080043import java.util.Collection;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070044import java.util.Dictionary;
tom53efab52014-10-07 17:43:48 -070045import java.util.List;
Sho SHIMIZUb5638b82016-02-11 14:55:05 -080046import java.util.Optional;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070047import java.util.Random;
Ray Milkey36992c82015-11-17 13:31:15 -080048import java.util.Set;
Madan Jampani27b69c62015-05-15 15:49:02 -070049import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070050import java.util.concurrent.ExecutionException;
Jordan Halterman9bdc24f2017-04-19 23:45:12 -070051import java.util.concurrent.Executor;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070052import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070053import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070054import java.util.concurrent.TimeUnit;
55import java.util.concurrent.TimeoutException;
Madan Jampani307a21e2016-09-01 15:49:47 -070056import java.util.function.BinaryOperator;
Madan Jampania29c6772015-08-17 13:17:07 -070057import java.util.function.Function;
58import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080059import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070060import java.util.stream.Stream;
61import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070062
Yuta HIGUCHI47d96092017-11-17 14:05:26 -080063import static com.google.common.base.Preconditions.checkNotNull;
Jonathan Hartcc962d82016-08-09 16:52:22 -070064import static java.nio.file.Files.delete;
65import static java.nio.file.Files.walkFileTree;
66import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
67import static org.slf4j.LoggerFactory.getLogger;
Ray Milkey705d9bc2014-11-18 08:19:00 -080068
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080069/**
70 * Miscellaneous utility methods.
71 */
tom5f38b3a2014-08-27 23:50:54 -070072public abstract class Tools {
73
74 private Tools() {
75 }
76
Thomas Vachuska02aeb032015-01-06 22:36:30 -080077 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080078
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080079 private static Random random = new SecureRandom();
Thomas Vachuskaadba1522015-06-04 15:08:30 -070080
Ray Milkey86ee5e82018-04-02 15:33:07 -070081 private static final String INPUT_JSON_CANNOT_BE_NULL = "Input JSON cannot be null";
82
tom5f38b3a2014-08-27 23:50:54 -070083 /**
84 * Returns a thread factory that produces threads named according to the
85 * supplied name pattern.
86 *
87 * @param pattern name pattern
88 * @return thread factory
89 */
90 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080091 return new ThreadFactoryBuilder()
92 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080093 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
94 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080095 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080096
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080097 /**
98 * Returns a thread factory that produces threads named according to the
99 * supplied name pattern and from the specified thread-group. The thread
100 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800101 * {@code onos/intent}. The thread names will be produced by converting
102 * the thread group name into dash-delimited format and pre-pended to the
103 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -0800104 *
105 * @param groupName group name in slash-delimited format to indicate hierarchy
106 * @param pattern name pattern
107 * @return thread factory
108 */
109 public static ThreadFactory groupedThreads(String groupName, String pattern) {
Jian Li03e9fb02016-03-01 17:13:54 -0800110 return groupedThreads(groupName, pattern, log);
111 }
112
113 /**
114 * Returns a thread factory that produces threads named according to the
115 * supplied name pattern and from the specified thread-group. The thread
116 * group name is expected to be specified in slash-delimited format, e.g.
117 * {@code onos/intent}. The thread names will be produced by converting
118 * the thread group name into dash-delimited format and pre-pended to the
119 * specified pattern. If a logger is specified, it will use the logger to
120 * print out the exception if it has any.
121 *
122 * @param groupName group name in slash-delimited format to indicate hierarchy
123 * @param pattern name pattern
124 * @param logger logger
125 * @return thread factory
126 */
127 public static ThreadFactory groupedThreads(String groupName, String pattern, Logger logger) {
128 if (logger == null) {
129 return groupedThreads(groupName, pattern);
130 }
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -0800131 return new ThreadFactoryBuilder()
132 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800133 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Jian Li03e9fb02016-03-01 17:13:54 -0800134 .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e))
Thomas Vachuska480adad2015-03-06 10:27:09 -0800135 .build();
tom5f38b3a2014-08-27 23:50:54 -0700136 }
137
tom782a7cf2014-09-11 23:58:38 -0700138 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800139 * Returns a thread factory that produces threads with MIN_PRIORITY.
140 *
141 * @param factory backing ThreadFactory
142 * @return thread factory
143 */
144 public static ThreadFactory minPriority(ThreadFactory factory) {
145 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800146 .setThreadFactory(factory)
147 .setPriority(Thread.MIN_PRIORITY)
148 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800149 }
150
151 /**
Yuta HIGUCHIa2a11cd2016-12-19 14:19:11 -0800152 * Returns a thread factory that produces threads with MAX_PRIORITY.
153 *
154 * @param factory backing ThreadFactory
155 * @return thread factory
156 */
157 public static ThreadFactory maxPriority(ThreadFactory factory) {
158 return new ThreadFactoryBuilder()
159 .setThreadFactory(factory)
160 .setPriority(Thread.MAX_PRIORITY)
161 .build();
162 }
163
164 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800165 * Returns true if the collection is null or is empty.
166 *
167 * @param collection collection to test
168 * @return true if null or empty; false otherwise
169 */
Yuta HIGUCHI488a94c2018-01-26 17:24:09 -0800170 public static boolean isNullOrEmpty(Collection<?> collection) {
Brian O'Connore2eac102015-02-12 18:30:22 -0800171 return collection == null || collection.isEmpty();
172 }
173
174 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700175 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700176 * not found exception.
177 *
178 * @param item item to check
179 * @param message not found message
180 * @param <T> item type
181 * @return item if not null
182 * @throws org.onlab.util.ItemNotFoundException if item is null
183 */
184 public static <T> T nullIsNotFound(T item, String message) {
185 if (item == null) {
186 throw new ItemNotFoundException(message);
187 }
188 return item;
189 }
190
191 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800192 * Returns the specified set if the set is not null and not empty;
193 * otherwise throws a not found exception.
194 *
195 * @param item set to check
196 * @param message not found message
197 * @param <T> Set item type
198 * @return item if not null and not empty
199 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
200 */
201 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
202 if (item == null || item.isEmpty()) {
203 throw new ItemNotFoundException(message);
204 }
205 return item;
206 }
207
208 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700209 * Returns the specified item if that item is not null; otherwise throws
210 * bad argument exception.
211 *
212 * @param item item to check
213 * @param message not found message
214 * @param <T> item type
215 * @return item if not null
216 * @throws IllegalArgumentException if item is null
217 */
218 public static <T> T nullIsIllegal(T item, String message) {
219 if (item == null) {
220 throw new IllegalArgumentException(message);
221 }
222 return item;
223 }
224
225 /**
Ray Milkey86ee5e82018-04-02 15:33:07 -0700226 * Utility to convert a mapper and an input stream into a JSON tree,
227 * and be tolerant of a null tree being returned.
228 *
229 * @param mapper JSON object mapper
230 * @param stream IO stream containing the JSON
231 * @return object node for the given
232 * @throws IOException if JSON parsing fails
233 */
234 public static ObjectNode readTreeFromStream(ObjectMapper mapper, InputStream stream) throws IOException {
235 return nullIsIllegal((ObjectNode) mapper.readTree(stream), INPUT_JSON_CANNOT_BE_NULL);
236 }
237
238 /**
tom782a7cf2014-09-11 23:58:38 -0700239 * Converts a string from hex to long.
240 *
241 * @param string hex number in string form; sans 0x
242 * @return long value
243 */
244 public static long fromHex(String string) {
245 return UnsignedLongs.parseUnsignedLong(string, 16);
246 }
247
248 /**
249 * Converts a long value to hex string; 16 wide and sans 0x.
250 *
251 * @param value long value
252 * @return hex string
253 */
254 public static String toHex(long value) {
255 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
256 }
257
258 /**
259 * Converts a long value to hex string; 16 wide and sans 0x.
260 *
261 * @param value long value
262 * @param width string width; zero padded
263 * @return hex string
264 */
265 public static String toHex(long value, int width) {
266 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
267 }
tomf110fff2014-09-26 00:38:18 -0700268
269 /**
Jonathan Hartcc962d82016-08-09 16:52:22 -0700270 * Returns a string encoding in hex of the given long value with prefix
271 * '0x'.
272 *
273 * @param value long value to encode as hex string
274 * @return hex string
275 */
276 public static String toHexWithPrefix(long value) {
277 return "0x" + Long.toHexString(value);
278 }
279
280 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800281 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800282 * @param input input string
283 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800284 */
285 public static byte[] getBytesUtf8(String input) {
286 return input.getBytes(Charsets.UTF_8);
287 }
288
289 /**
290 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800291 * @param input input byte array
292 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800293 */
294 public static String toStringUtf8(byte[] input) {
295 return new String(input, Charsets.UTF_8);
296 }
297
298 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700299 * Returns a copy of the input byte array.
300 *
301 * @param original input
302 * @return copy of original
303 */
304 public static byte[] copyOf(byte[] original) {
305 return Arrays.copyOf(original, original.length);
306 }
307
308 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700309 * Get property as a string value.
310 *
311 * @param properties properties to be looked up
312 * @param propertyName the name of the property to look up
313 * @return value when the propertyName is defined or return null
314 */
315 public static String get(Dictionary<?, ?> properties, String propertyName) {
316 Object v = properties.get(propertyName);
317 String s = (v instanceof String) ? (String) v :
318 v != null ? v.toString() : null;
319 return Strings.isNullOrEmpty(s) ? null : s.trim();
320 }
321
322 /**
Jian Lid9b5f552016-03-11 18:15:31 -0800323 * Get Integer property from the propertyName
324 * Return null if propertyName is not found.
325 *
326 * @param properties properties to be looked up
327 * @param propertyName the name of the property to look up
328 * @return value when the propertyName is defined or return null
329 */
330 public static Integer getIntegerProperty(Dictionary<?, ?> properties,
331 String propertyName) {
332 Integer value;
333 try {
334 String s = get(properties, propertyName);
335 value = Strings.isNullOrEmpty(s) ? null : Integer.valueOf(s);
336 } catch (NumberFormatException | ClassCastException e) {
337 value = null;
338 }
339 return value;
340 }
341
342 /**
343 * Get Integer property from the propertyName
344 * Return default value if propertyName is not found.
345 *
346 * @param properties properties to be looked up
347 * @param propertyName the name of the property to look up
348 * @param defaultValue the default value that to be assigned
349 * @return value when the propertyName is defined or return default value
350 */
351 public static int getIntegerProperty(Dictionary<?, ?> properties,
352 String propertyName,
353 int defaultValue) {
354 try {
355 String s = get(properties, propertyName);
356 return Strings.isNullOrEmpty(s) ? defaultValue : Integer.valueOf(s);
357 } catch (NumberFormatException | ClassCastException e) {
358 return defaultValue;
359 }
360 }
361
362 /**
363 * Check property name is defined and set to true.
364 *
365 * @param properties properties to be looked up
366 * @param propertyName the name of the property to look up
367 * @return value when the propertyName is defined or return null
368 */
369 public static Boolean isPropertyEnabled(Dictionary<?, ?> properties,
370 String propertyName) {
371 Boolean value;
372 try {
373 String s = get(properties, propertyName);
374 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
375 } catch (ClassCastException e) {
376 value = null;
377 }
378 return value;
379 }
380
381 /**
382 * Check property name is defined as set to true.
383 *
384 * @param properties properties to be looked up
385 * @param propertyName the name of the property to look up
386 * @param defaultValue the default value that to be assigned
387 * @return value when the propertyName is defined or return the default value
388 */
389 public static boolean isPropertyEnabled(Dictionary<?, ?> properties,
390 String propertyName,
391 boolean defaultValue) {
392 try {
393 String s = get(properties, propertyName);
394 return Strings.isNullOrEmpty(s) ? defaultValue : Boolean.valueOf(s);
395 } catch (ClassCastException e) {
396 return defaultValue;
397 }
398 }
399
400 /**
tomf110fff2014-09-26 00:38:18 -0700401 * Suspends the current thread for a specified number of millis.
402 *
403 * @param ms number of millis
404 */
405 public static void delay(int ms) {
406 try {
407 Thread.sleep(ms);
408 } catch (InterruptedException e) {
Ray Milkey5c7d4882018-02-05 14:50:39 -0800409 Thread.currentThread().interrupt();
Ray Milkey986a47a2018-01-25 11:38:51 -0800410 throw new IllegalStateException("Interrupted", e);
tomf110fff2014-09-26 00:38:18 -0700411 }
412 }
413
tom53efab52014-10-07 17:43:48 -0700414 /**
sdn94b00152016-08-30 02:12:32 -0700415 * Get Long property from the propertyName
416 * Return null if propertyName is not found.
417 *
418 * @param properties properties to be looked up
419 * @param propertyName the name of the property to look up
420 * @return value when the propertyName is defined or return null
421 */
422 public static Long getLongProperty(Dictionary<?, ?> properties,
423 String propertyName) {
424 Long value;
425 try {
426 String s = get(properties, propertyName);
427 value = Strings.isNullOrEmpty(s) ? null : Long.valueOf(s);
428 } catch (NumberFormatException | ClassCastException e) {
429 value = null;
430 }
431 return value;
432 }
433
434 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700435 * Returns a function that retries execution on failure.
436 * @param base base function
437 * @param exceptionClass type of exception for which to retry
438 * @param maxRetries max number of retries before giving up
439 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
440 * the interval (0, maxDelayBetweenRetries]
441 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700442 * @param <U> type of function input
443 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700444 */
445 public static <U, V> Function<U, V> retryable(Function<U, V> base,
446 Class<? extends Throwable> exceptionClass,
447 int maxRetries,
448 int maxDelayBetweenRetries) {
449 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
450 }
451
452 /**
453 * Returns a Supplier that retries execution on failure.
454 * @param base base supplier
455 * @param exceptionClass type of exception for which to retry
456 * @param maxRetries max number of retries before giving up
457 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
458 * the interval (0, maxDelayBetweenRetries]
459 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700460 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700461 */
462 public static <V> Supplier<V> retryable(Supplier<V> base,
463 Class<? extends Throwable> exceptionClass,
464 int maxRetries,
465 int maxDelayBetweenRetries) {
466 return () -> new RetryingFunction<>(v -> base.get(),
467 exceptionClass,
468 maxRetries,
469 maxDelayBetweenRetries).apply(null);
470 }
471
472 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700473 * Suspends the current thread for a random number of millis between 0 and
474 * the indicated limit.
475 *
476 * @param ms max number of millis
477 */
478 public static void randomDelay(int ms) {
479 try {
480 Thread.sleep(random.nextInt(ms));
481 } catch (InterruptedException e) {
Ray Milkey5c7d4882018-02-05 14:50:39 -0800482 Thread.currentThread().interrupt();
Ray Milkey986a47a2018-01-25 11:38:51 -0800483 throw new IllegalStateException("Interrupted", e);
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700484 }
485 }
486
487 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700488 * Suspends the current thread for a specified number of millis and nanos.
489 *
490 * @param ms number of millis
491 * @param nanos number of nanos
492 */
493 public static void delay(int ms, int nanos) {
494 try {
495 Thread.sleep(ms, nanos);
496 } catch (InterruptedException e) {
Ray Milkey5c7d4882018-02-05 14:50:39 -0800497 Thread.currentThread().interrupt();
Ray Milkey986a47a2018-01-25 11:38:51 -0800498 throw new IllegalStateException("Interrupted", e);
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700499 }
500 }
501
502 /**
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800503 * Purges the specified directory path.&nbsp;Use with great caution since
504 * no attempt is made to check for symbolic links, which could result in
505 * deletion of unintended files.
506 *
507 * @param path directory to be removed
508 * @throws java.io.IOException if unable to remove contents
509 */
510 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800511 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700512 File dir = new File(path);
513 if (dir.exists() && dir.isDirectory()) {
514 walkFileTree(Paths.get(path), visitor);
515 if (visitor.exception != null) {
516 throw visitor.exception;
517 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800518 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800519 }
520
521 /**
522 * Purges the specified directory path.&nbsp;Use with great caution since
523 * no attempt is made to check for symbolic links, which could result in
524 * deletion of unintended files.
525 *
526 * @param dir directory to be removed
527 * @throws java.io.IOException if unable to remove contents
528 */
529 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800530 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700531 if (dir.exists() && dir.isDirectory()) {
532 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
533 if (visitor.exception != null) {
534 throw visitor.exception;
535 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800536 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800537 }
538
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800539 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800540 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800541
542 private IOException exception;
543
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800544 @Override
545 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
546 throws IOException {
547 if (attributes.isRegularFile()) {
548 delete(file);
549 }
550 return FileVisitResult.CONTINUE;
551 }
552
553 @Override
554 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
555 throws IOException {
556 delete(directory);
557 return FileVisitResult.CONTINUE;
558 }
559
560 @Override
561 public FileVisitResult visitFileFailed(Path file, IOException ioe)
562 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800563 this.exception = ioe;
564 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800565 }
566 }
567
Madan Jampani30a57f82015-03-02 12:19:41 -0800568 /**
569 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800570 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800571 * @param unixTime system time in millis
572 * @return human friendly time ago
573 */
574 public static String timeAgo(long unixTime) {
575 long deltaMillis = System.currentTimeMillis() - unixTime;
576 long secondsSince = (long) (deltaMillis / 1000.0);
577 long minsSince = (long) (deltaMillis / (1000.0 * 60));
578 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
579 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
580 if (daysSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800581 return String.format("%dd%dh ago", daysSince, hoursSince - daysSince * 24);
Madan Jampani30a57f82015-03-02 12:19:41 -0800582 } else if (hoursSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800583 return String.format("%dh%dm ago", hoursSince, minsSince - hoursSince * 60);
Madan Jampani30a57f82015-03-02 12:19:41 -0800584 } else if (minsSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800585 return String.format("%dm%ds ago", minsSince, secondsSince - minsSince * 60);
Madan Jampani30a57f82015-03-02 12:19:41 -0800586 } else if (secondsSince > 0) {
587 return String.format("%ds ago", secondsSince);
588 } else {
589 return "just now";
590 }
591 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800592
593 /**
594 * Copies the specified directory path.&nbsp;Use with great caution since
595 * no attempt is made to check for symbolic links, which could result in
596 * copy of unintended files.
597 *
598 * @param src directory to be copied
599 * @param dst destination directory to be removed
600 * @throws java.io.IOException if unable to remove contents
601 */
602 public static void copyDirectory(String src, String dst) throws IOException {
603 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
604 }
605
606 /**
607 * Copies the specified directory path.&nbsp;Use with great caution since
608 * no attempt is made to check for symbolic links, which could result in
609 * copy of unintended files.
610 *
611 * @param src directory to be copied
612 * @param dst destination directory to be removed
613 * @throws java.io.IOException if unable to remove contents
614 */
615 public static void copyDirectory(File src, File dst) throws IOException {
616 walkFileTree(Paths.get(src.getAbsolutePath()),
617 new DirectoryCopier(src.getAbsolutePath(),
618 dst.getAbsolutePath()));
619 }
620
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700621 /**
622 * Returns the future value when complete or if future
623 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700624 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700625 * @param future future
626 * @param defaultValue default value
627 * @param <T> future value type
628 * @return future value when complete or if future
629 * completes exceptionally returns the defaultValue.
630 */
631 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
632 try {
633 return future.get();
634 } catch (InterruptedException e) {
635 Thread.currentThread().interrupt();
636 return defaultValue;
637 } catch (ExecutionException e) {
638 return defaultValue;
639 }
640 }
641
642 /**
643 * Returns the future value when complete or if future
644 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700645 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700646 * @param future future
647 * @param timeout time to wait for successful completion
648 * @param timeUnit time unit
649 * @param defaultValue default value
650 * @param <T> future value type
651 * @return future value when complete or if future
652 * completes exceptionally returns the defaultValue.
653 */
654 public static <T> T futureGetOrElse(Future<T> future,
655 long timeout,
656 TimeUnit timeUnit,
657 T defaultValue) {
658 try {
659 return future.get(timeout, timeUnit);
660 } catch (InterruptedException e) {
661 Thread.currentThread().interrupt();
662 return defaultValue;
663 } catch (ExecutionException | TimeoutException e) {
664 return defaultValue;
665 }
666 }
667
Madan Jampani27b69c62015-05-15 15:49:02 -0700668 /**
669 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700670 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700671 * @param t exception
672 * @param <T> future value type
673 * @return future
674 */
675 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
676 CompletableFuture<T> future = new CompletableFuture<>();
677 future.completeExceptionally(t);
678 return future;
679 }
680
681 /**
Jordan Halterman046faeb2017-05-01 15:10:13 -0700682 * Returns a future that's completed using the given {@code orderedExecutor} if the future is not blocked or the
683 * given {@code threadPoolExecutor} if the future is blocked.
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700684 * <p>
Jordan Halterman046faeb2017-05-01 15:10:13 -0700685 * This method allows futures to maintain single-thread semantics via the provided {@code orderedExecutor} while
686 * ensuring user code can block without blocking completion of futures. When the returned future or any of its
687 * descendants is blocked on a {@link CompletableFuture#get()} or {@link CompletableFuture#join()} call, completion
688 * of the returned future will be done using the provided {@code threadPoolExecutor}.
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700689 *
690 * @param future the future to convert into an asynchronous future
Jordan Halterman046faeb2017-05-01 15:10:13 -0700691 * @param orderedExecutor the ordered executor with which to attempt to complete the future
692 * @param threadPoolExecutor the backup executor with which to complete blocked futures
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700693 * @param <T> future value type
694 * @return a new completable future to be completed using the provided {@code executor} once the provided
695 * {@code future} is complete
696 */
Jordan Halterman046faeb2017-05-01 15:10:13 -0700697 public static <T> CompletableFuture<T> orderedFuture(
698 CompletableFuture<T> future,
699 Executor orderedExecutor,
700 Executor threadPoolExecutor) {
Jordan Haltermane265d372017-05-17 22:40:47 -0700701 if (future.isDone()) {
702 return future;
703 }
704
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700705 BlockingAwareFuture<T> newFuture = new BlockingAwareFuture<>();
Jordan Halterman046faeb2017-05-01 15:10:13 -0700706 future.whenComplete((result, error) -> {
707 Runnable completer = () -> {
708 if (future.isCompletedExceptionally()) {
709 newFuture.completeExceptionally(error);
710 } else {
711 newFuture.complete(result);
712 }
713 };
714
715 if (newFuture.isBlocked()) {
716 threadPoolExecutor.execute(completer);
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700717 } else {
Jordan Halterman046faeb2017-05-01 15:10:13 -0700718 orderedExecutor.execute(completer);
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700719 }
Jordan Halterman046faeb2017-05-01 15:10:13 -0700720 });
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700721 return newFuture;
722 }
723
724 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800725 * Returns a new CompletableFuture completed with a list of computed values
726 * when all of the given CompletableFuture complete.
727 *
728 * @param futures the CompletableFutures
729 * @param <T> value type of CompletableFuture
730 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
731 */
732 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
733 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
734 .thenApply(v -> futures.stream()
735 .map(CompletableFuture::join)
736 .collect(Collectors.toList())
737 );
738 }
739
740 /**
Madan Jampani307a21e2016-09-01 15:49:47 -0700741 * Returns a new CompletableFuture completed by reducing a list of computed values
742 * when all of the given CompletableFuture complete.
743 *
744 * @param futures the CompletableFutures
745 * @param reducer reducer for computing the result
746 * @param emptyValue zero value to be returned if the input future list is empty
747 * @param <T> value type of CompletableFuture
748 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
749 */
750 public static <T> CompletableFuture<T> allOf(List<CompletableFuture<T>> futures,
751 BinaryOperator<T> reducer,
752 T emptyValue) {
753 return Tools.allOf(futures)
754 .thenApply(resultList -> resultList.stream().reduce(reducer).orElse(emptyValue));
755 }
756
757 /**
Jordan Halterman281dbf32018-06-15 17:46:28 -0700758 * Returns a new CompletableFuture completed with the first result from a list of futures. If no future
759 * is completed successfully, the returned future will be completed with the first exception.
760 *
761 * @param futures the input futures
762 * @param <T> future result type
763 * @return a new CompletableFuture
764 */
765 public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures) {
766 CompletableFuture<T> resultFuture = new CompletableFuture<>();
767 CompletableFuture.allOf(futures.stream()
768 .map(future -> future.thenAccept(r -> resultFuture.complete(r)))
769 .toArray(CompletableFuture[]::new))
770 .whenComplete((r, e) -> {
771 if (!resultFuture.isDone()) {
772 if (e != null) {
773 resultFuture.completeExceptionally(e);
774 } else {
775 resultFuture.complete(null);
776 }
777 }
778 });
779 return resultFuture;
780 }
781
782 /**
Madan Jampani307a21e2016-09-01 15:49:47 -0700783 * Returns a new CompletableFuture completed by with the first positive result from a list of
784 * input CompletableFutures.
785 *
786 * @param futures the input list of CompletableFutures
787 * @param positiveResultMatcher matcher to identify a positive result
788 * @param negativeResult value to complete with if none of the futures complete with a positive result
789 * @param <T> value type of CompletableFuture
790 * @return a new CompletableFuture
791 */
792 public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures,
793 Match<T> positiveResultMatcher,
794 T negativeResult) {
795 CompletableFuture<T> responseFuture = new CompletableFuture<>();
796 Tools.allOf(Lists.transform(futures, future -> future.thenAccept(r -> {
797 if (positiveResultMatcher.matches(r)) {
798 responseFuture.complete(r);
799 }
800 }))).whenComplete((r, e) -> {
801 if (!responseFuture.isDone()) {
802 if (e != null) {
803 responseFuture.completeExceptionally(e);
804 } else {
805 responseFuture.complete(negativeResult);
806 }
807 }
808 });
809 return responseFuture;
810 }
811
812 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700813 * Returns the contents of {@code ByteBuffer} as byte array.
814 * <p>
815 * WARNING: There is a performance cost due to array copy
816 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700817 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700818 * @param buffer byte buffer
819 * @return byte array containing the byte buffer contents
820 */
821 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
822 int length = buffer.remaining();
823 if (buffer.hasArray()) {
824 int offset = buffer.arrayOffset() + buffer.position();
825 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
826 }
827 byte[] bytes = new byte[length];
828 buffer.duplicate().get(bytes);
829 return bytes;
830 }
831
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700832 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700833 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700834 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700835 * @param it iterable to convert
836 * @param <T> type if item
837 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700838 */
839 public static <T> Stream<T> stream(Iterable<T> it) {
840 return StreamSupport.stream(it.spliterator(), false);
841 }
842
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800843 /**
844 * Converts an optional to a stream.
845 *
846 * @param optional optional to convert
847 * @param <T> type of enclosed value
848 * @return optional as a stream
849 */
Sho SHIMIZU6ac20982016-05-04 09:50:54 -0700850 public static <T> Stream<T> stream(Optional<? extends T> optional) {
HIGUCHI Yuta0bc256f2016-05-06 15:28:26 -0700851 return optional.map(x -> Stream.<T>of(x)).orElse(Stream.empty());
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800852 }
853
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800854 // Auxiliary path visitor for recursive directory structure copying.
855 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800856 private Path src;
857 private Path dst;
858 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
859
860 DirectoryCopier(String src, String dst) {
861 this.src = Paths.get(src);
862 this.dst = Paths.get(dst);
863 }
864
865 @Override
866 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
867 Path targetPath = dst.resolve(src.relativize(dir));
868 if (!Files.exists(targetPath)) {
869 Files.createDirectory(targetPath);
870 }
871 return FileVisitResult.CONTINUE;
872 }
873
874 @Override
875 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
876 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
877 return FileVisitResult.CONTINUE;
878 }
879 }
880
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700881 /**
882 * Creates OffsetDateTime instance from epoch milliseconds,
883 * using system default time zone.
884 *
885 * @param epochMillis to convert
886 * @return OffsetDateTime
887 */
888 public static OffsetDateTime defaultOffsetDataTime(long epochMillis) {
889 return OffsetDateTime.ofInstant(Instant.ofEpochMilli(epochMillis),
890 ZoneId.systemDefault());
891 }
892
Yuta HIGUCHI47d96092017-11-17 14:05:26 -0800893 /**
894 * Returns smaller of the two Comparable values.
895 *
896 * @param l an argument
897 * @param r another argument
898 * @return the smaller of {@code l} or {@code r}
899 * @param <C> Comparable type
900 * @throws NullPointerException if any of the arguments were null.
901 */
902 public static <C extends Comparable<? super C>> C min(C l, C r) {
903 checkNotNull(l, "l cannot be null");
904 checkNotNull(r, "r cannot be null");
905 return l.compareTo(r) <= 0 ? l : r;
906 }
907
908 /**
909 * Returns larger of the two Comparable values.
910 *
911 * @param l an argument
912 * @param r another argument
913 * @return the larger of {@code l} or {@code r}
914 * @param <C> Comparable type
915 * @throws NullPointerException if any of the arguments were null.
916 */
917 public static <C extends Comparable<? super C>> C max(C l, C r) {
918 checkNotNull(l, "l cannot be null");
919 checkNotNull(r, "r cannot be null");
920 return l.compareTo(r) >= 0 ? l : r;
921 }
Charles Chan58a33da2018-04-04 17:26:46 -0700922
923 /**
924 * Log level for the customized logger.
925 */
926 public enum LogLevel {
927 TRACE, DEBUG, INFO, WARN, ERROR
928 }
929
930 /**
931 * Wrapper function that enables logger invocation with log level as a parameter.
932 *
933 * @param logger logger
934 * @param level log level
935 * @param format format string
936 * @param args objects
937 */
938 public static void log(Logger logger, LogLevel level, String format, Object... args) {
939 switch (level) {
940 case TRACE:
941 logger.trace(format, args);
942 break;
943 case DEBUG:
944 logger.debug(format, args);
945 break;
946 case INFO:
947 logger.info(format, args);
948 break;
949 case WARN:
950 logger.warn(format, args);
951 break;
952 case ERROR:
953 logger.error(format, args);
954 break;
955 default:
956 log.error("Unknown log level {}", level);
957 break;
958 }
959 }
tom5f38b3a2014-08-27 23:50:54 -0700960}