Thomas Vachuska | 24c849c | 2014-10-27 09:53:05 -0700 | [diff] [blame] | 1 | /* |
Brian O'Connor | 5ab426f | 2016-04-09 01:19:45 -0700 | [diff] [blame] | 2 | * Copyright 2014-present 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.File; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 25 | import java.io.IOException; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 26 | import java.nio.ByteBuffer; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 27 | import java.nio.file.FileVisitResult; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 28 | import java.nio.file.Files; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 29 | import java.nio.file.Path; |
| 30 | import java.nio.file.Paths; |
| 31 | import java.nio.file.SimpleFileVisitor; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 32 | import java.nio.file.StandardCopyOption; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 33 | import java.nio.file.attribute.BasicFileAttributes; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 34 | import java.util.Arrays; |
Brian O'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 35 | import java.util.Collection; |
Thomas Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 36 | import java.util.Dictionary; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 37 | import java.util.List; |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 38 | import java.util.Optional; |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 39 | import java.util.Random; |
Ray Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 40 | import java.util.Set; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 41 | import java.util.concurrent.CompletableFuture; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 42 | import java.util.concurrent.ExecutionException; |
| 43 | import java.util.concurrent.Future; |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 44 | import java.util.concurrent.ThreadFactory; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 45 | import java.util.concurrent.TimeUnit; |
| 46 | import java.util.concurrent.TimeoutException; |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 47 | import java.util.function.Function; |
| 48 | import java.util.function.Supplier; |
Sho SHIMIZU | 85803e2 | 2016-01-13 21:53:43 -0800 | [diff] [blame] | 49 | import java.util.stream.Collectors; |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 50 | import java.util.stream.Stream; |
| 51 | import java.util.stream.StreamSupport; |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 52 | |
Jian Li | 66f1526 | 2016-03-03 11:18:40 -0800 | [diff] [blame] | 53 | import static java.nio.file.Files.delete; |
| 54 | import static java.nio.file.Files.walkFileTree; |
| 55 | import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory; |
| 56 | import static org.slf4j.LoggerFactory.getLogger; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 57 | |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 58 | /** |
| 59 | * Miscellaneous utility methods. |
| 60 | */ |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 61 | public abstract class Tools { |
| 62 | |
| 63 | private Tools() { |
| 64 | } |
| 65 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 66 | private static final Logger log = getLogger(Tools.class); |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 67 | |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 68 | private static Random random = new Random(); |
| 69 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 70 | /** |
| 71 | * Returns a thread factory that produces threads named according to the |
| 72 | * supplied name pattern. |
| 73 | * |
| 74 | * @param pattern name pattern |
| 75 | * @return thread factory |
| 76 | */ |
| 77 | public static ThreadFactory namedThreads(String pattern) { |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 78 | return new ThreadFactoryBuilder() |
| 79 | .setNameFormat(pattern) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 80 | .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e)) |
| 81 | .build(); |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 82 | } |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 83 | |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 84 | /** |
| 85 | * Returns a thread factory that produces threads named according to the |
| 86 | * supplied name pattern and from the specified thread-group. The thread |
| 87 | * 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] | 88 | * {@code onos/intent}. The thread names will be produced by converting |
| 89 | * the thread group name into dash-delimited format and pre-pended to the |
| 90 | * specified pattern. |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 91 | * |
| 92 | * @param groupName group name in slash-delimited format to indicate hierarchy |
| 93 | * @param pattern name pattern |
| 94 | * @return thread factory |
| 95 | */ |
| 96 | public static ThreadFactory groupedThreads(String groupName, String pattern) { |
Jian Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 97 | return groupedThreads(groupName, pattern, log); |
| 98 | } |
| 99 | |
| 100 | /** |
| 101 | * Returns a thread factory that produces threads named according to the |
| 102 | * supplied name pattern and from the specified thread-group. The thread |
| 103 | * group name is expected to be specified in slash-delimited format, e.g. |
| 104 | * {@code onos/intent}. The thread names will be produced by converting |
| 105 | * the thread group name into dash-delimited format and pre-pended to the |
| 106 | * specified pattern. If a logger is specified, it will use the logger to |
| 107 | * print out the exception if it has any. |
| 108 | * |
| 109 | * @param groupName group name in slash-delimited format to indicate hierarchy |
| 110 | * @param pattern name pattern |
| 111 | * @param logger logger |
| 112 | * @return thread factory |
| 113 | */ |
| 114 | public static ThreadFactory groupedThreads(String groupName, String pattern, Logger logger) { |
| 115 | if (logger == null) { |
| 116 | return groupedThreads(groupName, pattern); |
| 117 | } |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 118 | return new ThreadFactoryBuilder() |
| 119 | .setThreadFactory(groupedThreadFactory(groupName)) |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 120 | .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern) |
Jian Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 121 | .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e)) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 122 | .build(); |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 123 | } |
| 124 | |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 125 | /** |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 126 | * Returns a thread factory that produces threads with MIN_PRIORITY. |
| 127 | * |
| 128 | * @param factory backing ThreadFactory |
| 129 | * @return thread factory |
| 130 | */ |
| 131 | public static ThreadFactory minPriority(ThreadFactory factory) { |
| 132 | return new ThreadFactoryBuilder() |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 133 | .setThreadFactory(factory) |
| 134 | .setPriority(Thread.MIN_PRIORITY) |
| 135 | .build(); |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 136 | } |
| 137 | |
| 138 | /** |
Brian O'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 139 | * Returns true if the collection is null or is empty. |
| 140 | * |
| 141 | * @param collection collection to test |
| 142 | * @return true if null or empty; false otherwise |
| 143 | */ |
| 144 | public static boolean isNullOrEmpty(Collection collection) { |
| 145 | return collection == null || collection.isEmpty(); |
| 146 | } |
| 147 | |
| 148 | /** |
Ray Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 149 | * Returns the specified item if that item is not null; otherwise throws |
Thomas Vachuska | ca88bb7 | 2015-04-08 19:38:02 -0700 | [diff] [blame] | 150 | * not found exception. |
| 151 | * |
| 152 | * @param item item to check |
| 153 | * @param message not found message |
| 154 | * @param <T> item type |
| 155 | * @return item if not null |
| 156 | * @throws org.onlab.util.ItemNotFoundException if item is null |
| 157 | */ |
| 158 | public static <T> T nullIsNotFound(T item, String message) { |
| 159 | if (item == null) { |
| 160 | throw new ItemNotFoundException(message); |
| 161 | } |
| 162 | return item; |
| 163 | } |
| 164 | |
| 165 | /** |
Ray Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 166 | * Returns the specified set if the set is not null and not empty; |
| 167 | * otherwise throws a not found exception. |
| 168 | * |
| 169 | * @param item set to check |
| 170 | * @param message not found message |
| 171 | * @param <T> Set item type |
| 172 | * @return item if not null and not empty |
| 173 | * @throws org.onlab.util.ItemNotFoundException if set is null or empty |
| 174 | */ |
| 175 | public static <T> Set<T> emptyIsNotFound(Set<T> item, String message) { |
| 176 | if (item == null || item.isEmpty()) { |
| 177 | throw new ItemNotFoundException(message); |
| 178 | } |
| 179 | return item; |
| 180 | } |
| 181 | |
| 182 | /** |
Ray Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 183 | * Returns the specified item if that item is not null; otherwise throws |
| 184 | * bad argument exception. |
| 185 | * |
| 186 | * @param item item to check |
| 187 | * @param message not found message |
| 188 | * @param <T> item type |
| 189 | * @return item if not null |
| 190 | * @throws IllegalArgumentException if item is null |
| 191 | */ |
| 192 | public static <T> T nullIsIllegal(T item, String message) { |
| 193 | if (item == null) { |
| 194 | throw new IllegalArgumentException(message); |
| 195 | } |
| 196 | return item; |
| 197 | } |
| 198 | |
| 199 | /** |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 200 | * Converts a string from hex to long. |
| 201 | * |
| 202 | * @param string hex number in string form; sans 0x |
| 203 | * @return long value |
| 204 | */ |
| 205 | public static long fromHex(String string) { |
| 206 | return UnsignedLongs.parseUnsignedLong(string, 16); |
| 207 | } |
| 208 | |
| 209 | /** |
| 210 | * Converts a long value to hex string; 16 wide and sans 0x. |
| 211 | * |
| 212 | * @param value long value |
| 213 | * @return hex string |
| 214 | */ |
| 215 | public static String toHex(long value) { |
| 216 | return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0'); |
| 217 | } |
| 218 | |
| 219 | /** |
| 220 | * Converts a long value to hex string; 16 wide and sans 0x. |
| 221 | * |
| 222 | * @param value long value |
| 223 | * @param width string width; zero padded |
| 224 | * @return hex string |
| 225 | */ |
| 226 | public static String toHex(long value, int width) { |
| 227 | return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0'); |
| 228 | } |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 229 | |
| 230 | /** |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 231 | * Returns the UTF-8 encoded byte[] representation of a String. |
Jian Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 232 | * @param input input string |
| 233 | * @return UTF-8 encoded byte array |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 234 | */ |
| 235 | public static byte[] getBytesUtf8(String input) { |
| 236 | return input.getBytes(Charsets.UTF_8); |
| 237 | } |
| 238 | |
| 239 | /** |
| 240 | * Returns the String representation of UTF-8 encoded byte[]. |
Jian Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 241 | * @param input input byte array |
| 242 | * @return UTF-8 encoded string |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 243 | */ |
| 244 | public static String toStringUtf8(byte[] input) { |
| 245 | return new String(input, Charsets.UTF_8); |
| 246 | } |
| 247 | |
| 248 | /** |
Madan Jampani | 9eb55d1 | 2015-08-14 07:47:56 -0700 | [diff] [blame] | 249 | * Returns a copy of the input byte array. |
| 250 | * |
| 251 | * @param original input |
| 252 | * @return copy of original |
| 253 | */ |
| 254 | public static byte[] copyOf(byte[] original) { |
| 255 | return Arrays.copyOf(original, original.length); |
| 256 | } |
| 257 | |
| 258 | /** |
Thomas Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 259 | * Get property as a string value. |
| 260 | * |
| 261 | * @param properties properties to be looked up |
| 262 | * @param propertyName the name of the property to look up |
| 263 | * @return value when the propertyName is defined or return null |
| 264 | */ |
| 265 | public static String get(Dictionary<?, ?> properties, String propertyName) { |
| 266 | Object v = properties.get(propertyName); |
| 267 | String s = (v instanceof String) ? (String) v : |
| 268 | v != null ? v.toString() : null; |
| 269 | return Strings.isNullOrEmpty(s) ? null : s.trim(); |
| 270 | } |
| 271 | |
| 272 | /** |
Jian Li | d9b5f55 | 2016-03-11 18:15:31 -0800 | [diff] [blame] | 273 | * Get Integer property from the propertyName |
| 274 | * Return null if propertyName is not found. |
| 275 | * |
| 276 | * @param properties properties to be looked up |
| 277 | * @param propertyName the name of the property to look up |
| 278 | * @return value when the propertyName is defined or return null |
| 279 | */ |
| 280 | public static Integer getIntegerProperty(Dictionary<?, ?> properties, |
| 281 | String propertyName) { |
| 282 | Integer value; |
| 283 | try { |
| 284 | String s = get(properties, propertyName); |
| 285 | value = Strings.isNullOrEmpty(s) ? null : Integer.valueOf(s); |
| 286 | } catch (NumberFormatException | ClassCastException e) { |
| 287 | value = null; |
| 288 | } |
| 289 | return value; |
| 290 | } |
| 291 | |
| 292 | /** |
| 293 | * Get Integer property from the propertyName |
| 294 | * Return default value if propertyName is not found. |
| 295 | * |
| 296 | * @param properties properties to be looked up |
| 297 | * @param propertyName the name of the property to look up |
| 298 | * @param defaultValue the default value that to be assigned |
| 299 | * @return value when the propertyName is defined or return default value |
| 300 | */ |
| 301 | public static int getIntegerProperty(Dictionary<?, ?> properties, |
| 302 | String propertyName, |
| 303 | int defaultValue) { |
| 304 | try { |
| 305 | String s = get(properties, propertyName); |
| 306 | return Strings.isNullOrEmpty(s) ? defaultValue : Integer.valueOf(s); |
| 307 | } catch (NumberFormatException | ClassCastException e) { |
| 308 | return defaultValue; |
| 309 | } |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * Check property name is defined and set to true. |
| 314 | * |
| 315 | * @param properties properties to be looked up |
| 316 | * @param propertyName the name of the property to look up |
| 317 | * @return value when the propertyName is defined or return null |
| 318 | */ |
| 319 | public static Boolean isPropertyEnabled(Dictionary<?, ?> properties, |
| 320 | String propertyName) { |
| 321 | Boolean value; |
| 322 | try { |
| 323 | String s = get(properties, propertyName); |
| 324 | value = Strings.isNullOrEmpty(s) ? null : Boolean.valueOf(s); |
| 325 | } catch (ClassCastException e) { |
| 326 | value = null; |
| 327 | } |
| 328 | return value; |
| 329 | } |
| 330 | |
| 331 | /** |
| 332 | * Check property name is defined as set to true. |
| 333 | * |
| 334 | * @param properties properties to be looked up |
| 335 | * @param propertyName the name of the property to look up |
| 336 | * @param defaultValue the default value that to be assigned |
| 337 | * @return value when the propertyName is defined or return the default value |
| 338 | */ |
| 339 | public static boolean isPropertyEnabled(Dictionary<?, ?> properties, |
| 340 | String propertyName, |
| 341 | boolean defaultValue) { |
| 342 | try { |
| 343 | String s = get(properties, propertyName); |
| 344 | return Strings.isNullOrEmpty(s) ? defaultValue : Boolean.valueOf(s); |
| 345 | } catch (ClassCastException e) { |
| 346 | return defaultValue; |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | /** |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 351 | * Suspends the current thread for a specified number of millis. |
| 352 | * |
| 353 | * @param ms number of millis |
| 354 | */ |
| 355 | public static void delay(int ms) { |
| 356 | try { |
| 357 | Thread.sleep(ms); |
| 358 | } catch (InterruptedException e) { |
| 359 | throw new RuntimeException("Interrupted", e); |
| 360 | } |
| 361 | } |
| 362 | |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 363 | /** |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 364 | * Returns a function that retries execution on failure. |
| 365 | * @param base base function |
| 366 | * @param exceptionClass type of exception for which to retry |
| 367 | * @param maxRetries max number of retries before giving up |
| 368 | * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from |
| 369 | * the interval (0, maxDelayBetweenRetries] |
| 370 | * @return function |
Thomas Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 371 | * @param <U> type of function input |
| 372 | * @param <V> type of function output |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 373 | */ |
| 374 | public static <U, V> Function<U, V> retryable(Function<U, V> base, |
| 375 | Class<? extends Throwable> exceptionClass, |
| 376 | int maxRetries, |
| 377 | int maxDelayBetweenRetries) { |
| 378 | return new RetryingFunction<>(base, exceptionClass, maxRetries, maxDelayBetweenRetries); |
| 379 | } |
| 380 | |
| 381 | /** |
| 382 | * Returns a Supplier that retries execution on failure. |
| 383 | * @param base base supplier |
| 384 | * @param exceptionClass type of exception for which to retry |
| 385 | * @param maxRetries max number of retries before giving up |
| 386 | * @param maxDelayBetweenRetries max delay between successive retries. The actual delay is randomly picked from |
| 387 | * the interval (0, maxDelayBetweenRetries] |
| 388 | * @return supplier |
Thomas Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 389 | * @param <V> type of supplied result |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 390 | */ |
| 391 | public static <V> Supplier<V> retryable(Supplier<V> base, |
| 392 | Class<? extends Throwable> exceptionClass, |
| 393 | int maxRetries, |
| 394 | int maxDelayBetweenRetries) { |
| 395 | return () -> new RetryingFunction<>(v -> base.get(), |
| 396 | exceptionClass, |
| 397 | maxRetries, |
| 398 | maxDelayBetweenRetries).apply(null); |
| 399 | } |
| 400 | |
| 401 | /** |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 402 | * Suspends the current thread for a random number of millis between 0 and |
| 403 | * the indicated limit. |
| 404 | * |
| 405 | * @param ms max number of millis |
| 406 | */ |
| 407 | public static void randomDelay(int ms) { |
| 408 | try { |
| 409 | Thread.sleep(random.nextInt(ms)); |
| 410 | } catch (InterruptedException e) { |
| 411 | throw new RuntimeException("Interrupted", e); |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | /** |
Thomas Vachuska | c40d463 | 2015-04-09 16:55:03 -0700 | [diff] [blame] | 416 | * Suspends the current thread for a specified number of millis and nanos. |
| 417 | * |
| 418 | * @param ms number of millis |
| 419 | * @param nanos number of nanos |
| 420 | */ |
| 421 | public static void delay(int ms, int nanos) { |
| 422 | try { |
| 423 | Thread.sleep(ms, nanos); |
| 424 | } catch (InterruptedException e) { |
| 425 | throw new RuntimeException("Interrupted", e); |
| 426 | } |
| 427 | } |
| 428 | |
| 429 | /** |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 430 | * Purges the specified directory path. Use with great caution since |
| 431 | * no attempt is made to check for symbolic links, which could result in |
| 432 | * deletion of unintended files. |
| 433 | * |
| 434 | * @param path directory to be removed |
| 435 | * @throws java.io.IOException if unable to remove contents |
| 436 | */ |
| 437 | public static void removeDirectory(String path) throws IOException { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 438 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 439 | File dir = new File(path); |
| 440 | if (dir.exists() && dir.isDirectory()) { |
| 441 | walkFileTree(Paths.get(path), visitor); |
| 442 | if (visitor.exception != null) { |
| 443 | throw visitor.exception; |
| 444 | } |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 445 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 446 | } |
| 447 | |
| 448 | /** |
| 449 | * Purges the specified directory path. Use with great caution since |
| 450 | * no attempt is made to check for symbolic links, which could result in |
| 451 | * deletion of unintended files. |
| 452 | * |
| 453 | * @param dir directory to be removed |
| 454 | * @throws java.io.IOException if unable to remove contents |
| 455 | */ |
| 456 | public static void removeDirectory(File dir) throws IOException { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 457 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 458 | if (dir.exists() && dir.isDirectory()) { |
| 459 | walkFileTree(Paths.get(dir.getAbsolutePath()), visitor); |
| 460 | if (visitor.exception != null) { |
| 461 | throw visitor.exception; |
| 462 | } |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 463 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 464 | } |
| 465 | |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 466 | // Auxiliary path visitor for recursive directory structure removal. |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 467 | private static class DirectoryDeleter extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 468 | |
| 469 | private IOException exception; |
| 470 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 471 | @Override |
| 472 | public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) |
| 473 | throws IOException { |
| 474 | if (attributes.isRegularFile()) { |
| 475 | delete(file); |
| 476 | } |
| 477 | return FileVisitResult.CONTINUE; |
| 478 | } |
| 479 | |
| 480 | @Override |
| 481 | public FileVisitResult postVisitDirectory(Path directory, IOException ioe) |
| 482 | throws IOException { |
| 483 | delete(directory); |
| 484 | return FileVisitResult.CONTINUE; |
| 485 | } |
| 486 | |
| 487 | @Override |
| 488 | public FileVisitResult visitFileFailed(Path file, IOException ioe) |
| 489 | throws IOException { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 490 | this.exception = ioe; |
| 491 | return FileVisitResult.TERMINATE; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 492 | } |
| 493 | } |
| 494 | |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 495 | /** |
| 496 | * Returns a human friendly time ago string for a specified system time. |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 497 | * |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 498 | * @param unixTime system time in millis |
| 499 | * @return human friendly time ago |
| 500 | */ |
| 501 | public static String timeAgo(long unixTime) { |
| 502 | long deltaMillis = System.currentTimeMillis() - unixTime; |
| 503 | long secondsSince = (long) (deltaMillis / 1000.0); |
| 504 | long minsSince = (long) (deltaMillis / (1000.0 * 60)); |
| 505 | long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60)); |
| 506 | long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24)); |
| 507 | if (daysSince > 0) { |
| 508 | return String.format("%dd ago", daysSince); |
| 509 | } else if (hoursSince > 0) { |
| 510 | return String.format("%dh ago", hoursSince); |
| 511 | } else if (minsSince > 0) { |
| 512 | return String.format("%dm ago", minsSince); |
| 513 | } else if (secondsSince > 0) { |
| 514 | return String.format("%ds ago", secondsSince); |
| 515 | } else { |
| 516 | return "just now"; |
| 517 | } |
| 518 | } |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 519 | |
| 520 | /** |
| 521 | * Copies the specified directory path. Use with great caution since |
| 522 | * no attempt is made to check for symbolic links, which could result in |
| 523 | * copy of unintended files. |
| 524 | * |
| 525 | * @param src directory to be copied |
| 526 | * @param dst destination directory to be removed |
| 527 | * @throws java.io.IOException if unable to remove contents |
| 528 | */ |
| 529 | public static void copyDirectory(String src, String dst) throws IOException { |
| 530 | walkFileTree(Paths.get(src), new DirectoryCopier(src, dst)); |
| 531 | } |
| 532 | |
| 533 | /** |
| 534 | * Copies the specified directory path. Use with great caution since |
| 535 | * no attempt is made to check for symbolic links, which could result in |
| 536 | * copy of unintended files. |
| 537 | * |
| 538 | * @param src directory to be copied |
| 539 | * @param dst destination directory to be removed |
| 540 | * @throws java.io.IOException if unable to remove contents |
| 541 | */ |
| 542 | public static void copyDirectory(File src, File dst) throws IOException { |
| 543 | walkFileTree(Paths.get(src.getAbsolutePath()), |
| 544 | new DirectoryCopier(src.getAbsolutePath(), |
| 545 | dst.getAbsolutePath())); |
| 546 | } |
| 547 | |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 548 | /** |
| 549 | * Returns the future value when complete or if future |
| 550 | * completes exceptionally returns the defaultValue. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 551 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 552 | * @param future future |
| 553 | * @param defaultValue default value |
| 554 | * @param <T> future value type |
| 555 | * @return future value when complete or if future |
| 556 | * completes exceptionally returns the defaultValue. |
| 557 | */ |
| 558 | public static <T> T futureGetOrElse(Future<T> future, T defaultValue) { |
| 559 | try { |
| 560 | return future.get(); |
| 561 | } catch (InterruptedException e) { |
| 562 | Thread.currentThread().interrupt(); |
| 563 | return defaultValue; |
| 564 | } catch (ExecutionException e) { |
| 565 | return defaultValue; |
| 566 | } |
| 567 | } |
| 568 | |
| 569 | /** |
| 570 | * Returns the future value when complete or if future |
| 571 | * completes exceptionally returns the defaultValue. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 572 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 573 | * @param future future |
| 574 | * @param timeout time to wait for successful completion |
| 575 | * @param timeUnit time unit |
| 576 | * @param defaultValue default value |
| 577 | * @param <T> future value type |
| 578 | * @return future value when complete or if future |
| 579 | * completes exceptionally returns the defaultValue. |
| 580 | */ |
| 581 | public static <T> T futureGetOrElse(Future<T> future, |
| 582 | long timeout, |
| 583 | TimeUnit timeUnit, |
| 584 | T defaultValue) { |
| 585 | try { |
| 586 | return future.get(timeout, timeUnit); |
| 587 | } catch (InterruptedException e) { |
| 588 | Thread.currentThread().interrupt(); |
| 589 | return defaultValue; |
| 590 | } catch (ExecutionException | TimeoutException e) { |
| 591 | return defaultValue; |
| 592 | } |
| 593 | } |
| 594 | |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 595 | /** |
| 596 | * Returns a future that is completed exceptionally. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 597 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 598 | * @param t exception |
| 599 | * @param <T> future value type |
| 600 | * @return future |
| 601 | */ |
| 602 | public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) { |
| 603 | CompletableFuture<T> future = new CompletableFuture<>(); |
| 604 | future.completeExceptionally(t); |
| 605 | return future; |
| 606 | } |
| 607 | |
| 608 | /** |
Sho SHIMIZU | 85803e2 | 2016-01-13 21:53:43 -0800 | [diff] [blame] | 609 | * Returns a new CompletableFuture completed with a list of computed values |
| 610 | * when all of the given CompletableFuture complete. |
| 611 | * |
| 612 | * @param futures the CompletableFutures |
| 613 | * @param <T> value type of CompletableFuture |
| 614 | * @return a new CompletableFuture that is completed when all of the given CompletableFutures complete |
| 615 | */ |
| 616 | public static <T> CompletableFuture<List<T>> allOf(List<CompletableFuture<T>> futures) { |
| 617 | return CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])) |
| 618 | .thenApply(v -> futures.stream() |
| 619 | .map(CompletableFuture::join) |
| 620 | .collect(Collectors.toList()) |
| 621 | ); |
| 622 | } |
| 623 | |
| 624 | /** |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 625 | * Returns the contents of {@code ByteBuffer} as byte array. |
| 626 | * <p> |
| 627 | * WARNING: There is a performance cost due to array copy |
| 628 | * when using this method. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 629 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 630 | * @param buffer byte buffer |
| 631 | * @return byte array containing the byte buffer contents |
| 632 | */ |
| 633 | public static byte[] byteBuffertoArray(ByteBuffer buffer) { |
| 634 | int length = buffer.remaining(); |
| 635 | if (buffer.hasArray()) { |
| 636 | int offset = buffer.arrayOffset() + buffer.position(); |
| 637 | return Arrays.copyOfRange(buffer.array(), offset, offset + length); |
| 638 | } |
| 639 | byte[] bytes = new byte[length]; |
| 640 | buffer.duplicate().get(bytes); |
| 641 | return bytes; |
| 642 | } |
| 643 | |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 644 | /** |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 645 | * Converts an iterable to a stream. |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 646 | * |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 647 | * @param it iterable to convert |
| 648 | * @param <T> type if item |
| 649 | * @return iterable as a stream |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 650 | */ |
| 651 | public static <T> Stream<T> stream(Iterable<T> it) { |
| 652 | return StreamSupport.stream(it.spliterator(), false); |
| 653 | } |
| 654 | |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 655 | /** |
| 656 | * Converts an optional to a stream. |
| 657 | * |
| 658 | * @param optional optional to convert |
| 659 | * @param <T> type of enclosed value |
| 660 | * @return optional as a stream |
| 661 | */ |
Sho SHIMIZU | 6ac2098 | 2016-05-04 09:50:54 -0700 | [diff] [blame] | 662 | public static <T> Stream<T> stream(Optional<? extends T> optional) { |
| 663 | return optional.map(x -> Stream.of(x)).orElse(Stream.empty()); |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 664 | } |
| 665 | |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 666 | // Auxiliary path visitor for recursive directory structure copying. |
| 667 | private static class DirectoryCopier extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 668 | private Path src; |
| 669 | private Path dst; |
| 670 | private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING; |
| 671 | |
| 672 | DirectoryCopier(String src, String dst) { |
| 673 | this.src = Paths.get(src); |
| 674 | this.dst = Paths.get(dst); |
| 675 | } |
| 676 | |
| 677 | @Override |
| 678 | public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { |
| 679 | Path targetPath = dst.resolve(src.relativize(dir)); |
| 680 | if (!Files.exists(targetPath)) { |
| 681 | Files.createDirectory(targetPath); |
| 682 | } |
| 683 | return FileVisitResult.CONTINUE; |
| 684 | } |
| 685 | |
| 686 | @Override |
| 687 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { |
| 688 | Files.copy(file, dst.resolve(src.relativize(file)), copyOption); |
| 689 | return FileVisitResult.CONTINUE; |
| 690 | } |
| 691 | } |
| 692 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 693 | } |