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 | |
Madan Jampani | 307a21e | 2016-09-01 15:49:47 -0700 | [diff] [blame] | 18 | import static java.nio.file.Files.delete; |
| 19 | import static java.nio.file.Files.walkFileTree; |
| 20 | import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory; |
| 21 | import static org.slf4j.LoggerFactory.getLogger; |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 22 | |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 23 | import java.io.File; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 24 | import java.io.IOException; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 25 | import java.nio.ByteBuffer; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 26 | import java.nio.file.FileVisitResult; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 27 | import java.nio.file.Files; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 28 | import java.nio.file.Path; |
| 29 | import java.nio.file.Paths; |
| 30 | import java.nio.file.SimpleFileVisitor; |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 31 | import java.nio.file.StandardCopyOption; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 32 | import java.nio.file.attribute.BasicFileAttributes; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 33 | import java.util.Arrays; |
Brian O'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 34 | import java.util.Collection; |
Thomas Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 35 | import java.util.Dictionary; |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 36 | import java.util.List; |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 37 | import java.util.Optional; |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 38 | import java.util.Random; |
Ray Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 39 | import java.util.Set; |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 40 | import java.util.concurrent.CompletableFuture; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 41 | import java.util.concurrent.ExecutionException; |
| 42 | import java.util.concurrent.Future; |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 43 | import java.util.concurrent.ThreadFactory; |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 44 | import java.util.concurrent.TimeUnit; |
| 45 | import java.util.concurrent.TimeoutException; |
Madan Jampani | 307a21e | 2016-09-01 15:49:47 -0700 | [diff] [blame] | 46 | import java.util.function.BinaryOperator; |
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 | |
Madan Jampani | 307a21e | 2016-09-01 15:49:47 -0700 | [diff] [blame] | 53 | import org.slf4j.Logger; |
| 54 | |
| 55 | import com.google.common.base.Charsets; |
| 56 | import com.google.common.base.Strings; |
| 57 | import com.google.common.collect.Lists; |
| 58 | import com.google.common.primitives.UnsignedLongs; |
| 59 | import com.google.common.util.concurrent.ThreadFactoryBuilder; |
Ray Milkey | 705d9bc | 2014-11-18 08:19:00 -0800 | [diff] [blame] | 60 | |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 61 | /** |
| 62 | * Miscellaneous utility methods. |
| 63 | */ |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 64 | public abstract class Tools { |
| 65 | |
| 66 | private Tools() { |
| 67 | } |
| 68 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 69 | private static final Logger log = getLogger(Tools.class); |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 70 | |
Thomas Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 71 | private static Random random = new Random(); |
| 72 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 73 | /** |
| 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 HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 81 | return new ThreadFactoryBuilder() |
| 82 | .setNameFormat(pattern) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 83 | .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e)) |
| 84 | .build(); |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 85 | } |
Yuta HIGUCHI | 683e978 | 2014-11-25 17:26:36 -0800 | [diff] [blame] | 86 | |
Thomas Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 87 | /** |
| 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 Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 91 | * {@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 Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 94 | * |
| 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 Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 100 | 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 Vachuska | 9c17a6d | 2015-02-17 23:36:43 -0800 | [diff] [blame] | 121 | return new ThreadFactoryBuilder() |
| 122 | .setThreadFactory(groupedThreadFactory(groupName)) |
Thomas Vachuska | c13b90a | 2015-02-18 18:19:55 -0800 | [diff] [blame] | 123 | .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern) |
Jian Li | 03e9fb0 | 2016-03-01 17:13:54 -0800 | [diff] [blame] | 124 | .setUncaughtExceptionHandler((t, e) -> logger.error("Uncaught exception on " + t.getName(), e)) |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 125 | .build(); |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 126 | } |
| 127 | |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 128 | /** |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 129 | * 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 Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 136 | .setThreadFactory(factory) |
| 137 | .setPriority(Thread.MIN_PRIORITY) |
| 138 | .build(); |
Yuta HIGUCHI | 0658627 | 2014-11-25 14:27:03 -0800 | [diff] [blame] | 139 | } |
| 140 | |
| 141 | /** |
Yuta HIGUCHI | a2a11cd | 2016-12-19 14:19:11 -0800 | [diff] [blame] | 142 | * 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'Connor | e2eac10 | 2015-02-12 18:30:22 -0800 | [diff] [blame] | 155 | * 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 Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 165 | * Returns the specified item if that item is not null; otherwise throws |
Thomas Vachuska | ca88bb7 | 2015-04-08 19:38:02 -0700 | [diff] [blame] | 166 | * 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 Milkey | 36992c8 | 2015-11-17 13:31:15 -0800 | [diff] [blame] | 182 | * 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 Milkey | d43fe45 | 2015-05-29 09:35:12 -0700 | [diff] [blame] | 199 | * 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 | /** |
tom | 782a7cf | 2014-09-11 23:58:38 -0700 | [diff] [blame] | 216 | * 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 | } |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 245 | |
| 246 | /** |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 247 | * Returns the UTF-8 encoded byte[] representation of a String. |
Jian Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 248 | * @param input input string |
| 249 | * @return UTF-8 encoded byte array |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 250 | */ |
| 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 Li | dfba739 | 2016-01-22 16:46:58 -0800 | [diff] [blame] | 257 | * @param input input byte array |
| 258 | * @return UTF-8 encoded string |
Madan Jampani | f2f086c | 2016-01-13 16:15:39 -0800 | [diff] [blame] | 259 | */ |
| 260 | public static String toStringUtf8(byte[] input) { |
| 261 | return new String(input, Charsets.UTF_8); |
| 262 | } |
| 263 | |
| 264 | /** |
Madan Jampani | 9eb55d1 | 2015-08-14 07:47:56 -0700 | [diff] [blame] | 265 | * 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 Vachuska | 6519e6f | 2015-03-11 02:29:31 -0700 | [diff] [blame] | 275 | * 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 Li | d9b5f55 | 2016-03-11 18:15:31 -0800 | [diff] [blame] | 289 | * 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 | /** |
tom | f110fff | 2014-09-26 00:38:18 -0700 | [diff] [blame] | 367 | * 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 | |
tom | 53efab5 | 2014-10-07 17:43:48 -0700 | [diff] [blame] | 379 | /** |
sdn | 94b0015 | 2016-08-30 02:12:32 -0700 | [diff] [blame] | 380 | * 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 Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 400 | * 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 Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 407 | * @param <U> type of function input |
| 408 | * @param <V> type of function output |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 409 | */ |
| 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 Vachuska | 87ae1d9 | 2015-08-19 17:39:11 -0700 | [diff] [blame] | 425 | * @param <V> type of supplied result |
Madan Jampani | a29c677 | 2015-08-17 13:17:07 -0700 | [diff] [blame] | 426 | */ |
| 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 Vachuska | adba152 | 2015-06-04 15:08:30 -0700 | [diff] [blame] | 438 | * 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 Vachuska | c40d463 | 2015-04-09 16:55:03 -0700 | [diff] [blame] | 452 | * 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 Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 466 | * Purges the specified directory path. 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 474 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 475 | 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 481 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 482 | } |
| 483 | |
| 484 | /** |
| 485 | * Purges the specified directory path. 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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 493 | DirectoryDeleter visitor = new DirectoryDeleter(); |
Thomas Vachuska | f9c8436 | 2015-04-15 11:20:45 -0700 | [diff] [blame] | 494 | if (dir.exists() && dir.isDirectory()) { |
| 495 | walkFileTree(Paths.get(dir.getAbsolutePath()), visitor); |
| 496 | if (visitor.exception != null) { |
| 497 | throw visitor.exception; |
| 498 | } |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 499 | } |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 500 | } |
| 501 | |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 502 | // Auxiliary path visitor for recursive directory structure removal. |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 503 | private static class DirectoryDeleter extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 504 | |
| 505 | private IOException exception; |
| 506 | |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 507 | @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 Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 526 | this.exception = ioe; |
| 527 | return FileVisitResult.TERMINATE; |
Thomas Vachuska | 02aeb03 | 2015-01-06 22:36:30 -0800 | [diff] [blame] | 528 | } |
| 529 | } |
| 530 | |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 531 | /** |
| 532 | * Returns a human friendly time ago string for a specified system time. |
Thomas Vachuska | 480adad | 2015-03-06 10:27:09 -0800 | [diff] [blame] | 533 | * |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 534 | * @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) { |
Saurav Das | d5ec9e9 | 2017-01-17 10:40:18 -0800 | [diff] [blame] | 544 | return String.format("%dd%dh ago", daysSince, hoursSince - daysSince * 24); |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 545 | } else if (hoursSince > 0) { |
Saurav Das | d5ec9e9 | 2017-01-17 10:40:18 -0800 | [diff] [blame] | 546 | return String.format("%dh%dm ago", hoursSince, minsSince - hoursSince * 60); |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 547 | } else if (minsSince > 0) { |
Saurav Das | d5ec9e9 | 2017-01-17 10:40:18 -0800 | [diff] [blame] | 548 | return String.format("%dm%ds ago", minsSince, secondsSince - minsSince * 60); |
Madan Jampani | 30a57f8 | 2015-03-02 12:19:41 -0800 | [diff] [blame] | 549 | } else if (secondsSince > 0) { |
| 550 | return String.format("%ds ago", secondsSince); |
| 551 | } else { |
| 552 | return "just now"; |
| 553 | } |
| 554 | } |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 555 | |
| 556 | /** |
| 557 | * Copies the specified directory path. 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. 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 Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 584 | /** |
| 585 | * Returns the future value when complete or if future |
| 586 | * completes exceptionally returns the defaultValue. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 587 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 588 | * @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 Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 608 | * |
Madan Jampani | 2bfa94c | 2015-04-11 05:03:49 -0700 | [diff] [blame] | 609 | * @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 Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 631 | /** |
| 632 | * Returns a future that is completed exceptionally. |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 633 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 634 | * @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 SHIMIZU | 85803e2 | 2016-01-13 21:53:43 -0800 | [diff] [blame] | 645 | * 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 Jampani | 307a21e | 2016-09-01 15:49:47 -0700 | [diff] [blame] | 661 | * 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 Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 708 | * 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 Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 712 | * |
Madan Jampani | 27b69c6 | 2015-05-15 15:49:02 -0700 | [diff] [blame] | 713 | * @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 Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 727 | /** |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 728 | * Converts an iterable to a stream. |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 729 | * |
Thomas Vachuska | d894b5d | 2015-07-30 11:59:07 -0700 | [diff] [blame] | 730 | * @param it iterable to convert |
| 731 | * @param <T> type if item |
| 732 | * @return iterable as a stream |
HIGUCHI Yuta | bfc8b7a | 2015-07-01 23:47:43 -0700 | [diff] [blame] | 733 | */ |
| 734 | public static <T> Stream<T> stream(Iterable<T> it) { |
| 735 | return StreamSupport.stream(it.spliterator(), false); |
| 736 | } |
| 737 | |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 738 | /** |
| 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 SHIMIZU | 6ac2098 | 2016-05-04 09:50:54 -0700 | [diff] [blame] | 745 | public static <T> Stream<T> stream(Optional<? extends T> optional) { |
HIGUCHI Yuta | 0bc256f | 2016-05-06 15:28:26 -0700 | [diff] [blame] | 746 | return optional.map(x -> Stream.<T>of(x)).orElse(Stream.empty()); |
Sho SHIMIZU | b5638b8 | 2016-02-11 14:55:05 -0800 | [diff] [blame] | 747 | } |
| 748 | |
Thomas Vachuska | 62ad95f | 2015-02-18 12:11:36 -0800 | [diff] [blame] | 749 | // Auxiliary path visitor for recursive directory structure copying. |
| 750 | private static class DirectoryCopier extends SimpleFileVisitor<Path> { |
Thomas Vachuska | 90b453f | 2015-01-30 18:57:14 -0800 | [diff] [blame] | 751 | 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 | |
tom | 5f38b3a | 2014-08-27 23:50:54 -0700 | [diff] [blame] | 776 | } |