blob: e13fb2bbc5a3e3f56bd6092061b7bcc40d72a222 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 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
Jian Li66f15262016-03-03 11:18:40 -080018import com.google.common.base.Charsets;
19import com.google.common.base.Strings;
20import com.google.common.primitives.UnsignedLongs;
21import com.google.common.util.concurrent.ThreadFactoryBuilder;
22import org.slf4j.Logger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080023
tom53efab52014-10-07 17:43:48 -070024import java.io.BufferedReader;
25import java.io.File;
Ray Milkey705d9bc2014-11-18 08:19:00 -080026import java.io.FileInputStream;
tom53efab52014-10-07 17:43:48 -070027import java.io.IOException;
Ray Milkey705d9bc2014-11-18 08:19:00 -080028import java.io.InputStreamReader;
Madan Jampani27b69c62015-05-15 15:49:02 -070029import java.nio.ByteBuffer;
Ray Milkey705d9bc2014-11-18 08:19:00 -080030import java.nio.charset.StandardCharsets;
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;
tom53efab52014-10-07 17:43:48 -070038import java.util.ArrayList;
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;
48import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070049import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070050import java.util.concurrent.TimeUnit;
51import java.util.concurrent.TimeoutException;
Madan Jampania29c6772015-08-17 13:17:07 -070052import java.util.function.Function;
53import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080054import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070055import java.util.stream.Stream;
56import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070057
Jian Li66f15262016-03-03 11:18:40 -080058import static java.nio.file.Files.delete;
59import static java.nio.file.Files.walkFileTree;
60import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
61import static org.slf4j.LoggerFactory.getLogger;
Ray Milkey705d9bc2014-11-18 08:19:00 -080062
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080063/**
64 * Miscellaneous utility methods.
65 */
tom5f38b3a2014-08-27 23:50:54 -070066public abstract class Tools {
67
68 private Tools() {
69 }
70
Thomas Vachuska02aeb032015-01-06 22:36:30 -080071 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080072
Thomas Vachuskaadba1522015-06-04 15:08:30 -070073 private static Random random = new Random();
74
tom5f38b3a2014-08-27 23:50:54 -070075 /**
76 * Returns a thread factory that produces threads named according to the
77 * supplied name pattern.
78 *
79 * @param pattern name pattern
80 * @return thread factory
81 */
82 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080083 return new ThreadFactoryBuilder()
84 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080085 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
86 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080087 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080088
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080089 /**
90 * Returns a thread factory that produces threads named according to the
91 * supplied name pattern and from the specified thread-group. The thread
92 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080093 * {@code onos/intent}. The thread names will be produced by converting
94 * the thread group name into dash-delimited format and pre-pended to the
95 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080096 *
97 * @param groupName group name in slash-delimited format to indicate hierarchy
98 * @param pattern name pattern
99 * @return thread factory
100 */
101 public static ThreadFactory groupedThreads(String groupName, String pattern) {
Jian Li03e9fb02016-03-01 17:13:54 -0800102 return groupedThreads(groupName, pattern, log);
103 }
104
105 /**
106 * Returns a thread factory that produces threads named according to the
107 * supplied name pattern and from the specified thread-group. The thread
108 * group name is expected to be specified in slash-delimited format, e.g.
109 * {@code onos/intent}. The thread names will be produced by converting
110 * the thread group name into dash-delimited format and pre-pended to the
111 * specified pattern. If a logger is specified, it will use the logger to
112 * print out the exception if it has any.
113 *
114 * @param groupName group name in slash-delimited format to indicate hierarchy
115 * @param pattern name pattern
116 * @param logger logger
117 * @return thread factory
118 */
119 public static ThreadFactory groupedThreads(String groupName, String pattern, Logger logger) {
120 if (logger == null) {
121 return groupedThreads(groupName, pattern);
122 }
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -0800123 return new ThreadFactoryBuilder()
124 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800125 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Jian Li03e9fb02016-03-01 17:13:54 -0800126 .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e))
Thomas Vachuska480adad2015-03-06 10:27:09 -0800127 .build();
tom5f38b3a2014-08-27 23:50:54 -0700128 }
129
tom782a7cf2014-09-11 23:58:38 -0700130 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800131 * Returns a thread factory that produces threads with MIN_PRIORITY.
132 *
133 * @param factory backing ThreadFactory
134 * @return thread factory
135 */
136 public static ThreadFactory minPriority(ThreadFactory factory) {
137 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800138 .setThreadFactory(factory)
139 .setPriority(Thread.MIN_PRIORITY)
140 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800141 }
142
143 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800144 * Returns true if the collection is null or is empty.
145 *
146 * @param collection collection to test
147 * @return true if null or empty; false otherwise
148 */
149 public static boolean isNullOrEmpty(Collection collection) {
150 return collection == null || collection.isEmpty();
151 }
152
153 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700154 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700155 * not found exception.
156 *
157 * @param item item to check
158 * @param message not found message
159 * @param <T> item type
160 * @return item if not null
161 * @throws org.onlab.util.ItemNotFoundException if item is null
162 */
163 public static <T> T nullIsNotFound(T item, String message) {
164 if (item == null) {
165 throw new ItemNotFoundException(message);
166 }
167 return item;
168 }
169
170 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800171 * Returns the specified set if the set is not null and not empty;
172 * otherwise throws a not found exception.
173 *
174 * @param item set to check
175 * @param message not found message
176 * @param <T> Set item type
177 * @return item if not null and not empty
178 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
179 */
180 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
181 if (item == null || item.isEmpty()) {
182 throw new ItemNotFoundException(message);
183 }
184 return item;
185 }
186
187 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700188 * Returns the specified item if that item is not null; otherwise throws
189 * bad argument exception.
190 *
191 * @param item item to check
192 * @param message not found message
193 * @param <T> item type
194 * @return item if not null
195 * @throws IllegalArgumentException if item is null
196 */
197 public static <T> T nullIsIllegal(T item, String message) {
198 if (item == null) {
199 throw new IllegalArgumentException(message);
200 }
201 return item;
202 }
203
204 /**
tom782a7cf2014-09-11 23:58:38 -0700205 * Converts a string from hex to long.
206 *
207 * @param string hex number in string form; sans 0x
208 * @return long value
209 */
210 public static long fromHex(String string) {
211 return UnsignedLongs.parseUnsignedLong(string, 16);
212 }
213
214 /**
215 * Converts a long value to hex string; 16 wide and sans 0x.
216 *
217 * @param value long value
218 * @return hex string
219 */
220 public static String toHex(long value) {
221 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
222 }
223
224 /**
225 * Converts a long value to hex string; 16 wide and sans 0x.
226 *
227 * @param value long value
228 * @param width string width; zero padded
229 * @return hex string
230 */
231 public static String toHex(long value, int width) {
232 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
233 }
tomf110fff2014-09-26 00:38:18 -0700234
235 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800236 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800237 * @param input input string
238 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800239 */
240 public static byte[] getBytesUtf8(String input) {
241 return input.getBytes(Charsets.UTF_8);
242 }
243
244 /**
245 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800246 * @param input input byte array
247 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800248 */
249 public static String toStringUtf8(byte[] input) {
250 return new String(input, Charsets.UTF_8);
251 }
252
253 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700254 * Returns a copy of the input byte array.
255 *
256 * @param original input
257 * @return copy of original
258 */
259 public static byte[] copyOf(byte[] original) {
260 return Arrays.copyOf(original, original.length);
261 }
262
263 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700264 * Get property as a string value.
265 *
266 * @param properties properties to be looked up
267 * @param propertyName the name of the property to look up
268 * @return value when the propertyName is defined or return null
269 */
270 public static String get(Dictionary<?, ?> properties, String propertyName) {
271 Object v = properties.get(propertyName);
272 String s = (v instanceof String) ? (String) v :
273 v != null ? v.toString() : null;
274 return Strings.isNullOrEmpty(s) ? null : s.trim();
275 }
276
277 /**
tomf110fff2014-09-26 00:38:18 -0700278 * Suspends the current thread for a specified number of millis.
279 *
280 * @param ms number of millis
281 */
282 public static void delay(int ms) {
283 try {
284 Thread.sleep(ms);
285 } catch (InterruptedException e) {
286 throw new RuntimeException("Interrupted", e);
287 }
288 }
289
tom53efab52014-10-07 17:43:48 -0700290 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700291 * Returns a function that retries execution on failure.
292 * @param base base function
293 * @param exceptionClass type of exception for which to retry
294 * @param maxRetries max number of retries before giving up
295 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
296 * the interval (0, maxDelayBetweenRetries]
297 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700298 * @param <U> type of function input
299 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700300 */
301 public static <U, V> Function<U, V> retryable(Function<U, V> base,
302 Class<? extends Throwable> exceptionClass,
303 int maxRetries,
304 int maxDelayBetweenRetries) {
305 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
306 }
307
308 /**
309 * Returns a Supplier that retries execution on failure.
310 * @param base base supplier
311 * @param exceptionClass type of exception for which to retry
312 * @param maxRetries max number of retries before giving up
313 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
314 * the interval (0, maxDelayBetweenRetries]
315 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700316 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700317 */
318 public static <V> Supplier<V> retryable(Supplier<V> base,
319 Class<? extends Throwable> exceptionClass,
320 int maxRetries,
321 int maxDelayBetweenRetries) {
322 return () -> new RetryingFunction<>(v -> base.get(),
323 exceptionClass,
324 maxRetries,
325 maxDelayBetweenRetries).apply(null);
326 }
327
328 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700329 * Suspends the current thread for a random number of millis between 0 and
330 * the indicated limit.
331 *
332 * @param ms max number of millis
333 */
334 public static void randomDelay(int ms) {
335 try {
336 Thread.sleep(random.nextInt(ms));
337 } catch (InterruptedException e) {
338 throw new RuntimeException("Interrupted", e);
339 }
340 }
341
342 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700343 * Suspends the current thread for a specified number of millis and nanos.
344 *
345 * @param ms number of millis
346 * @param nanos number of nanos
347 */
348 public static void delay(int ms, int nanos) {
349 try {
350 Thread.sleep(ms, nanos);
351 } catch (InterruptedException e) {
352 throw new RuntimeException("Interrupted", e);
353 }
354 }
355
356 /**
tom53efab52014-10-07 17:43:48 -0700357 * Slurps the contents of a file into a list of strings, one per line.
358 *
359 * @param path file path
360 * @return file contents
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700361 * @deprecated in Emu release
tom53efab52014-10-07 17:43:48 -0700362 */
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700363 @Deprecated
tom53efab52014-10-07 17:43:48 -0700364 public static List<String> slurp(File path) {
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700365 try (
Ray Milkey705d9bc2014-11-18 08:19:00 -0800366 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800367 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700368 ) {
tom53efab52014-10-07 17:43:48 -0700369 List<String> lines = new ArrayList<>();
370 String line;
371 while ((line = br.readLine()) != null) {
372 lines.add(line);
373 }
374 return lines;
375
376 } catch (IOException e) {
377 return null;
378 }
379 }
380
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800381 /**
382 * Purges the specified directory path.&nbsp;Use with great caution since
383 * no attempt is made to check for symbolic links, which could result in
384 * deletion of unintended files.
385 *
386 * @param path directory to be removed
387 * @throws java.io.IOException if unable to remove contents
388 */
389 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800390 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700391 File dir = new File(path);
392 if (dir.exists() && dir.isDirectory()) {
393 walkFileTree(Paths.get(path), visitor);
394 if (visitor.exception != null) {
395 throw visitor.exception;
396 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800397 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800398 }
399
400 /**
401 * Purges the specified directory path.&nbsp;Use with great caution since
402 * no attempt is made to check for symbolic links, which could result in
403 * deletion of unintended files.
404 *
405 * @param dir directory to be removed
406 * @throws java.io.IOException if unable to remove contents
407 */
408 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800409 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700410 if (dir.exists() && dir.isDirectory()) {
411 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
412 if (visitor.exception != null) {
413 throw visitor.exception;
414 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800415 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800416 }
417
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800418 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800419 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800420
421 private IOException exception;
422
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800423 @Override
424 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
425 throws IOException {
426 if (attributes.isRegularFile()) {
427 delete(file);
428 }
429 return FileVisitResult.CONTINUE;
430 }
431
432 @Override
433 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
434 throws IOException {
435 delete(directory);
436 return FileVisitResult.CONTINUE;
437 }
438
439 @Override
440 public FileVisitResult visitFileFailed(Path file, IOException ioe)
441 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800442 this.exception = ioe;
443 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800444 }
445 }
446
Madan Jampani30a57f82015-03-02 12:19:41 -0800447 /**
448 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800449 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800450 * @param unixTime system time in millis
451 * @return human friendly time ago
452 */
453 public static String timeAgo(long unixTime) {
454 long deltaMillis = System.currentTimeMillis() - unixTime;
455 long secondsSince = (long) (deltaMillis / 1000.0);
456 long minsSince = (long) (deltaMillis / (1000.0 * 60));
457 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
458 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
459 if (daysSince > 0) {
460 return String.format("%dd ago", daysSince);
461 } else if (hoursSince > 0) {
462 return String.format("%dh ago", hoursSince);
463 } else if (minsSince > 0) {
464 return String.format("%dm ago", minsSince);
465 } else if (secondsSince > 0) {
466 return String.format("%ds ago", secondsSince);
467 } else {
468 return "just now";
469 }
470 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800471
472 /**
473 * Copies the specified directory path.&nbsp;Use with great caution since
474 * no attempt is made to check for symbolic links, which could result in
475 * copy of unintended files.
476 *
477 * @param src directory to be copied
478 * @param dst destination directory to be removed
479 * @throws java.io.IOException if unable to remove contents
480 */
481 public static void copyDirectory(String src, String dst) throws IOException {
482 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
483 }
484
485 /**
486 * Copies the specified directory path.&nbsp;Use with great caution since
487 * no attempt is made to check for symbolic links, which could result in
488 * copy of unintended files.
489 *
490 * @param src directory to be copied
491 * @param dst destination directory to be removed
492 * @throws java.io.IOException if unable to remove contents
493 */
494 public static void copyDirectory(File src, File dst) throws IOException {
495 walkFileTree(Paths.get(src.getAbsolutePath()),
496 new DirectoryCopier(src.getAbsolutePath(),
497 dst.getAbsolutePath()));
498 }
499
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700500 /**
501 * Returns the future value when complete or if future
502 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700503 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700504 * @param future future
505 * @param defaultValue default value
506 * @param <T> future value type
507 * @return future value when complete or if future
508 * completes exceptionally returns the defaultValue.
509 */
510 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
511 try {
512 return future.get();
513 } catch (InterruptedException e) {
514 Thread.currentThread().interrupt();
515 return defaultValue;
516 } catch (ExecutionException e) {
517 return defaultValue;
518 }
519 }
520
521 /**
522 * Returns the future value when complete or if future
523 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700524 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700525 * @param future future
526 * @param timeout time to wait for successful completion
527 * @param timeUnit time unit
528 * @param defaultValue default value
529 * @param <T> future value type
530 * @return future value when complete or if future
531 * completes exceptionally returns the defaultValue.
532 */
533 public static <T> T futureGetOrElse(Future<T> future,
534 long timeout,
535 TimeUnit timeUnit,
536 T defaultValue) {
537 try {
538 return future.get(timeout, timeUnit);
539 } catch (InterruptedException e) {
540 Thread.currentThread().interrupt();
541 return defaultValue;
542 } catch (ExecutionException | TimeoutException e) {
543 return defaultValue;
544 }
545 }
546
Madan Jampani27b69c62015-05-15 15:49:02 -0700547 /**
548 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700549 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700550 * @param t exception
551 * @param <T> future value type
552 * @return future
553 */
554 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
555 CompletableFuture<T> future = new CompletableFuture<>();
556 future.completeExceptionally(t);
557 return future;
558 }
559
560 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800561 * Returns a new CompletableFuture completed with a list of computed values
562 * when all of the given CompletableFuture complete.
563 *
564 * @param futures the CompletableFutures
565 * @param <T> value type of CompletableFuture
566 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
567 */
568 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
569 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
570 .thenApply(v -> futures.stream()
571 .map(CompletableFuture::join)
572 .collect(Collectors.toList())
573 );
574 }
575
576 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700577 * Returns the contents of {@code ByteBuffer} as byte array.
578 * <p>
579 * WARNING: There is a performance cost due to array copy
580 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700581 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700582 * @param buffer byte buffer
583 * @return byte array containing the byte buffer contents
584 */
585 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
586 int length = buffer.remaining();
587 if (buffer.hasArray()) {
588 int offset = buffer.arrayOffset() + buffer.position();
589 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
590 }
591 byte[] bytes = new byte[length];
592 buffer.duplicate().get(bytes);
593 return bytes;
594 }
595
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700596 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700597 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700598 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700599 * @param it iterable to convert
600 * @param <T> type if item
601 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700602 */
603 public static <T> Stream<T> stream(Iterable<T> it) {
604 return StreamSupport.stream(it.spliterator(), false);
605 }
606
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800607 /**
608 * Converts an optional to a stream.
609 *
610 * @param optional optional to convert
611 * @param <T> type of enclosed value
612 * @return optional as a stream
613 */
614 public static <T> Stream<T> stream(Optional<T> optional) {
615 return optional.map(Stream::of).orElse(Stream.empty());
616 }
617
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800618 // Auxiliary path visitor for recursive directory structure copying.
619 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800620 private Path src;
621 private Path dst;
622 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
623
624 DirectoryCopier(String src, String dst) {
625 this.src = Paths.get(src);
626 this.dst = Paths.get(dst);
627 }
628
629 @Override
630 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
631 Path targetPath = dst.resolve(src.relativize(dir));
632 if (!Files.exists(targetPath)) {
633 Files.createDirectory(targetPath);
634 }
635 return FileVisitResult.CONTINUE;
636 }
637
638 @Override
639 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
640 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
641 return FileVisitResult.CONTINUE;
642 }
643 }
644
tom5f38b3a2014-08-27 23:50:54 -0700645}