blob: 9bc6436b5062ce8cd482ffd17c157cbb07d1a790 [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
Madan Jampani2bfa94c2015-04-11 05:03:49 -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.BufferedReader;
24import java.io.File;
Ray Milkey705d9bc2014-11-18 08:19:00 -080025import java.io.FileInputStream;
tom53efab52014-10-07 17:43:48 -070026import java.io.IOException;
Ray Milkey705d9bc2014-11-18 08:19:00 -080027import java.io.InputStreamReader;
Madan Jampani27b69c62015-05-15 15:49:02 -070028import java.nio.ByteBuffer;
Ray Milkey705d9bc2014-11-18 08:19:00 -080029import java.nio.charset.StandardCharsets;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080030import java.nio.file.FileVisitResult;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080031import java.nio.file.Files;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080032import java.nio.file.Path;
33import java.nio.file.Paths;
34import java.nio.file.SimpleFileVisitor;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080035import java.nio.file.StandardCopyOption;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080036import java.nio.file.attribute.BasicFileAttributes;
tom53efab52014-10-07 17:43:48 -070037import java.util.ArrayList;
Madan Jampani27b69c62015-05-15 15:49:02 -070038import java.util.Arrays;
Brian O'Connore2eac102015-02-12 18:30:22 -080039import java.util.Collection;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070040import java.util.Dictionary;
tom53efab52014-10-07 17:43:48 -070041import java.util.List;
Sho SHIMIZUb5638b82016-02-11 14:55:05 -080042import java.util.Optional;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070043import java.util.Random;
Ray Milkey36992c82015-11-17 13:31:15 -080044import java.util.Set;
Madan Jampani27b69c62015-05-15 15:49:02 -070045import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070046import java.util.concurrent.ExecutionException;
47import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070048import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070049import java.util.concurrent.TimeUnit;
50import java.util.concurrent.TimeoutException;
Madan Jampania29c6772015-08-17 13:17:07 -070051import java.util.function.Function;
52import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080053import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070054import java.util.stream.Stream;
55import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070056
Madan Jampani2bfa94c2015-04-11 05:03:49 -070057import org.slf4j.Logger;
58
Madan Jampanif2f086c2016-01-13 16:15:39 -080059import com.google.common.base.Charsets;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070060import com.google.common.base.Strings;
61import com.google.common.primitives.UnsignedLongs;
62import com.google.common.util.concurrent.ThreadFactoryBuilder;
Ray Milkey705d9bc2014-11-18 08:19:00 -080063
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080064/**
65 * Miscellaneous utility methods.
66 */
tom5f38b3a2014-08-27 23:50:54 -070067public abstract class Tools {
68
69 private Tools() {
70 }
71
Thomas Vachuska02aeb032015-01-06 22:36:30 -080072 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080073
Thomas Vachuskaadba1522015-06-04 15:08:30 -070074 private static Random random = new Random();
75
tom5f38b3a2014-08-27 23:50:54 -070076 /**
77 * Returns a thread factory that produces threads named according to the
78 * supplied name pattern.
79 *
80 * @param pattern name pattern
81 * @return thread factory
82 */
83 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080084 return new ThreadFactoryBuilder()
85 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080086 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
87 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080088 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080089
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080090 /**
91 * Returns a thread factory that produces threads named according to the
92 * supplied name pattern and from the specified thread-group. The thread
93 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080094 * {@code onos/intent}. The thread names will be produced by converting
95 * the thread group name into dash-delimited format and pre-pended to the
96 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080097 *
98 * @param groupName group name in slash-delimited format to indicate hierarchy
99 * @param pattern name pattern
100 * @return thread factory
101 */
102 public static ThreadFactory groupedThreads(String groupName, String pattern) {
103 return new ThreadFactoryBuilder()
104 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800105 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -0800106 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
107 .build();
tom5f38b3a2014-08-27 23:50:54 -0700108 }
109
tom782a7cf2014-09-11 23:58:38 -0700110 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800111 * Returns a thread factory that produces threads with MIN_PRIORITY.
112 *
113 * @param factory backing ThreadFactory
114 * @return thread factory
115 */
116 public static ThreadFactory minPriority(ThreadFactory factory) {
117 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800118 .setThreadFactory(factory)
119 .setPriority(Thread.MIN_PRIORITY)
120 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800121 }
122
123 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800124 * Returns true if the collection is null or is empty.
125 *
126 * @param collection collection to test
127 * @return true if null or empty; false otherwise
128 */
129 public static boolean isNullOrEmpty(Collection collection) {
130 return collection == null || collection.isEmpty();
131 }
132
133 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700134 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700135 * not found exception.
136 *
137 * @param item item to check
138 * @param message not found message
139 * @param <T> item type
140 * @return item if not null
141 * @throws org.onlab.util.ItemNotFoundException if item is null
142 */
143 public static <T> T nullIsNotFound(T item, String message) {
144 if (item == null) {
145 throw new ItemNotFoundException(message);
146 }
147 return item;
148 }
149
150 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800151 * Returns the specified set if the set is not null and not empty;
152 * otherwise throws a not found exception.
153 *
154 * @param item set to check
155 * @param message not found message
156 * @param <T> Set item type
157 * @return item if not null and not empty
158 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
159 */
160 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
161 if (item == null || item.isEmpty()) {
162 throw new ItemNotFoundException(message);
163 }
164 return item;
165 }
166
167 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700168 * Returns the specified item if that item is not null; otherwise throws
169 * bad argument exception.
170 *
171 * @param item item to check
172 * @param message not found message
173 * @param <T> item type
174 * @return item if not null
175 * @throws IllegalArgumentException if item is null
176 */
177 public static <T> T nullIsIllegal(T item, String message) {
178 if (item == null) {
179 throw new IllegalArgumentException(message);
180 }
181 return item;
182 }
183
184 /**
tom782a7cf2014-09-11 23:58:38 -0700185 * Converts a string from hex to long.
186 *
187 * @param string hex number in string form; sans 0x
188 * @return long value
189 */
190 public static long fromHex(String string) {
191 return UnsignedLongs.parseUnsignedLong(string, 16);
192 }
193
194 /**
195 * Converts a long value to hex string; 16 wide and sans 0x.
196 *
197 * @param value long value
198 * @return hex string
199 */
200 public static String toHex(long value) {
201 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
202 }
203
204 /**
205 * Converts a long value to hex string; 16 wide and sans 0x.
206 *
207 * @param value long value
208 * @param width string width; zero padded
209 * @return hex string
210 */
211 public static String toHex(long value, int width) {
212 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
213 }
tomf110fff2014-09-26 00:38:18 -0700214
215 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800216 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800217 * @param input input string
218 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800219 */
220 public static byte[] getBytesUtf8(String input) {
221 return input.getBytes(Charsets.UTF_8);
222 }
223
224 /**
225 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800226 * @param input input byte array
227 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800228 */
229 public static String toStringUtf8(byte[] input) {
230 return new String(input, Charsets.UTF_8);
231 }
232
233 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700234 * Returns a copy of the input byte array.
235 *
236 * @param original input
237 * @return copy of original
238 */
239 public static byte[] copyOf(byte[] original) {
240 return Arrays.copyOf(original, original.length);
241 }
242
243 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700244 * Get property as a string value.
245 *
246 * @param properties properties to be looked up
247 * @param propertyName the name of the property to look up
248 * @return value when the propertyName is defined or return null
249 */
250 public static String get(Dictionary<?, ?> properties, String propertyName) {
251 Object v = properties.get(propertyName);
252 String s = (v instanceof String) ? (String) v :
253 v != null ? v.toString() : null;
254 return Strings.isNullOrEmpty(s) ? null : s.trim();
255 }
256
257 /**
tomf110fff2014-09-26 00:38:18 -0700258 * Suspends the current thread for a specified number of millis.
259 *
260 * @param ms number of millis
261 */
262 public static void delay(int ms) {
263 try {
264 Thread.sleep(ms);
265 } catch (InterruptedException e) {
266 throw new RuntimeException("Interrupted", e);
267 }
268 }
269
tom53efab52014-10-07 17:43:48 -0700270 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700271 * Returns a function that retries execution on failure.
272 * @param base base function
273 * @param exceptionClass type of exception for which to retry
274 * @param maxRetries max number of retries before giving up
275 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
276 * the interval (0, maxDelayBetweenRetries]
277 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700278 * @param <U> type of function input
279 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700280 */
281 public static <U, V> Function<U, V> retryable(Function<U, V> base,
282 Class<? extends Throwable> exceptionClass,
283 int maxRetries,
284 int maxDelayBetweenRetries) {
285 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
286 }
287
288 /**
289 * Returns a Supplier that retries execution on failure.
290 * @param base base supplier
291 * @param exceptionClass type of exception for which to retry
292 * @param maxRetries max number of retries before giving up
293 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
294 * the interval (0, maxDelayBetweenRetries]
295 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700296 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700297 */
298 public static <V> Supplier<V> retryable(Supplier<V> base,
299 Class<? extends Throwable> exceptionClass,
300 int maxRetries,
301 int maxDelayBetweenRetries) {
302 return () -> new RetryingFunction<>(v -> base.get(),
303 exceptionClass,
304 maxRetries,
305 maxDelayBetweenRetries).apply(null);
306 }
307
308 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700309 * Suspends the current thread for a random number of millis between 0 and
310 * the indicated limit.
311 *
312 * @param ms max number of millis
313 */
314 public static void randomDelay(int ms) {
315 try {
316 Thread.sleep(random.nextInt(ms));
317 } catch (InterruptedException e) {
318 throw new RuntimeException("Interrupted", e);
319 }
320 }
321
322 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700323 * Suspends the current thread for a specified number of millis and nanos.
324 *
325 * @param ms number of millis
326 * @param nanos number of nanos
327 */
328 public static void delay(int ms, int nanos) {
329 try {
330 Thread.sleep(ms, nanos);
331 } catch (InterruptedException e) {
332 throw new RuntimeException("Interrupted", e);
333 }
334 }
335
336 /**
tom53efab52014-10-07 17:43:48 -0700337 * Slurps the contents of a file into a list of strings, one per line.
338 *
339 * @param path file path
340 * @return file contents
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700341 * @deprecated in Emu release
tom53efab52014-10-07 17:43:48 -0700342 */
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700343 @Deprecated
tom53efab52014-10-07 17:43:48 -0700344 public static List<String> slurp(File path) {
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700345 try (
Ray Milkey705d9bc2014-11-18 08:19:00 -0800346 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800347 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700348 ) {
tom53efab52014-10-07 17:43:48 -0700349 List<String> lines = new ArrayList<>();
350 String line;
351 while ((line = br.readLine()) != null) {
352 lines.add(line);
353 }
354 return lines;
355
356 } catch (IOException e) {
357 return null;
358 }
359 }
360
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800361 /**
362 * Purges the specified directory path.&nbsp;Use with great caution since
363 * no attempt is made to check for symbolic links, which could result in
364 * deletion of unintended files.
365 *
366 * @param path directory to be removed
367 * @throws java.io.IOException if unable to remove contents
368 */
369 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800370 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700371 File dir = new File(path);
372 if (dir.exists() && dir.isDirectory()) {
373 walkFileTree(Paths.get(path), visitor);
374 if (visitor.exception != null) {
375 throw visitor.exception;
376 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800377 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800378 }
379
380 /**
381 * Purges the specified directory path.&nbsp;Use with great caution since
382 * no attempt is made to check for symbolic links, which could result in
383 * deletion of unintended files.
384 *
385 * @param dir directory to be removed
386 * @throws java.io.IOException if unable to remove contents
387 */
388 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800389 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700390 if (dir.exists() && dir.isDirectory()) {
391 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
392 if (visitor.exception != null) {
393 throw visitor.exception;
394 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800395 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800396 }
397
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800398 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800399 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800400
401 private IOException exception;
402
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800403 @Override
404 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
405 throws IOException {
406 if (attributes.isRegularFile()) {
407 delete(file);
408 }
409 return FileVisitResult.CONTINUE;
410 }
411
412 @Override
413 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
414 throws IOException {
415 delete(directory);
416 return FileVisitResult.CONTINUE;
417 }
418
419 @Override
420 public FileVisitResult visitFileFailed(Path file, IOException ioe)
421 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800422 this.exception = ioe;
423 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800424 }
425 }
426
Madan Jampani30a57f82015-03-02 12:19:41 -0800427 /**
428 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800429 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800430 * @param unixTime system time in millis
431 * @return human friendly time ago
432 */
433 public static String timeAgo(long unixTime) {
434 long deltaMillis = System.currentTimeMillis() - unixTime;
435 long secondsSince = (long) (deltaMillis / 1000.0);
436 long minsSince = (long) (deltaMillis / (1000.0 * 60));
437 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
438 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
439 if (daysSince > 0) {
440 return String.format("%dd ago", daysSince);
441 } else if (hoursSince > 0) {
442 return String.format("%dh ago", hoursSince);
443 } else if (minsSince > 0) {
444 return String.format("%dm ago", minsSince);
445 } else if (secondsSince > 0) {
446 return String.format("%ds ago", secondsSince);
447 } else {
448 return "just now";
449 }
450 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800451
452 /**
453 * Copies the specified directory path.&nbsp;Use with great caution since
454 * no attempt is made to check for symbolic links, which could result in
455 * copy of unintended files.
456 *
457 * @param src directory to be copied
458 * @param dst destination directory to be removed
459 * @throws java.io.IOException if unable to remove contents
460 */
461 public static void copyDirectory(String src, String dst) throws IOException {
462 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
463 }
464
465 /**
466 * Copies the specified directory path.&nbsp;Use with great caution since
467 * no attempt is made to check for symbolic links, which could result in
468 * copy of unintended files.
469 *
470 * @param src directory to be copied
471 * @param dst destination directory to be removed
472 * @throws java.io.IOException if unable to remove contents
473 */
474 public static void copyDirectory(File src, File dst) throws IOException {
475 walkFileTree(Paths.get(src.getAbsolutePath()),
476 new DirectoryCopier(src.getAbsolutePath(),
477 dst.getAbsolutePath()));
478 }
479
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700480 /**
481 * Returns the future value when complete or if future
482 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700483 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700484 * @param future future
485 * @param defaultValue default value
486 * @param <T> future value type
487 * @return future value when complete or if future
488 * completes exceptionally returns the defaultValue.
489 */
490 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
491 try {
492 return future.get();
493 } catch (InterruptedException e) {
494 Thread.currentThread().interrupt();
495 return defaultValue;
496 } catch (ExecutionException e) {
497 return defaultValue;
498 }
499 }
500
501 /**
502 * Returns the future value when complete or if future
503 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700504 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700505 * @param future future
506 * @param timeout time to wait for successful completion
507 * @param timeUnit time unit
508 * @param defaultValue default value
509 * @param <T> future value type
510 * @return future value when complete or if future
511 * completes exceptionally returns the defaultValue.
512 */
513 public static <T> T futureGetOrElse(Future<T> future,
514 long timeout,
515 TimeUnit timeUnit,
516 T defaultValue) {
517 try {
518 return future.get(timeout, timeUnit);
519 } catch (InterruptedException e) {
520 Thread.currentThread().interrupt();
521 return defaultValue;
522 } catch (ExecutionException | TimeoutException e) {
523 return defaultValue;
524 }
525 }
526
Madan Jampani27b69c62015-05-15 15:49:02 -0700527 /**
528 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700529 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700530 * @param t exception
531 * @param <T> future value type
532 * @return future
533 */
534 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
535 CompletableFuture<T> future = new CompletableFuture<>();
536 future.completeExceptionally(t);
537 return future;
538 }
539
540 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800541 * Returns a new CompletableFuture completed with a list of computed values
542 * when all of the given CompletableFuture complete.
543 *
544 * @param futures the CompletableFutures
545 * @param <T> value type of CompletableFuture
546 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
547 */
548 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
549 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
550 .thenApply(v -> futures.stream()
551 .map(CompletableFuture::join)
552 .collect(Collectors.toList())
553 );
554 }
555
556 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700557 * Returns the contents of {@code ByteBuffer} as byte array.
558 * <p>
559 * WARNING: There is a performance cost due to array copy
560 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700561 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700562 * @param buffer byte buffer
563 * @return byte array containing the byte buffer contents
564 */
565 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
566 int length = buffer.remaining();
567 if (buffer.hasArray()) {
568 int offset = buffer.arrayOffset() + buffer.position();
569 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
570 }
571 byte[] bytes = new byte[length];
572 buffer.duplicate().get(bytes);
573 return bytes;
574 }
575
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700576 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700577 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700578 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700579 * @param it iterable to convert
580 * @param <T> type if item
581 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700582 */
583 public static <T> Stream<T> stream(Iterable<T> it) {
584 return StreamSupport.stream(it.spliterator(), false);
585 }
586
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800587 /**
588 * Converts an optional to a stream.
589 *
590 * @param optional optional to convert
591 * @param <T> type of enclosed value
592 * @return optional as a stream
593 */
594 public static <T> Stream<T> stream(Optional<T> optional) {
595 return optional.map(Stream::of).orElse(Stream.empty());
596 }
597
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800598 // Auxiliary path visitor for recursive directory structure copying.
599 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800600 private Path src;
601 private Path dst;
602 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
603
604 DirectoryCopier(String src, String dst) {
605 this.src = Paths.get(src);
606 this.dst = Paths.get(dst);
607 }
608
609 @Override
610 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
611 Path targetPath = dst.resolve(src.relativize(dir));
612 if (!Files.exists(targetPath)) {
613 Files.createDirectory(targetPath);
614 }
615 return FileVisitResult.CONTINUE;
616 }
617
618 @Override
619 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
620 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
621 return FileVisitResult.CONTINUE;
622 }
623 }
624
tom5f38b3a2014-08-27 23:50:54 -0700625}