blob: 4b2cac99d5dfbd9d4e1dd8486d4fcab9b0445129 [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
Jonathan Hartcc962d82016-08-09 16:52:22 -070018import com.google.common.base.Charsets;
19import com.google.common.base.Strings;
20import com.google.common.collect.Lists;
21import com.google.common.primitives.UnsignedLongs;
22import com.google.common.util.concurrent.ThreadFactoryBuilder;
23import org.slf4j.Logger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080024
tom53efab52014-10-07 17:43:48 -070025import java.io.File;
tom53efab52014-10-07 17:43:48 -070026import java.io.IOException;
Madan Jampani27b69c62015-05-15 15:49:02 -070027import java.nio.ByteBuffer;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080028import java.nio.file.FileVisitResult;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080029import java.nio.file.Files;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080030import java.nio.file.Path;
31import java.nio.file.Paths;
32import java.nio.file.SimpleFileVisitor;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080033import java.nio.file.StandardCopyOption;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080034import java.nio.file.attribute.BasicFileAttributes;
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080035import java.security.SecureRandom;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070036import java.time.Instant;
37import java.time.OffsetDateTime;
38import java.time.ZoneId;
Madan Jampani27b69c62015-05-15 15:49:02 -070039import java.util.Arrays;
Brian O'Connore2eac102015-02-12 18:30:22 -080040import java.util.Collection;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070041import java.util.Dictionary;
tom53efab52014-10-07 17:43:48 -070042import java.util.List;
Sho SHIMIZUb5638b82016-02-11 14:55:05 -080043import java.util.Optional;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070044import java.util.Random;
Ray Milkey36992c82015-11-17 13:31:15 -080045import java.util.Set;
Madan Jampani27b69c62015-05-15 15:49:02 -070046import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070047import java.util.concurrent.ExecutionException;
Jordan Halterman9bdc24f2017-04-19 23:45:12 -070048import java.util.concurrent.Executor;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070049import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070050import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070051import java.util.concurrent.TimeUnit;
52import java.util.concurrent.TimeoutException;
Madan Jampani307a21e2016-09-01 15:49:47 -070053import java.util.function.BinaryOperator;
Madan Jampania29c6772015-08-17 13:17:07 -070054import java.util.function.Function;
55import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080056import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070057import java.util.stream.Stream;
58import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070059
Yuta HIGUCHI47d96092017-11-17 14:05:26 -080060import static com.google.common.base.Preconditions.checkNotNull;
Jonathan Hartcc962d82016-08-09 16:52:22 -070061import static java.nio.file.Files.delete;
62import static java.nio.file.Files.walkFileTree;
63import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
64import static org.slf4j.LoggerFactory.getLogger;
Ray Milkey705d9bc2014-11-18 08:19:00 -080065
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080066/**
67 * Miscellaneous utility methods.
68 */
tom5f38b3a2014-08-27 23:50:54 -070069public abstract class Tools {
70
71 private Tools() {
72 }
73
Thomas Vachuska02aeb032015-01-06 22:36:30 -080074 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080075
Ray Milkeyb68bbbc2017-12-18 10:05:49 -080076 private static Random random = new SecureRandom();
Thomas Vachuskaadba1522015-06-04 15:08:30 -070077
tom5f38b3a2014-08-27 23:50:54 -070078 /**
79 * Returns a thread factory that produces threads named according to the
80 * supplied name pattern.
81 *
82 * @param pattern name pattern
83 * @return thread factory
84 */
85 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080086 return new ThreadFactoryBuilder()
87 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080088 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
89 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080090 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080091
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080092 /**
93 * Returns a thread factory that produces threads named according to the
94 * supplied name pattern and from the specified thread-group. The thread
95 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080096 * {@code onos/intent}. The thread names will be produced by converting
97 * the thread group name into dash-delimited format and pre-pended to the
98 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080099 *
100 * @param groupName group name in slash-delimited format to indicate hierarchy
101 * @param pattern name pattern
102 * @return thread factory
103 */
104 public static ThreadFactory groupedThreads(String groupName, String pattern) {
Jian Li03e9fb02016-03-01 17:13:54 -0800105 return groupedThreads(groupName, pattern, log);
106 }
107
108 /**
109 * Returns a thread factory that produces threads named according to the
110 * supplied name pattern and from the specified thread-group. The thread
111 * group name is expected to be specified in slash-delimited format, e.g.
112 * {@code onos/intent}. The thread names will be produced by converting
113 * the thread group name into dash-delimited format and pre-pended to the
114 * specified pattern. If a logger is specified, it will use the logger to
115 * print out the exception if it has any.
116 *
117 * @param groupName group name in slash-delimited format to indicate hierarchy
118 * @param pattern name pattern
119 * @param logger logger
120 * @return thread factory
121 */
122 public static ThreadFactory groupedThreads(String groupName, String pattern, Logger logger) {
123 if (logger == null) {
124 return groupedThreads(groupName, pattern);
125 }
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -0800126 return new ThreadFactoryBuilder()
127 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800128 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Jian Li03e9fb02016-03-01 17:13:54 -0800129 .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e))
Thomas Vachuska480adad2015-03-06 10:27:09 -0800130 .build();
tom5f38b3a2014-08-27 23:50:54 -0700131 }
132
tom782a7cf2014-09-11 23:58:38 -0700133 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800134 * Returns a thread factory that produces threads with MIN_PRIORITY.
135 *
136 * @param factory backing ThreadFactory
137 * @return thread factory
138 */
139 public static ThreadFactory minPriority(ThreadFactory factory) {
140 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800141 .setThreadFactory(factory)
142 .setPriority(Thread.MIN_PRIORITY)
143 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800144 }
145
146 /**
Yuta HIGUCHIa2a11cd2016-12-19 14:19:11 -0800147 * Returns a thread factory that produces threads with MAX_PRIORITY.
148 *
149 * @param factory backing ThreadFactory
150 * @return thread factory
151 */
152 public static ThreadFactory maxPriority(ThreadFactory factory) {
153 return new ThreadFactoryBuilder()
154 .setThreadFactory(factory)
155 .setPriority(Thread.MAX_PRIORITY)
156 .build();
157 }
158
159 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800160 * Returns true if the collection is null or is empty.
161 *
162 * @param collection collection to test
163 * @return true if null or empty; false otherwise
164 */
Yuta HIGUCHI488a94c2018-01-26 17:24:09 -0800165 public static boolean isNullOrEmpty(Collection<?> collection) {
Brian O'Connore2eac102015-02-12 18:30:22 -0800166 return collection == null || collection.isEmpty();
167 }
168
169 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700170 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700171 * not found exception.
172 *
173 * @param item item to check
174 * @param message not found message
175 * @param <T> item type
176 * @return item if not null
177 * @throws org.onlab.util.ItemNotFoundException if item is null
178 */
179 public static <T> T nullIsNotFound(T item, String message) {
180 if (item == null) {
181 throw new ItemNotFoundException(message);
182 }
183 return item;
184 }
185
186 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800187 * Returns the specified set if the set is not null and not empty;
188 * otherwise throws a not found exception.
189 *
190 * @param item set to check
191 * @param message not found message
192 * @param <T> Set item type
193 * @return item if not null and not empty
194 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
195 */
196 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
197 if (item == null || item.isEmpty()) {
198 throw new ItemNotFoundException(message);
199 }
200 return item;
201 }
202
203 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700204 * Returns the specified item if that item is not null; otherwise throws
205 * bad argument exception.
206 *
207 * @param item item to check
208 * @param message not found message
209 * @param <T> item type
210 * @return item if not null
211 * @throws IllegalArgumentException if item is null
212 */
213 public static <T> T nullIsIllegal(T item, String message) {
214 if (item == null) {
215 throw new IllegalArgumentException(message);
216 }
217 return item;
218 }
219
220 /**
tom782a7cf2014-09-11 23:58:38 -0700221 * Converts a string from hex to long.
222 *
223 * @param string hex number in string form; sans 0x
224 * @return long value
225 */
226 public static long fromHex(String string) {
227 return UnsignedLongs.parseUnsignedLong(string, 16);
228 }
229
230 /**
231 * Converts a long value to hex string; 16 wide and sans 0x.
232 *
233 * @param value long value
234 * @return hex string
235 */
236 public static String toHex(long value) {
237 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
238 }
239
240 /**
241 * Converts a long value to hex string; 16 wide and sans 0x.
242 *
243 * @param value long value
244 * @param width string width; zero padded
245 * @return hex string
246 */
247 public static String toHex(long value, int width) {
248 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
249 }
tomf110fff2014-09-26 00:38:18 -0700250
251 /**
Jonathan Hartcc962d82016-08-09 16:52:22 -0700252 * Returns a string encoding in hex of the given long value with prefix
253 * '0x'.
254 *
255 * @param value long value to encode as hex string
256 * @return hex string
257 */
258 public static String toHexWithPrefix(long value) {
259 return "0x" + Long.toHexString(value);
260 }
261
262 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800263 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800264 * @param input input string
265 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800266 */
267 public static byte[] getBytesUtf8(String input) {
268 return input.getBytes(Charsets.UTF_8);
269 }
270
271 /**
272 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800273 * @param input input byte array
274 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800275 */
276 public static String toStringUtf8(byte[] input) {
277 return new String(input, Charsets.UTF_8);
278 }
279
280 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700281 * Returns a copy of the input byte array.
282 *
283 * @param original input
284 * @return copy of original
285 */
286 public static byte[] copyOf(byte[] original) {
287 return Arrays.copyOf(original, original.length);
288 }
289
290 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700291 * Get property as a string value.
292 *
293 * @param properties properties to be looked up
294 * @param propertyName the name of the property to look up
295 * @return value when the propertyName is defined or return null
296 */
297 public static String get(Dictionary<?, ?> properties, String propertyName) {
298 Object v = properties.get(propertyName);
299 String s = (v instanceof String) ? (String) v :
300 v != null ? v.toString() : null;
301 return Strings.isNullOrEmpty(s) ? null : s.trim();
302 }
303
304 /**
Jian Lid9b5f552016-03-11 18:15:31 -0800305 * Get Integer property from the propertyName
306 * Return null if propertyName is not found.
307 *
308 * @param properties properties to be looked up
309 * @param propertyName the name of the property to look up
310 * @return value when the propertyName is defined or return null
311 */
312 public static Integer getIntegerProperty(Dictionary<?, ?> properties,
313 String propertyName) {
314 Integer value;
315 try {
316 String s = get(properties, propertyName);
317 value = Strings.isNullOrEmpty(s) ? null : Integer.valueOf(s);
318 } catch (NumberFormatException | ClassCastException e) {
319 value = null;
320 }
321 return value;
322 }
323
324 /**
325 * Get Integer property from the propertyName
326 * Return default value if propertyName is not found.
327 *
328 * @param properties properties to be looked up
329 * @param propertyName the name of the property to look up
330 * @param defaultValue the default value that to be assigned
331 * @return value when the propertyName is defined or return default value
332 */
333 public static int getIntegerProperty(Dictionary<?, ?> properties,
334 String propertyName,
335 int defaultValue) {
336 try {
337 String s = get(properties, propertyName);
338 return Strings.isNullOrEmpty(s) ? defaultValue : Integer.valueOf(s);
339 } catch (NumberFormatException | ClassCastException e) {
340 return defaultValue;
341 }
342 }
343
344 /**
345 * Check property name is defined and set to true.
346 *
347 * @param properties properties to be looked up
348 * @param propertyName the name of the property to look up
349 * @return value when the propertyName is defined or return null
350 */
351 public static Boolean isPropertyEnabled(Dictionary<?, ?> properties,
352 String propertyName) {
353 Boolean value;
354 try {
355 String s = get(properties, propertyName);
356 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
357 } catch (ClassCastException e) {
358 value = null;
359 }
360 return value;
361 }
362
363 /**
364 * Check property name is defined as set to true.
365 *
366 * @param properties properties to be looked up
367 * @param propertyName the name of the property to look up
368 * @param defaultValue the default value that to be assigned
369 * @return value when the propertyName is defined or return the default value
370 */
371 public static boolean isPropertyEnabled(Dictionary<?, ?> properties,
372 String propertyName,
373 boolean defaultValue) {
374 try {
375 String s = get(properties, propertyName);
376 return Strings.isNullOrEmpty(s) ? defaultValue : Boolean.valueOf(s);
377 } catch (ClassCastException e) {
378 return defaultValue;
379 }
380 }
381
382 /**
tomf110fff2014-09-26 00:38:18 -0700383 * Suspends the current thread for a specified number of millis.
384 *
385 * @param ms number of millis
386 */
387 public static void delay(int ms) {
388 try {
389 Thread.sleep(ms);
390 } catch (InterruptedException e) {
Ray Milkey986a47a2018-01-25 11:38:51 -0800391 throw new IllegalStateException("Interrupted", e);
tomf110fff2014-09-26 00:38:18 -0700392 }
393 }
394
tom53efab52014-10-07 17:43:48 -0700395 /**
sdn94b00152016-08-30 02:12:32 -0700396 * Get Long property from the propertyName
397 * Return null if propertyName is not found.
398 *
399 * @param properties properties to be looked up
400 * @param propertyName the name of the property to look up
401 * @return value when the propertyName is defined or return null
402 */
403 public static Long getLongProperty(Dictionary<?, ?> properties,
404 String propertyName) {
405 Long value;
406 try {
407 String s = get(properties, propertyName);
408 value = Strings.isNullOrEmpty(s) ? null : Long.valueOf(s);
409 } catch (NumberFormatException | ClassCastException e) {
410 value = null;
411 }
412 return value;
413 }
414
415 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700416 * Returns a function that retries execution on failure.
417 * @param base base function
418 * @param exceptionClass type of exception for which to retry
419 * @param maxRetries max number of retries before giving up
420 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
421 * the interval (0, maxDelayBetweenRetries]
422 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700423 * @param <U> type of function input
424 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700425 */
426 public static <U, V> Function<U, V> retryable(Function<U, V> base,
427 Class<? extends Throwable> exceptionClass,
428 int maxRetries,
429 int maxDelayBetweenRetries) {
430 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
431 }
432
433 /**
434 * Returns a Supplier that retries execution on failure.
435 * @param base base supplier
436 * @param exceptionClass type of exception for which to retry
437 * @param maxRetries max number of retries before giving up
438 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
439 * the interval (0, maxDelayBetweenRetries]
440 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700441 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700442 */
443 public static <V> Supplier<V> retryable(Supplier<V> base,
444 Class<? extends Throwable> exceptionClass,
445 int maxRetries,
446 int maxDelayBetweenRetries) {
447 return () -> new RetryingFunction<>(v -> base.get(),
448 exceptionClass,
449 maxRetries,
450 maxDelayBetweenRetries).apply(null);
451 }
452
453 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700454 * Suspends the current thread for a random number of millis between 0 and
455 * the indicated limit.
456 *
457 * @param ms max number of millis
458 */
459 public static void randomDelay(int ms) {
460 try {
461 Thread.sleep(random.nextInt(ms));
462 } catch (InterruptedException e) {
Ray Milkey986a47a2018-01-25 11:38:51 -0800463 throw new IllegalStateException("Interrupted", e);
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700464 }
465 }
466
467 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700468 * Suspends the current thread for a specified number of millis and nanos.
469 *
470 * @param ms number of millis
471 * @param nanos number of nanos
472 */
473 public static void delay(int ms, int nanos) {
474 try {
475 Thread.sleep(ms, nanos);
476 } catch (InterruptedException e) {
Ray Milkey986a47a2018-01-25 11:38:51 -0800477 throw new IllegalStateException("Interrupted", e);
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700478 }
479 }
480
481 /**
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800482 * Purges the specified directory path.&nbsp;Use with great caution since
483 * no attempt is made to check for symbolic links, which could result in
484 * deletion of unintended files.
485 *
486 * @param path directory to be removed
487 * @throws java.io.IOException if unable to remove contents
488 */
489 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800490 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700491 File dir = new File(path);
492 if (dir.exists() && dir.isDirectory()) {
493 walkFileTree(Paths.get(path), visitor);
494 if (visitor.exception != null) {
495 throw visitor.exception;
496 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800497 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800498 }
499
500 /**
501 * Purges the specified directory path.&nbsp;Use with great caution since
502 * no attempt is made to check for symbolic links, which could result in
503 * deletion of unintended files.
504 *
505 * @param dir directory to be removed
506 * @throws java.io.IOException if unable to remove contents
507 */
508 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800509 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700510 if (dir.exists() && dir.isDirectory()) {
511 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
512 if (visitor.exception != null) {
513 throw visitor.exception;
514 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800515 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800516 }
517
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800518 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800519 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800520
521 private IOException exception;
522
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800523 @Override
524 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
525 throws IOException {
526 if (attributes.isRegularFile()) {
527 delete(file);
528 }
529 return FileVisitResult.CONTINUE;
530 }
531
532 @Override
533 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
534 throws IOException {
535 delete(directory);
536 return FileVisitResult.CONTINUE;
537 }
538
539 @Override
540 public FileVisitResult visitFileFailed(Path file, IOException ioe)
541 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800542 this.exception = ioe;
543 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800544 }
545 }
546
Madan Jampani30a57f82015-03-02 12:19:41 -0800547 /**
548 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800549 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800550 * @param unixTime system time in millis
551 * @return human friendly time ago
552 */
553 public static String timeAgo(long unixTime) {
554 long deltaMillis = System.currentTimeMillis() - unixTime;
555 long secondsSince = (long) (deltaMillis / 1000.0);
556 long minsSince = (long) (deltaMillis / (1000.0 * 60));
557 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
558 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
559 if (daysSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800560 return String.format("%dd%dh ago", daysSince, hoursSince - daysSince * 24);
Madan Jampani30a57f82015-03-02 12:19:41 -0800561 } else if (hoursSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800562 return String.format("%dh%dm ago", hoursSince, minsSince - hoursSince * 60);
Madan Jampani30a57f82015-03-02 12:19:41 -0800563 } else if (minsSince > 0) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800564 return String.format("%dm%ds ago", minsSince, secondsSince - minsSince * 60);
Madan Jampani30a57f82015-03-02 12:19:41 -0800565 } else if (secondsSince > 0) {
566 return String.format("%ds ago", secondsSince);
567 } else {
568 return "just now";
569 }
570 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800571
572 /**
573 * Copies the specified directory path.&nbsp;Use with great caution since
574 * no attempt is made to check for symbolic links, which could result in
575 * copy of unintended files.
576 *
577 * @param src directory to be copied
578 * @param dst destination directory to be removed
579 * @throws java.io.IOException if unable to remove contents
580 */
581 public static void copyDirectory(String src, String dst) throws IOException {
582 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
583 }
584
585 /**
586 * Copies the specified directory path.&nbsp;Use with great caution since
587 * no attempt is made to check for symbolic links, which could result in
588 * copy of unintended files.
589 *
590 * @param src directory to be copied
591 * @param dst destination directory to be removed
592 * @throws java.io.IOException if unable to remove contents
593 */
594 public static void copyDirectory(File src, File dst) throws IOException {
595 walkFileTree(Paths.get(src.getAbsolutePath()),
596 new DirectoryCopier(src.getAbsolutePath(),
597 dst.getAbsolutePath()));
598 }
599
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700600 /**
601 * Returns the future value when complete or if future
602 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700603 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700604 * @param future future
605 * @param defaultValue default value
606 * @param <T> future value type
607 * @return future value when complete or if future
608 * completes exceptionally returns the defaultValue.
609 */
610 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
611 try {
612 return future.get();
613 } catch (InterruptedException e) {
614 Thread.currentThread().interrupt();
615 return defaultValue;
616 } catch (ExecutionException e) {
617 return defaultValue;
618 }
619 }
620
621 /**
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 timeout time to wait for successful completion
627 * @param timeUnit time unit
628 * @param defaultValue default value
629 * @param <T> future value type
630 * @return future value when complete or if future
631 * completes exceptionally returns the defaultValue.
632 */
633 public static <T> T futureGetOrElse(Future<T> future,
634 long timeout,
635 TimeUnit timeUnit,
636 T defaultValue) {
637 try {
638 return future.get(timeout, timeUnit);
639 } catch (InterruptedException e) {
640 Thread.currentThread().interrupt();
641 return defaultValue;
642 } catch (ExecutionException | TimeoutException e) {
643 return defaultValue;
644 }
645 }
646
Madan Jampani27b69c62015-05-15 15:49:02 -0700647 /**
648 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700649 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700650 * @param t exception
651 * @param <T> future value type
652 * @return future
653 */
654 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
655 CompletableFuture<T> future = new CompletableFuture<>();
656 future.completeExceptionally(t);
657 return future;
658 }
659
660 /**
Jordan Halterman046faeb2017-05-01 15:10:13 -0700661 * Returns a future that's completed using the given {@code orderedExecutor} if the future is not blocked or the
662 * given {@code threadPoolExecutor} if the future is blocked.
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700663 * <p>
Jordan Halterman046faeb2017-05-01 15:10:13 -0700664 * This method allows futures to maintain single-thread semantics via the provided {@code orderedExecutor} while
665 * ensuring user code can block without blocking completion of futures. When the returned future or any of its
666 * descendants is blocked on a {@link CompletableFuture#get()} or {@link CompletableFuture#join()} call, completion
667 * of the returned future will be done using the provided {@code threadPoolExecutor}.
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700668 *
669 * @param future the future to convert into an asynchronous future
Jordan Halterman046faeb2017-05-01 15:10:13 -0700670 * @param orderedExecutor the ordered executor with which to attempt to complete the future
671 * @param threadPoolExecutor the backup executor with which to complete blocked futures
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700672 * @param <T> future value type
673 * @return a new completable future to be completed using the provided {@code executor} once the provided
674 * {@code future} is complete
675 */
Jordan Halterman046faeb2017-05-01 15:10:13 -0700676 public static <T> CompletableFuture<T> orderedFuture(
677 CompletableFuture<T> future,
678 Executor orderedExecutor,
679 Executor threadPoolExecutor) {
Jordan Haltermane265d372017-05-17 22:40:47 -0700680 if (future.isDone()) {
681 return future;
682 }
683
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700684 BlockingAwareFuture<T> newFuture = new BlockingAwareFuture<>();
Jordan Halterman046faeb2017-05-01 15:10:13 -0700685 future.whenComplete((result, error) -> {
686 Runnable completer = () -> {
687 if (future.isCompletedExceptionally()) {
688 newFuture.completeExceptionally(error);
689 } else {
690 newFuture.complete(result);
691 }
692 };
693
694 if (newFuture.isBlocked()) {
695 threadPoolExecutor.execute(completer);
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700696 } else {
Jordan Halterman046faeb2017-05-01 15:10:13 -0700697 orderedExecutor.execute(completer);
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700698 }
Jordan Halterman046faeb2017-05-01 15:10:13 -0700699 });
Jordan Halterman9bdc24f2017-04-19 23:45:12 -0700700 return newFuture;
701 }
702
703 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800704 * Returns a new CompletableFuture completed with a list of computed values
705 * when all of the given CompletableFuture complete.
706 *
707 * @param futures the CompletableFutures
708 * @param <T> value type of CompletableFuture
709 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
710 */
711 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
712 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
713 .thenApply(v -> futures.stream()
714 .map(CompletableFuture::join)
715 .collect(Collectors.toList())
716 );
717 }
718
719 /**
Madan Jampani307a21e2016-09-01 15:49:47 -0700720 * Returns a new CompletableFuture completed by reducing a list of computed values
721 * when all of the given CompletableFuture complete.
722 *
723 * @param futures the CompletableFutures
724 * @param reducer reducer for computing the result
725 * @param emptyValue zero value to be returned if the input future list is empty
726 * @param <T> value type of CompletableFuture
727 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
728 */
729 public static <T> CompletableFuture<T> allOf(List<CompletableFuture<T>> futures,
730 BinaryOperator<T> reducer,
731 T emptyValue) {
732 return Tools.allOf(futures)
733 .thenApply(resultList -> resultList.stream().reduce(reducer).orElse(emptyValue));
734 }
735
736 /**
737 * Returns a new CompletableFuture completed by with the first positive result from a list of
738 * input CompletableFutures.
739 *
740 * @param futures the input list of CompletableFutures
741 * @param positiveResultMatcher matcher to identify a positive result
742 * @param negativeResult value to complete with if none of the futures complete with a positive result
743 * @param <T> value type of CompletableFuture
744 * @return a new CompletableFuture
745 */
746 public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures,
747 Match<T> positiveResultMatcher,
748 T negativeResult) {
749 CompletableFuture<T> responseFuture = new CompletableFuture<>();
750 Tools.allOf(Lists.transform(futures, future -> future.thenAccept(r -> {
751 if (positiveResultMatcher.matches(r)) {
752 responseFuture.complete(r);
753 }
754 }))).whenComplete((r, e) -> {
755 if (!responseFuture.isDone()) {
756 if (e != null) {
757 responseFuture.completeExceptionally(e);
758 } else {
759 responseFuture.complete(negativeResult);
760 }
761 }
762 });
763 return responseFuture;
764 }
765
766 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700767 * Returns the contents of {@code ByteBuffer} as byte array.
768 * <p>
769 * WARNING: There is a performance cost due to array copy
770 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700771 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700772 * @param buffer byte buffer
773 * @return byte array containing the byte buffer contents
774 */
775 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
776 int length = buffer.remaining();
777 if (buffer.hasArray()) {
778 int offset = buffer.arrayOffset() + buffer.position();
779 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
780 }
781 byte[] bytes = new byte[length];
782 buffer.duplicate().get(bytes);
783 return bytes;
784 }
785
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700786 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700787 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700788 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700789 * @param it iterable to convert
790 * @param <T> type if item
791 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700792 */
793 public static <T> Stream<T> stream(Iterable<T> it) {
794 return StreamSupport.stream(it.spliterator(), false);
795 }
796
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800797 /**
798 * Converts an optional to a stream.
799 *
800 * @param optional optional to convert
801 * @param <T> type of enclosed value
802 * @return optional as a stream
803 */
Sho SHIMIZU6ac20982016-05-04 09:50:54 -0700804 public static <T> Stream<T> stream(Optional<? extends T> optional) {
HIGUCHI Yuta0bc256f2016-05-06 15:28:26 -0700805 return optional.map(x -> Stream.<T>of(x)).orElse(Stream.empty());
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800806 }
807
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800808 // Auxiliary path visitor for recursive directory structure copying.
809 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800810 private Path src;
811 private Path dst;
812 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
813
814 DirectoryCopier(String src, String dst) {
815 this.src = Paths.get(src);
816 this.dst = Paths.get(dst);
817 }
818
819 @Override
820 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
821 Path targetPath = dst.resolve(src.relativize(dir));
822 if (!Files.exists(targetPath)) {
823 Files.createDirectory(targetPath);
824 }
825 return FileVisitResult.CONTINUE;
826 }
827
828 @Override
829 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
830 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
831 return FileVisitResult.CONTINUE;
832 }
833 }
834
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700835 /**
836 * Creates OffsetDateTime instance from epoch milliseconds,
837 * using system default time zone.
838 *
839 * @param epochMillis to convert
840 * @return OffsetDateTime
841 */
842 public static OffsetDateTime defaultOffsetDataTime(long epochMillis) {
843 return OffsetDateTime.ofInstant(Instant.ofEpochMilli(epochMillis),
844 ZoneId.systemDefault());
845 }
846
Yuta HIGUCHI47d96092017-11-17 14:05:26 -0800847 /**
848 * Returns smaller of the two Comparable values.
849 *
850 * @param l an argument
851 * @param r another argument
852 * @return the smaller of {@code l} or {@code r}
853 * @param <C> Comparable type
854 * @throws NullPointerException if any of the arguments were null.
855 */
856 public static <C extends Comparable<? super C>> C min(C l, C r) {
857 checkNotNull(l, "l cannot be null");
858 checkNotNull(r, "r cannot be null");
859 return l.compareTo(r) <= 0 ? l : r;
860 }
861
862 /**
863 * Returns larger of the two Comparable values.
864 *
865 * @param l an argument
866 * @param r another argument
867 * @return the larger of {@code l} or {@code r}
868 * @param <C> Comparable type
869 * @throws NullPointerException if any of the arguments were null.
870 */
871 public static <C extends Comparable<? super C>> C max(C l, C r) {
872 checkNotNull(l, "l cannot be null");
873 checkNotNull(r, "r cannot be null");
874 return l.compareTo(r) >= 0 ? l : r;
875 }
tom5f38b3a2014-08-27 23:50:54 -0700876}