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