blob: 6df74b05b7c3a1a4a43623177a888eccdb8be6df [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 /**
Yuta HIGUCHIa2a11cd2016-12-19 14:19:11 -0800142 * Returns a thread factory that produces threads with MAX_PRIORITY.
143 *
144 * @param factory backing ThreadFactory
145 * @return thread factory
146 */
147 public static ThreadFactory maxPriority(ThreadFactory factory) {
148 return new ThreadFactoryBuilder()
149 .setThreadFactory(factory)
150 .setPriority(Thread.MAX_PRIORITY)
151 .build();
152 }
153
154 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800155 * Returns true if the collection is null or is empty.
156 *
157 * @param collection collection to test
158 * @return true if null or empty; false otherwise
159 */
160 public static boolean isNullOrEmpty(Collection collection) {
161 return collection == null || collection.isEmpty();
162 }
163
164 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700165 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700166 * not found exception.
167 *
168 * @param item item to check
169 * @param message not found message
170 * @param <T> item type
171 * @return item if not null
172 * @throws org.onlab.util.ItemNotFoundException if item is null
173 */
174 public static <T> T nullIsNotFound(T item, String message) {
175 if (item == null) {
176 throw new ItemNotFoundException(message);
177 }
178 return item;
179 }
180
181 /**
Ray Milkey36992c82015-11-17 13:31:15 -0800182 * Returns the specified set if the set is not null and not empty;
183 * otherwise throws a not found exception.
184 *
185 * @param item set to check
186 * @param message not found message
187 * @param <T> Set item type
188 * @return item if not null and not empty
189 * @throws org.onlab.util.ItemNotFoundException if set is null or empty
190 */
191 public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) {
192 if (item == null || item.isEmpty()) {
193 throw new ItemNotFoundException(message);
194 }
195 return item;
196 }
197
198 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700199 * Returns the specified item if that item is not null; otherwise throws
200 * bad argument exception.
201 *
202 * @param item item to check
203 * @param message not found message
204 * @param <T> item type
205 * @return item if not null
206 * @throws IllegalArgumentException if item is null
207 */
208 public static <T> T nullIsIllegal(T item, String message) {
209 if (item == null) {
210 throw new IllegalArgumentException(message);
211 }
212 return item;
213 }
214
215 /**
tom782a7cf2014-09-11 23:58:38 -0700216 * Converts a string from hex to long.
217 *
218 * @param string hex number in string form; sans 0x
219 * @return long value
220 */
221 public static long fromHex(String string) {
222 return UnsignedLongs.parseUnsignedLong(string, 16);
223 }
224
225 /**
226 * Converts a long value to hex string; 16 wide and sans 0x.
227 *
228 * @param value long value
229 * @return hex string
230 */
231 public static String toHex(long value) {
232 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
233 }
234
235 /**
236 * Converts a long value to hex string; 16 wide and sans 0x.
237 *
238 * @param value long value
239 * @param width string width; zero padded
240 * @return hex string
241 */
242 public static String toHex(long value, int width) {
243 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
244 }
tomf110fff2014-09-26 00:38:18 -0700245
246 /**
Madan Jampanif2f086c2016-01-13 16:15:39 -0800247 * Returns the UTF-8 encoded byte[] representation of a String.
Jian Lidfba7392016-01-22 16:46:58 -0800248 * @param input input string
249 * @return UTF-8 encoded byte array
Madan Jampanif2f086c2016-01-13 16:15:39 -0800250 */
251 public static byte[] getBytesUtf8(String input) {
252 return input.getBytes(Charsets.UTF_8);
253 }
254
255 /**
256 * Returns the String representation of UTF-8 encoded byte[].
Jian Lidfba7392016-01-22 16:46:58 -0800257 * @param input input byte array
258 * @return UTF-8 encoded string
Madan Jampanif2f086c2016-01-13 16:15:39 -0800259 */
260 public static String toStringUtf8(byte[] input) {
261 return new String(input, Charsets.UTF_8);
262 }
263
264 /**
Madan Jampani9eb55d12015-08-14 07:47:56 -0700265 * Returns a copy of the input byte array.
266 *
267 * @param original input
268 * @return copy of original
269 */
270 public static byte[] copyOf(byte[] original) {
271 return Arrays.copyOf(original, original.length);
272 }
273
274 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700275 * Get property as a string value.
276 *
277 * @param properties properties to be looked up
278 * @param propertyName the name of the property to look up
279 * @return value when the propertyName is defined or return null
280 */
281 public static String get(Dictionary<?, ?> properties, String propertyName) {
282 Object v = properties.get(propertyName);
283 String s = (v instanceof String) ? (String) v :
284 v != null ? v.toString() : null;
285 return Strings.isNullOrEmpty(s) ? null : s.trim();
286 }
287
288 /**
Jian Lid9b5f552016-03-11 18:15:31 -0800289 * Get Integer property from the propertyName
290 * Return null if propertyName is not found.
291 *
292 * @param properties properties to be looked up
293 * @param propertyName the name of the property to look up
294 * @return value when the propertyName is defined or return null
295 */
296 public static Integer getIntegerProperty(Dictionary<?, ?> properties,
297 String propertyName) {
298 Integer value;
299 try {
300 String s = get(properties, propertyName);
301 value = Strings.isNullOrEmpty(s) ? null : Integer.valueOf(s);
302 } catch (NumberFormatException | ClassCastException e) {
303 value = null;
304 }
305 return value;
306 }
307
308 /**
309 * Get Integer property from the propertyName
310 * Return default value if propertyName is not found.
311 *
312 * @param properties properties to be looked up
313 * @param propertyName the name of the property to look up
314 * @param defaultValue the default value that to be assigned
315 * @return value when the propertyName is defined or return default value
316 */
317 public static int getIntegerProperty(Dictionary<?, ?> properties,
318 String propertyName,
319 int defaultValue) {
320 try {
321 String s = get(properties, propertyName);
322 return Strings.isNullOrEmpty(s) ? defaultValue : Integer.valueOf(s);
323 } catch (NumberFormatException | ClassCastException e) {
324 return defaultValue;
325 }
326 }
327
328 /**
329 * Check property name is defined and set to true.
330 *
331 * @param properties properties to be looked up
332 * @param propertyName the name of the property to look up
333 * @return value when the propertyName is defined or return null
334 */
335 public static Boolean isPropertyEnabled(Dictionary<?, ?> properties,
336 String propertyName) {
337 Boolean value;
338 try {
339 String s = get(properties, propertyName);
340 value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s);
341 } catch (ClassCastException e) {
342 value = null;
343 }
344 return value;
345 }
346
347 /**
348 * Check property name is defined as set to true.
349 *
350 * @param properties properties to be looked up
351 * @param propertyName the name of the property to look up
352 * @param defaultValue the default value that to be assigned
353 * @return value when the propertyName is defined or return the default value
354 */
355 public static boolean isPropertyEnabled(Dictionary<?, ?> properties,
356 String propertyName,
357 boolean defaultValue) {
358 try {
359 String s = get(properties, propertyName);
360 return Strings.isNullOrEmpty(s) ? defaultValue : Boolean.valueOf(s);
361 } catch (ClassCastException e) {
362 return defaultValue;
363 }
364 }
365
366 /**
tomf110fff2014-09-26 00:38:18 -0700367 * Suspends the current thread for a specified number of millis.
368 *
369 * @param ms number of millis
370 */
371 public static void delay(int ms) {
372 try {
373 Thread.sleep(ms);
374 } catch (InterruptedException e) {
375 throw new RuntimeException("Interrupted", e);
376 }
377 }
378
tom53efab52014-10-07 17:43:48 -0700379 /**
sdn94b00152016-08-30 02:12:32 -0700380 * Get Long property from the propertyName
381 * Return null if propertyName is not found.
382 *
383 * @param properties properties to be looked up
384 * @param propertyName the name of the property to look up
385 * @return value when the propertyName is defined or return null
386 */
387 public static Long getLongProperty(Dictionary<?, ?> properties,
388 String propertyName) {
389 Long value;
390 try {
391 String s = get(properties, propertyName);
392 value = Strings.isNullOrEmpty(s) ? null : Long.valueOf(s);
393 } catch (NumberFormatException | ClassCastException e) {
394 value = null;
395 }
396 return value;
397 }
398
399 /**
Madan Jampania29c6772015-08-17 13:17:07 -0700400 * Returns a function that retries execution on failure.
401 * @param base base function
402 * @param exceptionClass type of exception for which to retry
403 * @param maxRetries max number of retries before giving up
404 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
405 * the interval (0, maxDelayBetweenRetries]
406 * @return function
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700407 * @param <U> type of function input
408 * @param <V> type of function output
Madan Jampania29c6772015-08-17 13:17:07 -0700409 */
410 public static <U, V> Function<U, V> retryable(Function<U, V> base,
411 Class<? extends Throwable> exceptionClass,
412 int maxRetries,
413 int maxDelayBetweenRetries) {
414 return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries);
415 }
416
417 /**
418 * Returns a Supplier that retries execution on failure.
419 * @param base base supplier
420 * @param exceptionClass type of exception for which to retry
421 * @param maxRetries max number of retries before giving up
422 * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from
423 * the interval (0, maxDelayBetweenRetries]
424 * @return supplier
Thomas Vachuska87ae1d92015-08-19 17:39:11 -0700425 * @param <V> type of supplied result
Madan Jampania29c6772015-08-17 13:17:07 -0700426 */
427 public static <V> Supplier<V> retryable(Supplier<V> base,
428 Class<? extends Throwable> exceptionClass,
429 int maxRetries,
430 int maxDelayBetweenRetries) {
431 return () -> new RetryingFunction<>(v -> base.get(),
432 exceptionClass,
433 maxRetries,
434 maxDelayBetweenRetries).apply(null);
435 }
436
437 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700438 * Suspends the current thread for a random number of millis between 0 and
439 * the indicated limit.
440 *
441 * @param ms max number of millis
442 */
443 public static void randomDelay(int ms) {
444 try {
445 Thread.sleep(random.nextInt(ms));
446 } catch (InterruptedException e) {
447 throw new RuntimeException("Interrupted", e);
448 }
449 }
450
451 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700452 * Suspends the current thread for a specified number of millis and nanos.
453 *
454 * @param ms number of millis
455 * @param nanos number of nanos
456 */
457 public static void delay(int ms, int nanos) {
458 try {
459 Thread.sleep(ms, nanos);
460 } catch (InterruptedException e) {
461 throw new RuntimeException("Interrupted", e);
462 }
463 }
464
465 /**
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800466 * Purges 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 * deletion of unintended files.
469 *
470 * @param path directory to be removed
471 * @throws java.io.IOException if unable to remove contents
472 */
473 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800474 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700475 File dir = new File(path);
476 if (dir.exists() && dir.isDirectory()) {
477 walkFileTree(Paths.get(path), visitor);
478 if (visitor.exception != null) {
479 throw visitor.exception;
480 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800481 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800482 }
483
484 /**
485 * Purges the specified directory path.&nbsp;Use with great caution since
486 * no attempt is made to check for symbolic links, which could result in
487 * deletion of unintended files.
488 *
489 * @param dir directory to be removed
490 * @throws java.io.IOException if unable to remove contents
491 */
492 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800493 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700494 if (dir.exists() && dir.isDirectory()) {
495 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
496 if (visitor.exception != null) {
497 throw visitor.exception;
498 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800499 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800500 }
501
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800502 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800503 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800504
505 private IOException exception;
506
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800507 @Override
508 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
509 throws IOException {
510 if (attributes.isRegularFile()) {
511 delete(file);
512 }
513 return FileVisitResult.CONTINUE;
514 }
515
516 @Override
517 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
518 throws IOException {
519 delete(directory);
520 return FileVisitResult.CONTINUE;
521 }
522
523 @Override
524 public FileVisitResult visitFileFailed(Path file, IOException ioe)
525 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800526 this.exception = ioe;
527 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800528 }
529 }
530
Madan Jampani30a57f82015-03-02 12:19:41 -0800531 /**
532 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800533 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800534 * @param unixTime system time in millis
535 * @return human friendly time ago
536 */
537 public static String timeAgo(long unixTime) {
538 long deltaMillis = System.currentTimeMillis() - unixTime;
539 long secondsSince = (long) (deltaMillis / 1000.0);
540 long minsSince = (long) (deltaMillis / (1000.0 * 60));
541 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
542 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
543 if (daysSince > 0) {
544 return String.format("%dd ago", daysSince);
545 } else if (hoursSince > 0) {
546 return String.format("%dh ago", hoursSince);
547 } else if (minsSince > 0) {
548 return String.format("%dm ago", minsSince);
549 } else if (secondsSince > 0) {
550 return String.format("%ds ago", secondsSince);
551 } else {
552 return "just now";
553 }
554 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800555
556 /**
557 * Copies the specified directory path.&nbsp;Use with great caution since
558 * no attempt is made to check for symbolic links, which could result in
559 * copy of unintended files.
560 *
561 * @param src directory to be copied
562 * @param dst destination directory to be removed
563 * @throws java.io.IOException if unable to remove contents
564 */
565 public static void copyDirectory(String src, String dst) throws IOException {
566 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
567 }
568
569 /**
570 * Copies the specified directory path.&nbsp;Use with great caution since
571 * no attempt is made to check for symbolic links, which could result in
572 * copy of unintended files.
573 *
574 * @param src directory to be copied
575 * @param dst destination directory to be removed
576 * @throws java.io.IOException if unable to remove contents
577 */
578 public static void copyDirectory(File src, File dst) throws IOException {
579 walkFileTree(Paths.get(src.getAbsolutePath()),
580 new DirectoryCopier(src.getAbsolutePath(),
581 dst.getAbsolutePath()));
582 }
583
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700584 /**
585 * Returns the future value when complete or if future
586 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700587 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700588 * @param future future
589 * @param defaultValue default value
590 * @param <T> future value type
591 * @return future value when complete or if future
592 * completes exceptionally returns the defaultValue.
593 */
594 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
595 try {
596 return future.get();
597 } catch (InterruptedException e) {
598 Thread.currentThread().interrupt();
599 return defaultValue;
600 } catch (ExecutionException e) {
601 return defaultValue;
602 }
603 }
604
605 /**
606 * Returns the future value when complete or if future
607 * completes exceptionally returns the defaultValue.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700608 *
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700609 * @param future future
610 * @param timeout time to wait for successful completion
611 * @param timeUnit time unit
612 * @param defaultValue default value
613 * @param <T> future value type
614 * @return future value when complete or if future
615 * completes exceptionally returns the defaultValue.
616 */
617 public static <T> T futureGetOrElse(Future<T> future,
618 long timeout,
619 TimeUnit timeUnit,
620 T defaultValue) {
621 try {
622 return future.get(timeout, timeUnit);
623 } catch (InterruptedException e) {
624 Thread.currentThread().interrupt();
625 return defaultValue;
626 } catch (ExecutionException | TimeoutException e) {
627 return defaultValue;
628 }
629 }
630
Madan Jampani27b69c62015-05-15 15:49:02 -0700631 /**
632 * Returns a future that is completed exceptionally.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700633 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700634 * @param t exception
635 * @param <T> future value type
636 * @return future
637 */
638 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
639 CompletableFuture<T> future = new CompletableFuture<>();
640 future.completeExceptionally(t);
641 return future;
642 }
643
644 /**
Sho SHIMIZU85803e22016-01-13 21:53:43 -0800645 * Returns a new CompletableFuture completed with a list of computed values
646 * when all of the given CompletableFuture complete.
647 *
648 * @param futures the CompletableFutures
649 * @param <T> value type of CompletableFuture
650 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
651 */
652 public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) {
653 return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()]))
654 .thenApply(v -> futures.stream()
655 .map(CompletableFuture::join)
656 .collect(Collectors.toList())
657 );
658 }
659
660 /**
Madan Jampani307a21e2016-09-01 15:49:47 -0700661 * Returns a new CompletableFuture completed by reducing a list of computed values
662 * when all of the given CompletableFuture complete.
663 *
664 * @param futures the CompletableFutures
665 * @param reducer reducer for computing the result
666 * @param emptyValue zero value to be returned if the input future list is empty
667 * @param <T> value type of CompletableFuture
668 * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete
669 */
670 public static <T> CompletableFuture<T> allOf(List<CompletableFuture<T>> futures,
671 BinaryOperator<T> reducer,
672 T emptyValue) {
673 return Tools.allOf(futures)
674 .thenApply(resultList -> resultList.stream().reduce(reducer).orElse(emptyValue));
675 }
676
677 /**
678 * Returns a new CompletableFuture completed by with the first positive result from a list of
679 * input CompletableFutures.
680 *
681 * @param futures the input list of CompletableFutures
682 * @param positiveResultMatcher matcher to identify a positive result
683 * @param negativeResult value to complete with if none of the futures complete with a positive result
684 * @param <T> value type of CompletableFuture
685 * @return a new CompletableFuture
686 */
687 public static <T> CompletableFuture<T> firstOf(List<CompletableFuture<T>> futures,
688 Match<T> positiveResultMatcher,
689 T negativeResult) {
690 CompletableFuture<T> responseFuture = new CompletableFuture<>();
691 Tools.allOf(Lists.transform(futures, future -> future.thenAccept(r -> {
692 if (positiveResultMatcher.matches(r)) {
693 responseFuture.complete(r);
694 }
695 }))).whenComplete((r, e) -> {
696 if (!responseFuture.isDone()) {
697 if (e != null) {
698 responseFuture.completeExceptionally(e);
699 } else {
700 responseFuture.complete(negativeResult);
701 }
702 }
703 });
704 return responseFuture;
705 }
706
707 /**
Madan Jampani27b69c62015-05-15 15:49:02 -0700708 * Returns the contents of {@code ByteBuffer} as byte array.
709 * <p>
710 * WARNING: There is a performance cost due to array copy
711 * when using this method.
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700712 *
Madan Jampani27b69c62015-05-15 15:49:02 -0700713 * @param buffer byte buffer
714 * @return byte array containing the byte buffer contents
715 */
716 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
717 int length = buffer.remaining();
718 if (buffer.hasArray()) {
719 int offset = buffer.arrayOffset() + buffer.position();
720 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
721 }
722 byte[] bytes = new byte[length];
723 buffer.duplicate().get(bytes);
724 return bytes;
725 }
726
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700727 /**
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700728 * Converts an iterable to a stream.
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700729 *
Thomas Vachuskad894b5d2015-07-30 11:59:07 -0700730 * @param it iterable to convert
731 * @param <T> type if item
732 * @return iterable as a stream
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700733 */
734 public static <T> Stream<T> stream(Iterable<T> it) {
735 return StreamSupport.stream(it.spliterator(), false);
736 }
737
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800738 /**
739 * Converts an optional to a stream.
740 *
741 * @param optional optional to convert
742 * @param <T> type of enclosed value
743 * @return optional as a stream
744 */
Sho SHIMIZU6ac20982016-05-04 09:50:54 -0700745 public static <T> Stream<T> stream(Optional<? extends T> optional) {
HIGUCHI Yuta0bc256f2016-05-06 15:28:26 -0700746 return optional.map(x -> Stream.<T>of(x)).orElse(Stream.empty());
Sho SHIMIZUb5638b82016-02-11 14:55:05 -0800747 }
748
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800749 // Auxiliary path visitor for recursive directory structure copying.
750 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800751 private Path src;
752 private Path dst;
753 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
754
755 DirectoryCopier(String src, String dst) {
756 this.src = Paths.get(src);
757 this.dst = Paths.get(dst);
758 }
759
760 @Override
761 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
762 Path targetPath = dst.resolve(src.relativize(dir));
763 if (!Files.exists(targetPath)) {
764 Files.createDirectory(targetPath);
765 }
766 return FileVisitResult.CONTINUE;
767 }
768
769 @Override
770 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
771 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
772 return FileVisitResult.CONTINUE;
773 }
774 }
775
tom5f38b3a2014-08-27 23:50:54 -0700776}