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