Thomas Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame] | 1 | /* |
Ray Milkey | 34c9590 | 2015-04-15 09:47:53 -0700 | [diff] [blame] | 2 | * Copyright 2014-2015 Open Networking Laboratory |
Thomas Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame] | 3 | * |
Thomas Vachuska | 4f1a60c | 2014-10-28 13:39:07 -0700 | [diff] [blame] | 4 | * 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 Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame] | 7 | * |
Thomas Vachuska | 4f1a60c | 2014-10-28 13:39:07 -0700 | [diff] [blame] | 8 | * 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 Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame] | 15 | */ |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 16 | package org.onlab.util; |
| 17 | |
Jian Li | 66f1526 | 2016-03-03 11:18:40 -0800 | [diff] [blame] | 18 | import com.google.common.base.Charsets; |
| 19 | import com.google.common.base.Strings; |
| 20 | import com.google.common.primitives.UnsignedLongs; |
| 21 | import com.google.common.util.concurrent.ThreadFactoryBuilder; |
| 22 | import org.slf4j.Logger; |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 23 | |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 24 | import java.io.BufferedReader; |
| 25 | import java.io.File; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 26 | import java.io.FileInputStream; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 27 | import java.io.IOException; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 28 | import java.io.InputStreamReader; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 29 | import java.nio.ByteBuffer; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 30 | import java.nio.charset.StandardCharsets; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 31 | import java.nio.file.FileVisitResult; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 32 | import java.nio.file.Files; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 33 | import java.nio.file.Path; |
| 34 | import java.nio.file.Paths; |
| 35 | import java.nio.file.SimpleFileVisitor; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 36 | import java.nio.file.StandardCopyOption; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 37 | import java.nio.file.attribute.BasicFileAttributes; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 38 | import java.util.ArrayList; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 39 | import java.util.Arrays; |
Brian O'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 40 | import java.util.Collection; |
Thomas Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 41 | import java.util.Dictionary; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 42 | import java.util.List; |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 43 | import java.util.Optional; |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 44 | import java.util.Random; |
Ray Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 45 | import java.util.Set; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 46 | import java.util.concurrent.CompletableFuture; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 47 | import java.util.concurrent.ExecutionException; |
| 48 | import java.util.concurrent.Future; |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 49 | import java.util.concurrent.ThreadFactory; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 50 | import java.util.concurrent.TimeUnit; |
| 51 | import java.util.concurrent.TimeoutException; |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 52 | import java.util.function.Function; |
| 53 | import java.util.function.Supplier; |
Sho SHIMIZU | 85803e2 | 2016-01-13 21:53:43 -0800 | [diff] [blame] | 54 | import java.util.stream.Collectors; |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 55 | import java.util.stream.Stream; |
| 56 | import java.util.stream.StreamSupport; |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 57 | |
Jian Li | 66f1526 | 2016-03-03 11:18:40 -0800 | [diff] [blame] | 58 | import static java.nio.file.Files.delete; |
| 59 | import static java.nio.file.Files.walkFileTree; |
| 60 | import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory; |
| 61 | import static org.slf4j.LoggerFactory.getLogger; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 62 | |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 63 | /** |
| 64 | * Miscellaneous utility methods. |
| 65 | */ |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 66 | public abstract class Tools { |
| 67 | |
| 68 | private Tools() { |
| 69 | } |
| 70 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 71 | private static final Logger log = getLogger(Tools.class); |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 72 | |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 73 | private static Random random = new Random(); |
| 74 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 75 | /** |
| 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 HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 83 | return new ThreadFactoryBuilder() |
| 84 | .setNameFormat(pattern) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 85 | .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e)) |
| 86 | .build(); |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 87 | } |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 88 | |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 89 | /** |
| 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 Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 93 | * {@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 Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 96 | * |
| 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 Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 102 | 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 Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 123 | return new ThreadFactoryBuilder() |
| 124 | .setThreadFactory(groupedThreadFactory(groupName)) |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 125 | .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern) |
Jian Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 126 | .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e)) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 127 | .build(); |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 128 | } |
| 129 | |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 130 | /** |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 131 | * 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 Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 138 | .setThreadFactory(factory) |
| 139 | .setPriority(Thread.MIN_PRIORITY) |
| 140 | .build(); |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | /** |
Brian O'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 144 | * 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 Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 154 | * Returns the specified item if that item is not null; otherwise throws |
Thomas Vachuska | ca88bb7 | 2015-04-08 19:38:02 -0700 | [diff] [blame] | 155 | * 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 Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 171 | * 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 Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 188 | * 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 | /** |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 205 | * 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 | } |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 234 | |
| 235 | /** |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 236 | * Returns the UTF-8 encoded byte[] representation of a String. |
Jian Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 237 | * @param input input string |
| 238 | * @return UTF-8 encoded byte array |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 239 | */ |
| 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 Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 246 | * @param input input byte array |
| 247 | * @return UTF-8 encoded string |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 248 | */ |
| 249 | public static String toStringUtf8(byte[] input) { |
| 250 | return new String(input, Charsets.UTF_8); |
| 251 | } |
| 252 | |
| 253 | /** |
Madan Jampani | 9eb55d1 | 2015-08-14 07:47:56 -0700 | [diff] [blame] | 254 | * 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 Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 264 | * 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 | /** |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 278 | * 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 | |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 290 | /** |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 291 | * 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 Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 298 | * @param <U> type of function input |
| 299 | * @param <V> type of function output |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 300 | */ |
| 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 Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 316 | * @param <V> type of supplied result |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 317 | */ |
| 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 Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 329 | * 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 Vachuska | c40d463 | 2015-04-09 16:55:03 -0700 | [diff] [blame] | 343 | * 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 | /** |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 357 | * 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 Yuta | 3b3bd1e | 2015-09-22 16:39:33 -0700 | [diff] [blame] | 361 | * @deprecated in Emu release |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 362 | */ |
HIGUCHI Yuta | 3b3bd1e | 2015-09-22 16:39:33 -0700 | [diff] [blame] | 363 | @Deprecated |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 364 | public static List<String> slurp(File path) { |
HIGUCHI Yuta | cf4d617 | 2015-09-22 16:39:33 -0700 | [diff] [blame] | 365 | try ( |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 366 | BufferedReader br = new BufferedReader( |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 367 | new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8)); |
HIGUCHI Yuta | cf4d617 | 2015-09-22 16:39:33 -0700 | [diff] [blame] | 368 | ) { |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 369 | 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 Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 381 | /** |
| 382 | * Purges the specified directory path. 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 390 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 391 | 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 397 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 398 | } |
| 399 | |
| 400 | /** |
| 401 | * Purges the specified directory path. 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 409 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 410 | if (dir.exists() && dir.isDirectory()) { |
| 411 | walkFileTree(Paths.get(dir.getAbsolutePath()), visitor); |
| 412 | if (visitor.exception != null) { |
| 413 | throw visitor.exception; |
| 414 | } |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 415 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 416 | } |
| 417 | |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 418 | // Auxiliary path visitor for recursive directory structure removal. |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 419 | private static class DirectoryDeleter extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 420 | |
| 421 | private IOException exception; |
| 422 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 423 | @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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 442 | this.exception = ioe; |
| 443 | return FileVisitResult.TERMINATE; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 444 | } |
| 445 | } |
| 446 | |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 447 | /** |
| 448 | * Returns a human friendly time ago string for a specified system time. |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 449 | * |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 450 | * @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 Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 471 | |
| 472 | /** |
| 473 | * Copies the specified directory path. 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. 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 Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 500 | /** |
| 501 | * Returns the future value when complete or if future |
| 502 | * completes exceptionally returns the defaultValue. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 503 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 504 | * @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 Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 524 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 525 | * @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 Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 547 | /** |
| 548 | * Returns a future that is completed exceptionally. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 549 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 550 | * @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 SHIMIZU | 85803e2 | 2016-01-13 21:53:43 -0800 | [diff] [blame] | 561 | * 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 Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 577 | * 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 Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 581 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 582 | * @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 Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 596 | /** |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 597 | * Converts an iterable to a stream. |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 598 | * |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 599 | * @param it iterable to convert |
| 600 | * @param <T> type if item |
| 601 | * @return iterable as a stream |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 602 | */ |
| 603 | public static <T> Stream<T> stream(Iterable<T> it) { |
| 604 | return StreamSupport.stream(it.spliterator(), false); |
| 605 | } |
| 606 | |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 607 | /** |
| 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 618 | // Auxiliary path visitor for recursive directory structure copying. |
| 619 | private static class DirectoryCopier extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 620 | 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 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 645 | } |