blob: 44295081677cc078c4ee99d7e96a8c4299915b2b [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska24c849c2014-10-27 09:53:05 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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 Vachuska24c849c2014-10-27 09:53:05 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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 Vachuska24c849c2014-10-27 09:53:05 -070015 */
tom5f38b3a2014-08-27 23:50:54 -070016package org.onlab.util;
17
Madan Jampani2bfa94c2015-04-11 05:03:49 -070018import static java.nio.file.Files.delete;
19import static java.nio.file.Files.walkFileTree;
20import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
21import static org.slf4j.LoggerFactory.getLogger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080022
tom53efab52014-10-07 17:43:48 -070023import java.io.BufferedReader;
24import java.io.File;
Ray Milkey705d9bc2014-11-18 08:19:00 -080025import java.io.FileInputStream;
tom53efab52014-10-07 17:43:48 -070026import java.io.IOException;
Ray Milkey705d9bc2014-11-18 08:19:00 -080027import java.io.InputStreamReader;
Madan Jampani27b69c62015-05-15 15:49:02 -070028import java.nio.ByteBuffer;
Ray Milkey705d9bc2014-11-18 08:19:00 -080029import java.nio.charset.StandardCharsets;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080030import java.nio.file.FileVisitResult;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080031import java.nio.file.Files;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080032import java.nio.file.Path;
33import java.nio.file.Paths;
34import java.nio.file.SimpleFileVisitor;
Thomas Vachuska90b453f2015-01-30 18:57:14 -080035import java.nio.file.StandardCopyOption;
Thomas Vachuska02aeb032015-01-06 22:36:30 -080036import java.nio.file.attribute.BasicFileAttributes;
tom53efab52014-10-07 17:43:48 -070037import java.util.ArrayList;
Madan Jampani27b69c62015-05-15 15:49:02 -070038import java.util.Arrays;
Brian O'Connore2eac102015-02-12 18:30:22 -080039import java.util.Collection;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070040import java.util.Dictionary;
tom53efab52014-10-07 17:43:48 -070041import java.util.List;
Thomas Vachuskaadba1522015-06-04 15:08:30 -070042import java.util.Random;
Madan Jampani27b69c62015-05-15 15:49:02 -070043import java.util.concurrent.CompletableFuture;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070044import java.util.concurrent.ExecutionException;
45import java.util.concurrent.Future;
tom5f38b3a2014-08-27 23:50:54 -070046import java.util.concurrent.ThreadFactory;
Madan Jampani2bfa94c2015-04-11 05:03:49 -070047import java.util.concurrent.TimeUnit;
48import java.util.concurrent.TimeoutException;
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -070049import java.util.stream.Stream;
50import java.util.stream.StreamSupport;
tom5f38b3a2014-08-27 23:50:54 -070051
Madan Jampani2bfa94c2015-04-11 05:03:49 -070052import org.slf4j.Logger;
53
54import com.google.common.base.Strings;
55import com.google.common.primitives.UnsignedLongs;
56import com.google.common.util.concurrent.ThreadFactoryBuilder;
Ray Milkey705d9bc2014-11-18 08:19:00 -080057
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080058/**
59 * Miscellaneous utility methods.
60 */
tom5f38b3a2014-08-27 23:50:54 -070061public abstract class Tools {
62
63 private Tools() {
64 }
65
Thomas Vachuska02aeb032015-01-06 22:36:30 -080066 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080067
Thomas Vachuskaadba1522015-06-04 15:08:30 -070068 private static Random random = new Random();
69
tom5f38b3a2014-08-27 23:50:54 -070070 /**
71 * Returns a thread factory that produces threads named according to the
72 * supplied name pattern.
73 *
74 * @param pattern name pattern
75 * @return thread factory
76 */
77 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080078 return new ThreadFactoryBuilder()
79 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080080 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
81 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080082 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080083
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080084 /**
85 * Returns a thread factory that produces threads named according to the
86 * supplied name pattern and from the specified thread-group. The thread
87 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080088 * {@code onos/intent}. The thread names will be produced by converting
89 * the thread group name into dash-delimited format and pre-pended to the
90 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080091 *
92 * @param groupName group name in slash-delimited format to indicate hierarchy
93 * @param pattern name pattern
94 * @return thread factory
95 */
96 public static ThreadFactory groupedThreads(String groupName, String pattern) {
97 return new ThreadFactoryBuilder()
98 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080099 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -0800100 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
101 .build();
tom5f38b3a2014-08-27 23:50:54 -0700102 }
103
tom782a7cf2014-09-11 23:58:38 -0700104 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800105 * Returns a thread factory that produces threads with MIN_PRIORITY.
106 *
107 * @param factory backing ThreadFactory
108 * @return thread factory
109 */
110 public static ThreadFactory minPriority(ThreadFactory factory) {
111 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800112 .setThreadFactory(factory)
113 .setPriority(Thread.MIN_PRIORITY)
114 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800115 }
116
117 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800118 * Returns true if the collection is null or is empty.
119 *
120 * @param collection collection to test
121 * @return true if null or empty; false otherwise
122 */
123 public static boolean isNullOrEmpty(Collection collection) {
124 return collection == null || collection.isEmpty();
125 }
126
127 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700128 * Returns the specified item if that item is not null; otherwise throws
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700129 * not found exception.
130 *
131 * @param item item to check
132 * @param message not found message
133 * @param <T> item type
134 * @return item if not null
135 * @throws org.onlab.util.ItemNotFoundException if item is null
136 */
137 public static <T> T nullIsNotFound(T item, String message) {
138 if (item == null) {
139 throw new ItemNotFoundException(message);
140 }
141 return item;
142 }
143
144 /**
Ray Milkeyd43fe452015-05-29 09:35:12 -0700145 * Returns the specified item if that item is not null; otherwise throws
146 * bad argument exception.
147 *
148 * @param item item to check
149 * @param message not found message
150 * @param <T> item type
151 * @return item if not null
152 * @throws IllegalArgumentException if item is null
153 */
154 public static <T> T nullIsIllegal(T item, String message) {
155 if (item == null) {
156 throw new IllegalArgumentException(message);
157 }
158 return item;
159 }
160
161 /**
tom782a7cf2014-09-11 23:58:38 -0700162 * Converts a string from hex to long.
163 *
164 * @param string hex number in string form; sans 0x
165 * @return long value
166 */
167 public static long fromHex(String string) {
168 return UnsignedLongs.parseUnsignedLong(string, 16);
169 }
170
171 /**
172 * Converts a long value to hex string; 16 wide and sans 0x.
173 *
174 * @param value long value
175 * @return hex string
176 */
177 public static String toHex(long value) {
178 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
179 }
180
181 /**
182 * Converts a long value to hex string; 16 wide and sans 0x.
183 *
184 * @param value long value
185 * @param width string width; zero padded
186 * @return hex string
187 */
188 public static String toHex(long value, int width) {
189 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
190 }
tomf110fff2014-09-26 00:38:18 -0700191
192 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700193 * Get property as a string value.
194 *
195 * @param properties properties to be looked up
196 * @param propertyName the name of the property to look up
197 * @return value when the propertyName is defined or return null
198 */
199 public static String get(Dictionary<?, ?> properties, String propertyName) {
200 Object v = properties.get(propertyName);
201 String s = (v instanceof String) ? (String) v :
202 v != null ? v.toString() : null;
203 return Strings.isNullOrEmpty(s) ? null : s.trim();
204 }
205
206 /**
tomf110fff2014-09-26 00:38:18 -0700207 * Suspends the current thread for a specified number of millis.
208 *
209 * @param ms number of millis
210 */
211 public static void delay(int ms) {
212 try {
213 Thread.sleep(ms);
214 } catch (InterruptedException e) {
215 throw new RuntimeException("Interrupted", e);
216 }
217 }
218
tom53efab52014-10-07 17:43:48 -0700219 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700220 * Suspends the current thread for a random number of millis between 0 and
221 * the indicated limit.
222 *
223 * @param ms max number of millis
224 */
225 public static void randomDelay(int ms) {
226 try {
227 Thread.sleep(random.nextInt(ms));
228 } catch (InterruptedException e) {
229 throw new RuntimeException("Interrupted", e);
230 }
231 }
232
233 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700234 * Suspends the current thread for a specified number of millis and nanos.
235 *
236 * @param ms number of millis
237 * @param nanos number of nanos
238 */
239 public static void delay(int ms, int nanos) {
240 try {
241 Thread.sleep(ms, nanos);
242 } catch (InterruptedException e) {
243 throw new RuntimeException("Interrupted", e);
244 }
245 }
246
247 /**
tom53efab52014-10-07 17:43:48 -0700248 * Slurps the contents of a file into a list of strings, one per line.
249 *
250 * @param path file path
251 * @return file contents
252 */
253 public static List<String> slurp(File path) {
Ray Milkey705d9bc2014-11-18 08:19:00 -0800254 try {
255 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800256 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
Ray Milkey705d9bc2014-11-18 08:19:00 -0800257
tom53efab52014-10-07 17:43:48 -0700258 List<String> lines = new ArrayList<>();
259 String line;
260 while ((line = br.readLine()) != null) {
261 lines.add(line);
262 }
263 return lines;
264
265 } catch (IOException e) {
266 return null;
267 }
268 }
269
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800270 /**
271 * Purges the specified directory path.&nbsp;Use with great caution since
272 * no attempt is made to check for symbolic links, which could result in
273 * deletion of unintended files.
274 *
275 * @param path directory to be removed
276 * @throws java.io.IOException if unable to remove contents
277 */
278 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800279 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700280 File dir = new File(path);
281 if (dir.exists() && dir.isDirectory()) {
282 walkFileTree(Paths.get(path), visitor);
283 if (visitor.exception != null) {
284 throw visitor.exception;
285 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800286 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800287 }
288
289 /**
290 * Purges the specified directory path.&nbsp;Use with great caution since
291 * no attempt is made to check for symbolic links, which could result in
292 * deletion of unintended files.
293 *
294 * @param dir directory to be removed
295 * @throws java.io.IOException if unable to remove contents
296 */
297 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800298 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700299 if (dir.exists() && dir.isDirectory()) {
300 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
301 if (visitor.exception != null) {
302 throw visitor.exception;
303 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800304 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800305 }
306
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800307 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800308 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800309
310 private IOException exception;
311
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800312 @Override
313 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
314 throws IOException {
315 if (attributes.isRegularFile()) {
316 delete(file);
317 }
318 return FileVisitResult.CONTINUE;
319 }
320
321 @Override
322 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
323 throws IOException {
324 delete(directory);
325 return FileVisitResult.CONTINUE;
326 }
327
328 @Override
329 public FileVisitResult visitFileFailed(Path file, IOException ioe)
330 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800331 this.exception = ioe;
332 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800333 }
334 }
335
Madan Jampani30a57f82015-03-02 12:19:41 -0800336 /**
337 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800338 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800339 * @param unixTime system time in millis
340 * @return human friendly time ago
341 */
342 public static String timeAgo(long unixTime) {
343 long deltaMillis = System.currentTimeMillis() - unixTime;
344 long secondsSince = (long) (deltaMillis / 1000.0);
345 long minsSince = (long) (deltaMillis / (1000.0 * 60));
346 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
347 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
348 if (daysSince > 0) {
349 return String.format("%dd ago", daysSince);
350 } else if (hoursSince > 0) {
351 return String.format("%dh ago", hoursSince);
352 } else if (minsSince > 0) {
353 return String.format("%dm ago", minsSince);
354 } else if (secondsSince > 0) {
355 return String.format("%ds ago", secondsSince);
356 } else {
357 return "just now";
358 }
359 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800360
361 /**
362 * Copies the specified directory path.&nbsp;Use with great caution since
363 * no attempt is made to check for symbolic links, which could result in
364 * copy of unintended files.
365 *
366 * @param src directory to be copied
367 * @param dst destination directory to be removed
368 * @throws java.io.IOException if unable to remove contents
369 */
370 public static void copyDirectory(String src, String dst) throws IOException {
371 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
372 }
373
374 /**
375 * Copies the specified directory path.&nbsp;Use with great caution since
376 * no attempt is made to check for symbolic links, which could result in
377 * copy of unintended files.
378 *
379 * @param src directory to be copied
380 * @param dst destination directory to be removed
381 * @throws java.io.IOException if unable to remove contents
382 */
383 public static void copyDirectory(File src, File dst) throws IOException {
384 walkFileTree(Paths.get(src.getAbsolutePath()),
385 new DirectoryCopier(src.getAbsolutePath(),
386 dst.getAbsolutePath()));
387 }
388
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700389 /**
390 * Returns the future value when complete or if future
391 * completes exceptionally returns the defaultValue.
392 * @param future future
393 * @param defaultValue default value
394 * @param <T> future value type
395 * @return future value when complete or if future
396 * completes exceptionally returns the defaultValue.
397 */
398 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
399 try {
400 return future.get();
401 } catch (InterruptedException e) {
402 Thread.currentThread().interrupt();
403 return defaultValue;
404 } catch (ExecutionException e) {
405 return defaultValue;
406 }
407 }
408
409 /**
410 * Returns the future value when complete or if future
411 * completes exceptionally returns the defaultValue.
412 * @param future future
413 * @param timeout time to wait for successful completion
414 * @param timeUnit time unit
415 * @param defaultValue default value
416 * @param <T> future value type
417 * @return future value when complete or if future
418 * completes exceptionally returns the defaultValue.
419 */
420 public static <T> T futureGetOrElse(Future<T> future,
421 long timeout,
422 TimeUnit timeUnit,
423 T defaultValue) {
424 try {
425 return future.get(timeout, timeUnit);
426 } catch (InterruptedException e) {
427 Thread.currentThread().interrupt();
428 return defaultValue;
429 } catch (ExecutionException | TimeoutException e) {
430 return defaultValue;
431 }
432 }
433
Madan Jampani27b69c62015-05-15 15:49:02 -0700434 /**
435 * Returns a future that is completed exceptionally.
436 * @param t exception
437 * @param <T> future value type
438 * @return future
439 */
440 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
441 CompletableFuture<T> future = new CompletableFuture<>();
442 future.completeExceptionally(t);
443 return future;
444 }
445
446 /**
447 * Returns the contents of {@code ByteBuffer} as byte array.
448 * <p>
449 * WARNING: There is a performance cost due to array copy
450 * when using this method.
451 * @param buffer byte buffer
452 * @return byte array containing the byte buffer contents
453 */
454 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
455 int length = buffer.remaining();
456 if (buffer.hasArray()) {
457 int offset = buffer.arrayOffset() + buffer.position();
458 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
459 }
460 byte[] bytes = new byte[length];
461 buffer.duplicate().get(bytes);
462 return bytes;
463 }
464
HIGUCHI Yutabfc8b7a2015-07-01 23:47:43 -0700465 /**
466 * Converts an Iterable to a Stream.
467 *
468 * @param it Iterable to convert
469 * @return Iterable as a Stream
470 */
471 public static <T> Stream<T> stream(Iterable<T> it) {
472 return StreamSupport.stream(it.spliterator(), false);
473 }
474
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800475 // Auxiliary path visitor for recursive directory structure copying.
476 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800477 private Path src;
478 private Path dst;
479 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
480
481 DirectoryCopier(String src, String dst) {
482 this.src = Paths.get(src);
483 this.dst = Paths.get(dst);
484 }
485
486 @Override
487 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
488 Path targetPath = dst.resolve(src.relativize(dir));
489 if (!Files.exists(targetPath)) {
490 Files.createDirectory(targetPath);
491 }
492 return FileVisitResult.CONTINUE;
493 }
494
495 @Override
496 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
497 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
498 return FileVisitResult.CONTINUE;
499 }
500 }
501
tom5f38b3a2014-08-27 23:50:54 -0700502}