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