blob: 60a80c1a5771152cb01cc9c9caaab0c0c59224d6 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
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
Madan Jampani307a21e2016-09-01 15:49:47 -070018import static java.nio.file.Files.delete;
19import static java.nio.file.Files.walkFileTree;
20import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
21import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080022
tom53efab52014-10-07 17:43:48 -070023import java.io.File;
tom53efab52014-10-07 17:43:48 -070024import java.io.IOException;
Madan Jampani27b69c62015-05-15 15:49:02 -070025import java.nio.ByteBuffer;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080026import java.nio.file.FileVisitResult;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080027import java.nio.file.Files;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080028import java.nio.file.Path;
29import java.nio.file.Paths;
30import java.nio.file.SimpleFileVisitor;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080031import java.nio.file.StandardCopyOption;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080032import java.nio.file.attribute.BasicFileAttributes;
Madan Jampani27b69c62015-05-15 15:49:02 -070033import java.util.Arrays;
Brian O'Connore2eac102015-02-12 18:30:22 -080034import java.util.Collection;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070035import java.util.Dictionary;
tom53efab52014-10-07 17:43:48 -070036import java.util.List;
Sho SHIMIZUb5638b82016-02-11 14:55:05 -080037import java.util.Optional;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070038import java.util.Random;
Ray Milkey36992c82015-11-17 13:31:15 -080039import java.util.Set;
Madan Jampani27b69c62015-05-15 15:49:02 -070040import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070041import java.util.concurrent.ExecutionException;
42import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070043import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070044import java.util.concurrent.TimeUnit;
45import java.util.concurrent.TimeoutException;
Madan Jampani307a21e2016-09-01 15:49:47 -070046import java.util.function.BinaryOperator;
Madan Jampania29c6772015-08-17 13:17:07 -070047import java.util.function.Function;
48import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080049import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070050import java.util.stream.Stream;
51import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070052
Madan Jampani307a21e2016-09-01 15:49:47 -070053import org.slf4j.Logger;
54
55import com.google.common.base.Charsets;
56import com.google.common.base.Strings;
57import com.google.common.collect.Lists;
58import com.google.common.primitives.UnsignedLongs;
59import com.google.common.util.concurrent.ThreadFactoryBuilder;
Ray Milkey705d9bc2014-11-18 08:19:00 -080060
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080061/**
62 * Miscellaneous utility methods.
63 */
tom5f38b3a2014-08-27 23:50:54 -070064public abstract class Tools {
65
66 private Tools() {
67 }
68
Thomas Vachuska02aeb032015-01-06 22:36:30 -080069 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080070
Thomas Vachuskaadba1522015-06-04 15:08:30 -070071 private static Random random = new Random();
72
tom5f38b3a2014-08-27 23:50:54 -070073 /**
74 * Returns a thread factory that produces threads named according to the
75 * supplied name pattern.
76 *
77 * @param pattern name pattern
78 * @return thread factory
79 */
80 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080081 return new ThreadFactoryBuilder()
82 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080083 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
84 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080085 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080086
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080087 /**
88 * Returns a thread factory that produces threads named according to the
89 * supplied name pattern and from the specified thread-group. The thread
90 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080091 * {@code onos/intent}. The thread names will be produced by converting
92 * the thread group name into dash-delimited format and pre-pended to the
93 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080094 *
95 * @param groupName group name in slash-delimited format to indicate hierarchy
96 * @param pattern name pattern
97 * @return thread factory
98 */
99 public static ThreadFactory groupedThreads(String groupName, String pattern) {
Jian Li03e9fb02016-03-01 17:13:54 -0800100 return groupedThreads(groupName, pattern, log);
101 }
102
103 /**
104 * Returns a thread factory that produces threads named according to the
105 * supplied name pattern and from the specified thread-group. The thread
106 * group name is expected to be specified in slash-delimited format, e.g.
107 * {@code onos/intent}. The thread names will be produced by converting
108 * the thread group name into dash-delimited format and pre-pended to the
109 * specified pattern. If a logger is specified, it will use the logger to
110 * print out the exception if it has any.
111 *
112 * @param groupName group name in slash-delimited format to indicate hierarchy
113 * @param pattern name pattern
114 * @param logger logger
115 * @return thread factory
116 */
117 public static ThreadFactory groupedThreads(String groupName, String pattern, Logger logger) {
118 if (logger == null) {
119 return groupedThreads(groupName, pattern);
120 }
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -0800121 return new ThreadFactoryBuilder()
122 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800123 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Jian Li03e9fb02016-03-01 17:13:54 -0800124 .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e))
Thomas Vachuska480adad2015-03-06 10:27:09 -0800125 .build();
tom5f38b3a2014-08-27 23:50:54 -0700126 }
127
tom782a7cf2014-09-11 23:58:38 -0700128 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800129 * Returns a thread factory that produces threads with MIN_PRIORITY.
130 *
131 * @param factory backing ThreadFactory
132 * @return thread factory
133 */
134 public static ThreadFactory minPriority(ThreadFactory factory) {
135 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800136 .setThreadFactory(factory)
137 .setPriority(Thread.MIN_PRIORITY)
138 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800139 }
140
141 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800142 * Returns true if the collection is null or is empty.
143 *
144 * @param collection collection to test
145 * @return true if null or empty; false otherwise
146 */
147 public static boolean isNullOrEmpty(Collection collection) {
148 return collection == null || collection.isEmpty();
149 }
150
151 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700152 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700153 * not found exception.
154 *
155 * @param item item to check
156 * @param message not found message
157 * @param <T> item type
158 * @return item if not null
159 * @throws org.onlab.util.ItemNotFoundException if item is null
160 */
161 public static <T> T nullIsNotFound(T item, String message) {
162 if (item == null) {
163 throw new ItemNotFoundException(message);
164 }
165 return item;
166 }
167
168 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800169 * Returns the specified set if the set is not null and not empty;
170 * otherwise throws a not found exception.
171 *
172 * @param item set to check
173 * @param message not found message
174 * @param <T> Set item type
175 * @return item if not null and not empty
176 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
177 */
178 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
179 if (item == null || item.isEmpty()) {
180 throw new ItemNotFoundException(message);
181 }
182 return item;
183 }
184
185 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700186 * Returns the specified item if that item is not null; otherwise throws
187 * bad argument exception.
188 *
189 * @param item item to check
190 * @param message not found message
191 * @param <T> item type
192 * @return item if not null
193 * @throws IllegalArgumentException if item is null
194 */
195 public static <T> T nullIsIllegal(T item, String message) {
196 if (item == null) {
197 throw new IllegalArgumentException(message);
198 }
199 return item;
200 }
201
202 /**
tom782a7cf2014-09-11 23:58:38 -0700203 * Converts a string from hex to long.
204 *
205 * @param string hex number in string form; sans 0x
206 * @return long value
207 */
208 public static long fromHex(String string) {
209 return UnsignedLongs.parseUnsignedLong(string, 16);
210 }
211
212 /**
213 * Converts a long value to hex string; 16 wide and sans 0x.
214 *
215 * @param value long value
216 * @return hex string
217 */
218 public static String toHex(long value) {
219 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
220 }
221
222 /**
223 * Converts a long value to hex string; 16 wide and sans 0x.
224 *
225 * @param value long value
226 * @param width string width; zero padded
227 * @return hex string
228 */
229 public static String toHex(long value, int width) {
230 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
231 }
tomf110fff2014-09-26 00:38:18 -0700232
233 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800234 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800235 * @param input input string
236 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800237 */
238 public static byte[] getBytesUtf8(String input) {
239 return input.getBytes(Charsets.UTF_8);
240 }
241
242 /**
243 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800244 * @param input input byte array
245 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800246 */
247 public static String toStringUtf8(byte[] input) {
248 return new String(input, Charsets.UTF_8);
249 }
250
251 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700252 * Returns a copy of the input byte array.
253 *
254 * @param original input
255 * @return copy of original
256 */
257 public static byte[] copyOf(byte[] original) {
258 return Arrays.copyOf(original, original.length);
259 }
260
261 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700262 * Get property as a string value.
263 *
264 * @param properties properties to be looked up
265 * @param propertyName the name of the property to look up
266 * @return value when the propertyName is defined or return null
267 */
268 public static String get(Dictionary<?, ?> properties, String propertyName) {
269 Object v = properties.get(propertyName);
270 String s = (v instanceof String) ? (String) v :
271 v != null ? v.toString() : null;
272 return Strings.isNullOrEmpty(s) ? null : s.trim();
273 }
274
275 /**
Jian Lid9b5f552016-03-11 18:15:31 -0800276 * Get Integer property from the propertyName
277 * Return null if propertyName is not found.
278 *
279 * @param properties properties to be looked up
280 * @param propertyName the name of the property to look up
281 * @return value when the propertyName is defined or return null
282 */
283 public static Integer getIntegerProperty(Dictionary<?, ?> properties,
284 String propertyName) {
285 Integer value;
286 try {
287 String s = get(properties, propertyName);
288 value = Strings.isNullOrEmpty(s) ? null : Integer.valueOf(s);
289 } catch (NumberFormatException | ClassCastException e) {
290 value = null;
291 }
292 return value;
293 }
294
295 /**
296 * Get Integer property from the propertyName
297 * Return default value if propertyName is not found.
298 *
299 * @param properties properties to be looked up
300 * @param propertyName the name of the property to look up
301 * @param defaultValue the default value that to be assigned
302 * @return value when the propertyName is defined or return default value
303 */
304 public static int getIntegerProperty(Dictionary<?, ?> properties,
305 String propertyName,
306 int defaultValue) {
307 try {
308 String s = get(properties, propertyName);
309 return Strings.isNullOrEmpty(s) ? defaultValue : Integer.valueOf(s);
310 } catch (NumberFormatException | ClassCastException e) {
311 return defaultValue;
312 }
313 }
314
315 /**
316 * Check property name is defined and set to true.
317 *
318 * @param properties properties to be looked up
319 * @param propertyName the name of the property to look up
320 * @return value when the propertyName is defined or return null
321 */
322 public static Boolean isPropertyEnabled(Dictionary<?, ?> properties,
323 String propertyName) {
324 Boolean value;
325 try {
326 String s = get(properties, propertyName);
327 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
328 } catch (ClassCastException e) {
329 value = null;
330 }
331 return value;
332 }
333
334 /**
335 * Check property name is defined as set to true.
336 *
337 * @param properties properties to be looked up
338 * @param propertyName the name of the property to look up
339 * @param defaultValue the default value that to be assigned
340 * @return value when the propertyName is defined or return the default value
341 */
342 public static boolean isPropertyEnabled(Dictionary<?, ?> properties,
343 String propertyName,
344 boolean defaultValue) {
345 try {
346 String s = get(properties, propertyName);
347 return Strings.isNullOrEmpty(s) ? defaultValue : Boolean.valueOf(s);
348 } catch (ClassCastException e) {
349 return defaultValue;
350 }
351 }
352
353 /**
tomf110fff2014-09-26 00:38:18 -0700354 * Suspends the current thread for a specified number of millis.
355 *
356 * @param ms number of millis
357 */
358 public static void delay(int ms) {
359 try {
360 Thread.sleep(ms);
361 } catch (InterruptedException e) {
362 throw new RuntimeException("Interrupted", e);
363 }
364 }
365
tom53efab52014-10-07 17:43:48 -0700366 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700367 * Returns a function that retries execution on failure.
368 * @param base base function
369 * @param exceptionClass type of exception for which to retry
370 * @param maxRetries max number of retries before giving up
371 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
372 * the interval (0, maxDelayBetweenRetries]
373 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700374 * @param <U> type of function input
375 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700376 */
377 public static <U, V> Function<U, V> retryable(Function<U, V> base,
378 Class<? extends Throwable> exceptionClass,
379 int maxRetries,
380 int maxDelayBetweenRetries) {
381 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
382 }
383
384 /**
385 * Returns a Supplier that retries execution on failure.
386 * @param base base supplier
387 * @param exceptionClass type of exception for which to retry
388 * @param maxRetries max number of retries before giving up
389 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
390 * the interval (0, maxDelayBetweenRetries]
391 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700392 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700393 */
394 public static <V> Supplier<V> retryable(Supplier<V> base,
395 Class<? extends Throwable> exceptionClass,
396 int maxRetries,
397 int maxDelayBetweenRetries) {
398 return () -> new RetryingFunction<>(v -> base.get(),
399 exceptionClass,
400 maxRetries,
401 maxDelayBetweenRetries).apply(null);
402 }
403
404 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700405 * Suspends the current thread for a random number of millis between 0 and
406 * the indicated limit.
407 *
408 * @param ms max number of millis
409 */
410 public static void randomDelay(int ms) {
411 try {
412 Thread.sleep(random.nextInt(ms));
413 } catch (InterruptedException e) {
414 throw new RuntimeException("Interrupted", e);
415 }
416 }
417
418 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700419 * Suspends the current thread for a specified number of millis and nanos.
420 *
421 * @param ms number of millis
422 * @param nanos number of nanos
423 */
424 public static void delay(int ms, int nanos) {
425 try {
426 Thread.sleep(ms, nanos);
427 } catch (InterruptedException e) {
428 throw new RuntimeException("Interrupted", e);
429 }
430 }
431
432 /**
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800433 * Purges the specified directory path.&nbsp;Use with great caution since
434 * no attempt is made to check for symbolic links, which could result in
435 * deletion of unintended files.
436 *
437 * @param path directory to be removed
438 * @throws java.io.IOException if unable to remove contents
439 */
440 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800441 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700442 File dir = new File(path);
443 if (dir.exists() && dir.isDirectory()) {
444 walkFileTree(Paths.get(path), visitor);
445 if (visitor.exception != null) {
446 throw visitor.exception;
447 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800448 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800449 }
450
451 /**
452 * Purges the specified directory path.&nbsp;Use with great caution since
453 * no attempt is made to check for symbolic links, which could result in
454 * deletion of unintended files.
455 *
456 * @param dir directory to be removed
457 * @throws java.io.IOException if unable to remove contents
458 */
459 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800460 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700461 if (dir.exists() && dir.isDirectory()) {
462 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
463 if (visitor.exception != null) {
464 throw visitor.exception;
465 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800466 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800467 }
468
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800469 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800470 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800471
472 private IOException exception;
473
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800474 @Override
475 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
476 throws IOException {
477 if (attributes.isRegularFile()) {
478 delete(file);
479 }
480 return FileVisitResult.CONTINUE;
481 }
482
483 @Override
484 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
485 throws IOException {
486 delete(directory);
487 return FileVisitResult.CONTINUE;
488 }
489
490 @Override
491 public FileVisitResult visitFileFailed(Path file, IOException ioe)
492 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800493 this.exception = ioe;
494 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800495 }
496 }
497
Madan Jampani30a57f82015-03-02 12:19:41 -0800498 /**
499 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800500 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800501 * @param unixTime system time in millis
502 * @return human friendly time ago
503 */
504 public static String timeAgo(long unixTime) {
505 long deltaMillis = System.currentTimeMillis() - unixTime;
506 long secondsSince = (long) (deltaMillis / 1000.0);
507 long minsSince = (long) (deltaMillis / (1000.0 * 60));
508 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
509 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
510 if (daysSince > 0) {
511 return String.format("%dd ago", daysSince);
512 } else if (hoursSince > 0) {
513 return String.format("%dh ago", hoursSince);
514 } else if (minsSince > 0) {
515 return String.format("%dm ago", minsSince);
516 } else if (secondsSince > 0) {
517 return String.format("%ds ago", secondsSince);
518 } else {
519 return "just now";
520 }
521 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800522
523 /**
524 * Copies the specified directory path.&nbsp;Use with great caution since
525 * no attempt is made to check for symbolic links, which could result in
526 * copy of unintended files.
527 *
528 * @param src directory to be copied
529 * @param dst destination directory to be removed
530 * @throws java.io.IOException if unable to remove contents
531 */
532 public static void copyDirectory(String src, String dst) throws IOException {
533 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
534 }
535
536 /**
537 * Copies the specified directory path.&nbsp;Use with great caution since
538 * no attempt is made to check for symbolic links, which could result in
539 * copy of unintended files.
540 *
541 * @param src directory to be copied
542 * @param dst destination directory to be removed
543 * @throws java.io.IOException if unable to remove contents
544 */
545 public static void copyDirectory(File src, File dst) throws IOException {
546 walkFileTree(Paths.get(src.getAbsolutePath()),
547 new DirectoryCopier(src.getAbsolutePath(),
548 dst.getAbsolutePath()));
549 }
550
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700551 /**
552 * Returns the future value when complete or if future
553 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700554 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700555 * @param future future
556 * @param defaultValue default value
557 * @param <T> future value type
558 * @return future value when complete or if future
559 * completes exceptionally returns the defaultValue.
560 */
561 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
562 try {
563 return future.get();
564 } catch (InterruptedException e) {
565 Thread.currentThread().interrupt();
566 return defaultValue;
567 } catch (ExecutionException e) {
568 return defaultValue;
569 }
570 }
571
572 /**
573 * Returns the future value when complete or if future
574 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700575 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700576 * @param future future
577 * @param timeout time to wait for successful completion
578 * @param timeUnit time unit
579 * @param defaultValue default value
580 * @param <T> future value type
581 * @return future value when complete or if future
582 * completes exceptionally returns the defaultValue.
583 */
584 public static <T> T futureGetOrElse(Future<T> future,
585 long timeout,
586 TimeUnit timeUnit,
587 T defaultValue) {
588 try {
589 return future.get(timeout, timeUnit);
590 } catch (InterruptedException e) {
591 Thread.currentThread().interrupt();
592 return defaultValue;
593 } catch (ExecutionException | TimeoutException e) {
594 return defaultValue;
595 }
596 }
597
Madan Jampani27b69c62015-05-15 15:49:02 -0700598 /**
599 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700600 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700601 * @param t exception
602 * @param <T> future value type
603 * @return future
604 */
605 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
606 CompletableFuture<T> future = new CompletableFuture<>();
607 future.completeExceptionally(t);
608 return future;
609 }
610
611 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800612 * Returns a new CompletableFuture completed with a list of computed values
613 * when all of the given CompletableFuture complete.
614 *
615 * @param futures the CompletableFutures
616 * @param <T> value type of CompletableFuture
617 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
618 */
619 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
620 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
621 .thenApply(v -> futures.stream()
622 .map(CompletableFuture::join)
623 .collect(Collectors.toList())
624 );
625 }
626
627 /**
Madan Jampani307a21e2016-09-01 15:49:47 -0700628 * Returns a new CompletableFuture completed by reducing a list of computed values
629 * when all of the given CompletableFuture complete.
630 *
631 * @param futures the CompletableFutures
632 * @param reducer reducer for computing the result
633 * @param emptyValue zero value to be returned if the input future list is empty
634 * @param <T> value type of CompletableFuture
635 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
636 */
637 public static <T> CompletableFuture<T> allOf(List<CompletableFuture<T>> futures,
638 BinaryOperator<T> reducer,
639 T emptyValue) {
640 return Tools.allOf(futures)
641 .thenApply(resultList -> resultList.stream().reduce(reducer).orElse(emptyValue));
642 }
643
644 /**
645 * Returns a new CompletableFuture completed by with the first positive result from a list of
646 * input CompletableFutures.
647 *
648 * @param futures the input list of CompletableFutures
649 * @param positiveResultMatcher matcher to identify a positive result
650 * @param negativeResult value to complete with if none of the futures complete with a positive result
651 * @param <T> value type of CompletableFuture
652 * @return a new CompletableFuture
653 */
654 public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures,
655 Match<T> positiveResultMatcher,
656 T negativeResult) {
657 CompletableFuture<T> responseFuture = new CompletableFuture<>();
658 Tools.allOf(Lists.transform(futures, future -> future.thenAccept(r -> {
659 if (positiveResultMatcher.matches(r)) {
660 responseFuture.complete(r);
661 }
662 }))).whenComplete((r, e) -> {
663 if (!responseFuture.isDone()) {
664 if (e != null) {
665 responseFuture.completeExceptionally(e);
666 } else {
667 responseFuture.complete(negativeResult);
668 }
669 }
670 });
671 return responseFuture;
672 }
673
674 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700675 * Returns the contents of {@code ByteBuffer} as byte array.
676 * <p>
677 * WARNING: There is a performance cost due to array copy
678 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700679 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700680 * @param buffer byte buffer
681 * @return byte array containing the byte buffer contents
682 */
683 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
684 int length = buffer.remaining();
685 if (buffer.hasArray()) {
686 int offset = buffer.arrayOffset() + buffer.position();
687 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
688 }
689 byte[] bytes = new byte[length];
690 buffer.duplicate().get(bytes);
691 return bytes;
692 }
693
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700694 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700695 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700696 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700697 * @param it iterable to convert
698 * @param <T> type if item
699 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700700 */
701 public static <T> Stream<T> stream(Iterable<T> it) {
702 return StreamSupport.stream(it.spliterator(), false);
703 }
704
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800705 /**
706 * Converts an optional to a stream.
707 *
708 * @param optional optional to convert
709 * @param <T> type of enclosed value
710 * @return optional as a stream
711 */
Sho SHIMIZU6ac20982016-05-04 09:50:54 -0700712 public static <T> Stream<T> stream(Optional<? extends T> optional) {
HIGUCHI Yuta0bc256f2016-05-06 15:28:26 -0700713 return optional.map(x -> Stream.<T>of(x)).orElse(Stream.empty());
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800714 }
715
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800716 // Auxiliary path visitor for recursive directory structure copying.
717 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800718 private Path src;
719 private Path dst;
720 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
721
722 DirectoryCopier(String src, String dst) {
723 this.src = Paths.get(src);
724 this.dst = Paths.get(dst);
725 }
726
727 @Override
728 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
729 Path targetPath = dst.resolve(src.relativize(dir));
730 if (!Files.exists(targetPath)) {
731 Files.createDirectory(targetPath);
732 }
733 return FileVisitResult.CONTINUE;
734 }
735
736 @Override
737 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
738 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
739 return FileVisitResult.CONTINUE;
740 }
741 }
742
tom5f38b3a2014-08-27 23:50:54 -0700743}