blob: 73c8802f106f86d60a2d1c9861b5ca5dd57e1969 [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;
tom5f38b3a2014-08-27 23:50:54 -070049
Madan Jampani2bfa94c2015-04-11 05:03:49 -070050import org.slf4j.Logger;
51
52import com.google.common.base.Strings;
53import com.google.common.primitives.UnsignedLongs;
54import com.google.common.util.concurrent.ThreadFactoryBuilder;
Ray Milkey705d9bc2014-11-18 08:19:00 -080055
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080056/**
57 * Miscellaneous utility methods.
58 */
tom5f38b3a2014-08-27 23:50:54 -070059public abstract class Tools {
60
61 private Tools() {
62 }
63
Thomas Vachuska02aeb032015-01-06 22:36:30 -080064 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080065
Thomas Vachuskaadba1522015-06-04 15:08:30 -070066 private static Random random = new Random();
67
tom5f38b3a2014-08-27 23:50:54 -070068 /**
69 * Returns a thread factory that produces threads named according to the
70 * supplied name pattern.
71 *
72 * @param pattern name pattern
73 * @return thread factory
74 */
75 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080076 return new ThreadFactoryBuilder()
77 .setNameFormat(pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080078 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
79 .build();
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080080 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080081
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080082 /**
83 * Returns a thread factory that produces threads named according to the
84 * supplied name pattern and from the specified thread-group. The thread
85 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080086 * {@code onos/intent}. The thread names will be produced by converting
87 * the thread group name into dash-delimited format and pre-pended to the
88 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080089 *
90 * @param groupName group name in slash-delimited format to indicate hierarchy
91 * @param pattern name pattern
92 * @return thread factory
93 */
94 public static ThreadFactory groupedThreads(String groupName, String pattern) {
95 return new ThreadFactoryBuilder()
96 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080097 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Thomas Vachuska480adad2015-03-06 10:27:09 -080098 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on " + t.getName(), e))
99 .build();
tom5f38b3a2014-08-27 23:50:54 -0700100 }
101
tom782a7cf2014-09-11 23:58:38 -0700102 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800103 * Returns a thread factory that produces threads with MIN_PRIORITY.
104 *
105 * @param factory backing ThreadFactory
106 * @return thread factory
107 */
108 public static ThreadFactory minPriority(ThreadFactory factory) {
109 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800110 .setThreadFactory(factory)
111 .setPriority(Thread.MIN_PRIORITY)
112 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800113 }
114
115 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800116 * Returns true if the collection is null or is empty.
117 *
118 * @param collection collection to test
119 * @return true if null or empty; false otherwise
120 */
121 public static boolean isNullOrEmpty(Collection collection) {
122 return collection == null || collection.isEmpty();
123 }
124
125 /**
Thomas Vachuskaca88bb72015-04-08 19:38:02 -0700126 * Returns the specified item if that items is null; otherwise throws
127 * not found exception.
128 *
129 * @param item item to check
130 * @param message not found message
131 * @param <T> item type
132 * @return item if not null
133 * @throws org.onlab.util.ItemNotFoundException if item is null
134 */
135 public static <T> T nullIsNotFound(T item, String message) {
136 if (item == null) {
137 throw new ItemNotFoundException(message);
138 }
139 return item;
140 }
141
142 /**
tom782a7cf2014-09-11 23:58:38 -0700143 * Converts a string from hex to long.
144 *
145 * @param string hex number in string form; sans 0x
146 * @return long value
147 */
148 public static long fromHex(String string) {
149 return UnsignedLongs.parseUnsignedLong(string, 16);
150 }
151
152 /**
153 * Converts a long value to hex string; 16 wide and sans 0x.
154 *
155 * @param value long value
156 * @return hex string
157 */
158 public static String toHex(long value) {
159 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
160 }
161
162 /**
163 * Converts a long value to hex string; 16 wide and sans 0x.
164 *
165 * @param value long value
166 * @param width string width; zero padded
167 * @return hex string
168 */
169 public static String toHex(long value, int width) {
170 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
171 }
tomf110fff2014-09-26 00:38:18 -0700172
173 /**
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700174 * Get property as a string value.
175 *
176 * @param properties properties to be looked up
177 * @param propertyName the name of the property to look up
178 * @return value when the propertyName is defined or return null
179 */
180 public static String get(Dictionary<?, ?> properties, String propertyName) {
181 Object v = properties.get(propertyName);
182 String s = (v instanceof String) ? (String) v :
183 v != null ? v.toString() : null;
184 return Strings.isNullOrEmpty(s) ? null : s.trim();
185 }
186
187 /**
tomf110fff2014-09-26 00:38:18 -0700188 * Suspends the current thread for a specified number of millis.
189 *
190 * @param ms number of millis
191 */
192 public static void delay(int ms) {
193 try {
194 Thread.sleep(ms);
195 } catch (InterruptedException e) {
196 throw new RuntimeException("Interrupted", e);
197 }
198 }
199
tom53efab52014-10-07 17:43:48 -0700200 /**
Thomas Vachuskaadba1522015-06-04 15:08:30 -0700201 * Suspends the current thread for a random number of millis between 0 and
202 * the indicated limit.
203 *
204 * @param ms max number of millis
205 */
206 public static void randomDelay(int ms) {
207 try {
208 Thread.sleep(random.nextInt(ms));
209 } catch (InterruptedException e) {
210 throw new RuntimeException("Interrupted", e);
211 }
212 }
213
214 /**
Thomas Vachuskac40d4632015-04-09 16:55:03 -0700215 * Suspends the current thread for a specified number of millis and nanos.
216 *
217 * @param ms number of millis
218 * @param nanos number of nanos
219 */
220 public static void delay(int ms, int nanos) {
221 try {
222 Thread.sleep(ms, nanos);
223 } catch (InterruptedException e) {
224 throw new RuntimeException("Interrupted", e);
225 }
226 }
227
228 /**
tom53efab52014-10-07 17:43:48 -0700229 * Slurps the contents of a file into a list of strings, one per line.
230 *
231 * @param path file path
232 * @return file contents
233 */
234 public static List<String> slurp(File path) {
Ray Milkey705d9bc2014-11-18 08:19:00 -0800235 try {
236 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800237 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
Ray Milkey705d9bc2014-11-18 08:19:00 -0800238
tom53efab52014-10-07 17:43:48 -0700239 List<String> lines = new ArrayList<>();
240 String line;
241 while ((line = br.readLine()) != null) {
242 lines.add(line);
243 }
244 return lines;
245
246 } catch (IOException e) {
247 return null;
248 }
249 }
250
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800251 /**
252 * Purges the specified directory path.&nbsp;Use with great caution since
253 * no attempt is made to check for symbolic links, which could result in
254 * deletion of unintended files.
255 *
256 * @param path directory to be removed
257 * @throws java.io.IOException if unable to remove contents
258 */
259 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800260 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700261 File dir = new File(path);
262 if (dir.exists() && dir.isDirectory()) {
263 walkFileTree(Paths.get(path), visitor);
264 if (visitor.exception != null) {
265 throw visitor.exception;
266 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800267 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800268 }
269
270 /**
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 dir directory to be removed
276 * @throws java.io.IOException if unable to remove contents
277 */
278 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800279 DirectoryDeleter visitor = new DirectoryDeleter();
Thomas Vachuskaf9c84362015-04-15 11:20:45 -0700280 if (dir.exists() && dir.isDirectory()) {
281 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
282 if (visitor.exception != null) {
283 throw visitor.exception;
284 }
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800285 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800286 }
287
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800288 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800289 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800290
291 private IOException exception;
292
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800293 @Override
294 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
295 throws IOException {
296 if (attributes.isRegularFile()) {
297 delete(file);
298 }
299 return FileVisitResult.CONTINUE;
300 }
301
302 @Override
303 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
304 throws IOException {
305 delete(directory);
306 return FileVisitResult.CONTINUE;
307 }
308
309 @Override
310 public FileVisitResult visitFileFailed(Path file, IOException ioe)
311 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800312 this.exception = ioe;
313 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800314 }
315 }
316
Madan Jampani30a57f82015-03-02 12:19:41 -0800317 /**
318 * Returns a human friendly time ago string for a specified system time.
Thomas Vachuska480adad2015-03-06 10:27:09 -0800319 *
Madan Jampani30a57f82015-03-02 12:19:41 -0800320 * @param unixTime system time in millis
321 * @return human friendly time ago
322 */
323 public static String timeAgo(long unixTime) {
324 long deltaMillis = System.currentTimeMillis() - unixTime;
325 long secondsSince = (long) (deltaMillis / 1000.0);
326 long minsSince = (long) (deltaMillis / (1000.0 * 60));
327 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
328 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
329 if (daysSince > 0) {
330 return String.format("%dd ago", daysSince);
331 } else if (hoursSince > 0) {
332 return String.format("%dh ago", hoursSince);
333 } else if (minsSince > 0) {
334 return String.format("%dm ago", minsSince);
335 } else if (secondsSince > 0) {
336 return String.format("%ds ago", secondsSince);
337 } else {
338 return "just now";
339 }
340 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800341
342 /**
343 * Copies the specified directory path.&nbsp;Use with great caution since
344 * no attempt is made to check for symbolic links, which could result in
345 * copy of unintended files.
346 *
347 * @param src directory to be copied
348 * @param dst destination directory to be removed
349 * @throws java.io.IOException if unable to remove contents
350 */
351 public static void copyDirectory(String src, String dst) throws IOException {
352 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
353 }
354
355 /**
356 * Copies the specified directory path.&nbsp;Use with great caution since
357 * no attempt is made to check for symbolic links, which could result in
358 * copy of unintended files.
359 *
360 * @param src directory to be copied
361 * @param dst destination directory to be removed
362 * @throws java.io.IOException if unable to remove contents
363 */
364 public static void copyDirectory(File src, File dst) throws IOException {
365 walkFileTree(Paths.get(src.getAbsolutePath()),
366 new DirectoryCopier(src.getAbsolutePath(),
367 dst.getAbsolutePath()));
368 }
369
Madan Jampani2bfa94c2015-04-11 05:03:49 -0700370 /**
371 * Returns the future value when complete or if future
372 * completes exceptionally returns the defaultValue.
373 * @param future future
374 * @param defaultValue default value
375 * @param <T> future value type
376 * @return future value when complete or if future
377 * completes exceptionally returns the defaultValue.
378 */
379 public static <T> T futureGetOrElse(Future<T> future, T defaultValue) {
380 try {
381 return future.get();
382 } catch (InterruptedException e) {
383 Thread.currentThread().interrupt();
384 return defaultValue;
385 } catch (ExecutionException e) {
386 return defaultValue;
387 }
388 }
389
390 /**
391 * Returns the future value when complete or if future
392 * completes exceptionally returns the defaultValue.
393 * @param future future
394 * @param timeout time to wait for successful completion
395 * @param timeUnit time unit
396 * @param defaultValue default value
397 * @param <T> future value type
398 * @return future value when complete or if future
399 * completes exceptionally returns the defaultValue.
400 */
401 public static <T> T futureGetOrElse(Future<T> future,
402 long timeout,
403 TimeUnit timeUnit,
404 T defaultValue) {
405 try {
406 return future.get(timeout, timeUnit);
407 } catch (InterruptedException e) {
408 Thread.currentThread().interrupt();
409 return defaultValue;
410 } catch (ExecutionException | TimeoutException e) {
411 return defaultValue;
412 }
413 }
414
Madan Jampani27b69c62015-05-15 15:49:02 -0700415 /**
416 * Returns a future that is completed exceptionally.
417 * @param t exception
418 * @param <T> future value type
419 * @return future
420 */
421 public static <T> CompletableFuture<T> exceptionalFuture(Throwable t) {
422 CompletableFuture<T> future = new CompletableFuture<>();
423 future.completeExceptionally(t);
424 return future;
425 }
426
427 /**
428 * Returns the contents of {@code ByteBuffer} as byte array.
429 * <p>
430 * WARNING: There is a performance cost due to array copy
431 * when using this method.
432 * @param buffer byte buffer
433 * @return byte array containing the byte buffer contents
434 */
435 public static byte[] byteBuffertoArray(ByteBuffer buffer) {
436 int length = buffer.remaining();
437 if (buffer.hasArray()) {
438 int offset = buffer.arrayOffset() + buffer.position();
439 return Arrays.copyOfRange(buffer.array(), offset, offset + length);
440 }
441 byte[] bytes = new byte[length];
442 buffer.duplicate().get(bytes);
443 return bytes;
444 }
445
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800446 // Auxiliary path visitor for recursive directory structure copying.
447 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800448 private Path src;
449 private Path dst;
450 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
451
452 DirectoryCopier(String src, String dst) {
453 this.src = Paths.get(src);
454 this.dst = Paths.get(dst);
455 }
456
457 @Override
458 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
459 Path targetPath = dst.resolve(src.relativize(dir));
460 if (!Files.exists(targetPath)) {
461 Files.createDirectory(targetPath);
462 }
463 return FileVisitResult.CONTINUE;
464 }
465
466 @Override
467 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
468 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
469 return FileVisitResult.CONTINUE;
470 }
471 }
472
tom5f38b3a2014-08-27 23:50:54 -0700473}