blob: 136f1821d5210cf8ec5b2bfb37a2a50bdc7a92b1 [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;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070042import java.util.Random;
Ray Milkey36992c82015-11-17 13:31:15 -080043import java.util.Set;
Madan Jampani27b69c62015-05-15 15:49:02 -070044import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070045import java.util.concurrent.ExecutionException;
46import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070047import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070048import java.util.concurrent.TimeUnit;
49import java.util.concurrent.TimeoutException;
Madan Jampania29c6772015-08-17 13:17:07 -070050import java.util.function.Function;
51import java.util.function.Supplier;
Sho SHIMIZU85803e22016-01-13 21:53:43 -080052import java.util.stream.Collectors;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070053import java.util.stream.Stream;
54import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070055
Madan Jampani2bfa94c2015-04-11 05:03:49 -070056import org.slf4j.Logger;
57
Madan Jampanif2f086c2016-01-13 16:15:39 -080058import com.google.common.base.Charsets;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070059import com.google.common.base.Strings;
60import com.google.common.primitives.UnsignedLongs;
61import com.google.common.util.concurrent.ThreadFactoryBuilder;
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) {
102 return new ThreadFactoryBuilder()
103 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -0800104 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -0800105 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
106 .build();
tom5f38b3a2014-08-27 23:50:54 -0700107 }
108
tom782a7cf2014-09-11 23:58:38 -0700109 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800110 * Returns a thread factory that produces threads with MIN_PRIORITY.
111 *
112 * @param factory backing ThreadFactory
113 * @return thread factory
114 */
115 public static ThreadFactory minPriority(ThreadFactory factory) {
116 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800117 .setThreadFactory(factory)
118 .setPriority(Thread.MIN_PRIORITY)
119 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800120 }
121
122 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800123 * Returns true if the collection is null or is empty.
124 *
125 * @param collection collection to test
126 * @return true if null or empty; false otherwise
127 */
128 public static boolean isNullOrEmpty(Collection collection) {
129 return collection == null || collection.isEmpty();
130 }
131
132 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700133 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700134 * not found exception.
135 *
136 * @param item item to check
137 * @param message not found message
138 * @param <T> item type
139 * @return item if not null
140 * @throws org.onlab.util.ItemNotFoundException if item is null
141 */
142 public static <T> T nullIsNotFound(T item, String message) {
143 if (item == null) {
144 throw new ItemNotFoundException(message);
145 }
146 return item;
147 }
148
149 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800150 * Returns the specified set if the set is not null and not empty;
151 * otherwise throws a not found exception.
152 *
153 * @param item set to check
154 * @param message not found message
155 * @param <T> Set item type
156 * @return item if not null and not empty
157 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
158 */
159 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
160 if (item == null || item.isEmpty()) {
161 throw new ItemNotFoundException(message);
162 }
163 return item;
164 }
165
166 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700167 * Returns the specified item if that item is not null; otherwise throws
168 * bad argument exception.
169 *
170 * @param item item to check
171 * @param message not found message
172 * @param <T> item type
173 * @return item if not null
174 * @throws IllegalArgumentException if item is null
175 */
176 public static <T> T nullIsIllegal(T item, String message) {
177 if (item == null) {
178 throw new IllegalArgumentException(message);
179 }
180 return item;
181 }
182
183 /**
tom782a7cf2014-09-11 23:58:38 -0700184 * Converts a string from hex to long.
185 *
186 * @param string hex number in string form; sans 0x
187 * @return long value
188 */
189 public static long fromHex(String string) {
190 return UnsignedLongs.parseUnsignedLong(string, 16);
191 }
192
193 /**
194 * Converts a long value to hex string; 16 wide and sans 0x.
195 *
196 * @param value long value
197 * @return hex string
198 */
199 public static String toHex(long value) {
200 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
201 }
202
203 /**
204 * Converts a long value to hex string; 16 wide and sans 0x.
205 *
206 * @param value long value
207 * @param width string width; zero padded
208 * @return hex string
209 */
210 public static String toHex(long value, int width) {
211 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
212 }
tomf110fff2014-09-26 00:38:18 -0700213
214 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800215 * Returns the UTF-8 encoded byte[] representation of a String.
216 */
217 public static byte[] getBytesUtf8(String input) {
218 return input.getBytes(Charsets.UTF_8);
219 }
220
221 /**
222 * Returns the String representation of UTF-8 encoded byte[].
223 */
224 public static String toStringUtf8(byte[] input) {
225 return new String(input, Charsets.UTF_8);
226 }
227
228 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700229 * Returns a copy of the input byte array.
230 *
231 * @param original input
232 * @return copy of original
233 */
234 public static byte[] copyOf(byte[] original) {
235 return Arrays.copyOf(original, original.length);
236 }
237
238 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700239 * Get property as a string value.
240 *
241 * @param properties properties to be looked up
242 * @param propertyName the name of the property to look up
243 * @return value when the propertyName is defined or return null
244 */
245 public static String get(Dictionary<?, ?> properties, String propertyName) {
246 Object v = properties.get(propertyName);
247 String s = (v instanceof String) ? (String) v :
248 v != null ? v.toString() : null;
249 return Strings.isNullOrEmpty(s) ? null : s.trim();
250 }
251
252 /**
tomf110fff2014-09-26 00:38:18 -0700253 * Suspends the current thread for a specified number of millis.
254 *
255 * @param ms number of millis
256 */
257 public static void delay(int ms) {
258 try {
259 Thread.sleep(ms);
260 } catch (InterruptedException e) {
261 throw new RuntimeException("Interrupted", e);
262 }
263 }
264
tom53efab52014-10-07 17:43:48 -0700265 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700266 * Returns a function that retries execution on failure.
267 * @param base base function
268 * @param exceptionClass type of exception for which to retry
269 * @param maxRetries max number of retries before giving up
270 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
271 * the interval (0, maxDelayBetweenRetries]
272 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700273 * @param <U> type of function input
274 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700275 */
276 public static <U, V> Function<U, V> retryable(Function<U, V> base,
277 Class<? extends Throwable> exceptionClass,
278 int maxRetries,
279 int maxDelayBetweenRetries) {
280 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
281 }
282
283 /**
284 * Returns a Supplier that retries execution on failure.
285 * @param base base supplier
286 * @param exceptionClass type of exception for which to retry
287 * @param maxRetries max number of retries before giving up
288 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
289 * the interval (0, maxDelayBetweenRetries]
290 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700291 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700292 */
293 public static <V> Supplier<V> retryable(Supplier<V> base,
294 Class<? extends Throwable> exceptionClass,
295 int maxRetries,
296 int maxDelayBetweenRetries) {
297 return () -> new RetryingFunction<>(v -> base.get(),
298 exceptionClass,
299 maxRetries,
300 maxDelayBetweenRetries).apply(null);
301 }
302
303 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700304 * Suspends the current thread for a random number of millis between 0 and
305 * the indicated limit.
306 *
307 * @param ms max number of millis
308 */
309 public static void randomDelay(int ms) {
310 try {
311 Thread.sleep(random.nextInt(ms));
312 } catch (InterruptedException e) {
313 throw new RuntimeException("Interrupted", e);
314 }
315 }
316
317 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700318 * Suspends the current thread for a specified number of millis and nanos.
319 *
320 * @param ms number of millis
321 * @param nanos number of nanos
322 */
323 public static void delay(int ms, int nanos) {
324 try {
325 Thread.sleep(ms, nanos);
326 } catch (InterruptedException e) {
327 throw new RuntimeException("Interrupted", e);
328 }
329 }
330
331 /**
tom53efab52014-10-07 17:43:48 -0700332 * Slurps the contents of a file into a list of strings, one per line.
333 *
334 * @param path file path
335 * @return file contents
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700336 * @deprecated in Emu release
tom53efab52014-10-07 17:43:48 -0700337 */
HIGUCHI Yuta3b3bd1e2015-09-22 16:39:33 -0700338 @Deprecated
tom53efab52014-10-07 17:43:48 -0700339 public static List<String> slurp(File path) {
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700340 try (
Ray Milkey705d9bc2014-11-18 08:19:00 -0800341 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800342 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
HIGUCHI Yutacf4d6172015-09-22 16:39:33 -0700343 ) {
tom53efab52014-10-07 17:43:48 -0700344 List<String> lines = new ArrayList<>();
345 String line;
346 while ((line = br.readLine()) != null) {
347 lines.add(line);
348 }
349 return lines;
350
351 } catch (IOException e) {
352 return null;
353 }
354 }
355
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800356 /**
357 * Purges the specified directory path.&nbsp;Use with great caution since
358 * no attempt is made to check for symbolic links, which could result in
359 * deletion of unintended files.
360 *
361 * @param path directory to be removed
362 * @throws java.io.IOException if unable to remove contents
363 */
364 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800365 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700366 File dir = new File(path);
367 if (dir.exists() && dir.isDirectory()) {
368 walkFileTree(Paths.get(path), visitor);
369 if (visitor.exception != null) {
370 throw visitor.exception;
371 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800372 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800373 }
374
375 /**
376 * Purges the specified directory path.&nbsp;Use with great caution since
377 * no attempt is made to check for symbolic links, which could result in
378 * deletion of unintended files.
379 *
380 * @param dir directory to be removed
381 * @throws java.io.IOException if unable to remove contents
382 */
383 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800384 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700385 if (dir.exists() && dir.isDirectory()) {
386 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
387 if (visitor.exception != null) {
388 throw visitor.exception;
389 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800390 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800391 }
392
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800393 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800394 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800395
396 private IOException exception;
397
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800398 @Override
399 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
400 throws IOException {
401 if (attributes.isRegularFile()) {
402 delete(file);
403 }
404 return FileVisitResult.CONTINUE;
405 }
406
407 @Override
408 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
409 throws IOException {
410 delete(directory);
411 return FileVisitResult.CONTINUE;
412 }
413
414 @Override
415 public FileVisitResult visitFileFailed(Path file, IOException ioe)
416 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800417 this.exception = ioe;
418 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800419 }
420 }
421
Madan Jampani30a57f82015-03-02 12:19:41 -0800422 /**
423 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800424 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800425 * @param unixTime system time in millis
426 * @return human friendly time ago
427 */
428 public static String timeAgo(long unixTime) {
429 long deltaMillis = System.currentTimeMillis() - unixTime;
430 long secondsSince = (long) (deltaMillis / 1000.0);
431 long minsSince = (long) (deltaMillis / (1000.0 * 60));
432 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
433 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
434 if (daysSince > 0) {
435 return String.format("%dd ago", daysSince);
436 } else if (hoursSince > 0) {
437 return String.format("%dh ago", hoursSince);
438 } else if (minsSince > 0) {
439 return String.format("%dm ago", minsSince);
440 } else if (secondsSince > 0) {
441 return String.format("%ds ago", secondsSince);
442 } else {
443 return "just now";
444 }
445 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800446
447 /**
448 * Copies the specified directory path.&nbsp;Use with great caution since
449 * no attempt is made to check for symbolic links, which could result in
450 * copy of unintended files.
451 *
452 * @param src directory to be copied
453 * @param dst destination directory to be removed
454 * @throws java.io.IOException if unable to remove contents
455 */
456 public static void copyDirectory(String src, String dst) throws IOException {
457 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
458 }
459
460 /**
461 * Copies the specified directory path.&nbsp;Use with great caution since
462 * no attempt is made to check for symbolic links, which could result in
463 * copy of unintended files.
464 *
465 * @param src directory to be copied
466 * @param dst destination directory to be removed
467 * @throws java.io.IOException if unable to remove contents
468 */
469 public static void copyDirectory(File src, File dst) throws IOException {
470 walkFileTree(Paths.get(src.getAbsolutePath()),
471 new DirectoryCopier(src.getAbsolutePath(),
472 dst.getAbsolutePath()));
473 }
474
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700475 /**
476 * Returns the future value when complete or if future
477 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700478 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700479 * @param future future
480 * @param defaultValue default value
481 * @param <T> future value type
482 * @return future value when complete or if future
483 * completes exceptionally returns the defaultValue.
484 */
485 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
486 try {
487 return future.get();
488 } catch (InterruptedException e) {
489 Thread.currentThread().interrupt();
490 return defaultValue;
491 } catch (ExecutionException e) {
492 return defaultValue;
493 }
494 }
495
496 /**
497 * Returns the future value when complete or if future
498 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700499 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700500 * @param future future
501 * @param timeout time to wait for successful completion
502 * @param timeUnit time unit
503 * @param defaultValue default value
504 * @param <T> future value type
505 * @return future value when complete or if future
506 * completes exceptionally returns the defaultValue.
507 */
508 public static <T> T futureGetOrElse(Future<T> future,
509 long timeout,
510 TimeUnit timeUnit,
511 T defaultValue) {
512 try {
513 return future.get(timeout, timeUnit);
514 } catch (InterruptedException e) {
515 Thread.currentThread().interrupt();
516 return defaultValue;
517 } catch (ExecutionException | TimeoutException e) {
518 return defaultValue;
519 }
520 }
521
Madan Jampani27b69c62015-05-15 15:49:02 -0700522 /**
523 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700524 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700525 * @param t exception
526 * @param <T> future value type
527 * @return future
528 */
529 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
530 CompletableFuture<T> future = new CompletableFuture<>();
531 future.completeExceptionally(t);
532 return future;
533 }
534
535 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800536 * Returns a new CompletableFuture completed with a list of computed values
537 * when all of the given CompletableFuture complete.
538 *
539 * @param futures the CompletableFutures
540 * @param <T> value type of CompletableFuture
541 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
542 */
543 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
544 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
545 .thenApply(v -> futures.stream()
546 .map(CompletableFuture::join)
547 .collect(Collectors.toList())
548 );
549 }
550
551 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700552 * Returns the contents of {@code ByteBuffer} as byte array.
553 * <p>
554 * WARNING: There is a performance cost due to array copy
555 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700556 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700557 * @param buffer byte buffer
558 * @return byte array containing the byte buffer contents
559 */
560 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
561 int length = buffer.remaining();
562 if (buffer.hasArray()) {
563 int offset = buffer.arrayOffset() + buffer.position();
564 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
565 }
566 byte[] bytes = new byte[length];
567 buffer.duplicate().get(bytes);
568 return bytes;
569 }
570
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700571 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700572 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700573 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700574 * @param it iterable to convert
575 * @param <T> type if item
576 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700577 */
578 public static <T> Stream<T> stream(Iterable<T> it) {
579 return StreamSupport.stream(it.spliterator(), false);
580 }
581
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800582 // Auxiliary path visitor for recursive directory structure copying.
583 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800584 private Path src;
585 private Path dst;
586 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
587
588 DirectoryCopier(String src, String dst) {
589 this.src = Paths.get(src);
590 this.dst = Paths.get(dst);
591 }
592
593 @Override
594 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
595 Path targetPath = dst.resolve(src.relativize(dir));
596 if (!Files.exists(targetPath)) {
597 Files.createDirectory(targetPath);
598 }
599 return FileVisitResult.CONTINUE;
600 }
601
602 @Override
603 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
604 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
605 return FileVisitResult.CONTINUE;
606 }
607 }
608
tom5f38b3a2014-08-27 23:50:54 -0700609}