blob: 5643098480e2e83565581bfdd19812c0ce9f1f64 [file] [log] [blame]
tom5f38b3a2014-08-27 23:50:54 -07001package org.onlab.util;
2
tom782a7cf2014-09-11 23:58:38 -07003import com.google.common.base.Strings;
4import com.google.common.primitives.UnsignedLongs;
tom5f38b3a2014-08-27 23:50:54 -07005import com.google.common.util.concurrent.ThreadFactoryBuilder;
6
tom53efab52014-10-07 17:43:48 -07007import java.io.BufferedReader;
8import java.io.File;
9import java.io.FileReader;
10import java.io.IOException;
11import java.util.ArrayList;
12import java.util.List;
tom5f38b3a2014-08-27 23:50:54 -070013import java.util.concurrent.ThreadFactory;
14
15public abstract class Tools {
16
17 private Tools() {
18 }
19
20 /**
21 * Returns a thread factory that produces threads named according to the
22 * supplied name pattern.
23 *
24 * @param pattern name pattern
25 * @return thread factory
26 */
27 public static ThreadFactory namedThreads(String pattern) {
28 return new ThreadFactoryBuilder().setNameFormat(pattern).build();
29 }
30
tom782a7cf2014-09-11 23:58:38 -070031 /**
32 * Converts a string from hex to long.
33 *
34 * @param string hex number in string form; sans 0x
35 * @return long value
36 */
37 public static long fromHex(String string) {
38 return UnsignedLongs.parseUnsignedLong(string, 16);
39 }
40
41 /**
42 * Converts a long value to hex string; 16 wide and sans 0x.
43 *
44 * @param value long value
45 * @return hex string
46 */
47 public static String toHex(long value) {
48 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
49 }
50
51 /**
52 * Converts a long value to hex string; 16 wide and sans 0x.
53 *
54 * @param value long value
55 * @param width string width; zero padded
56 * @return hex string
57 */
58 public static String toHex(long value, int width) {
59 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
60 }
tomf110fff2014-09-26 00:38:18 -070061
62 /**
63 * Suspends the current thread for a specified number of millis.
64 *
65 * @param ms number of millis
66 */
67 public static void delay(int ms) {
68 try {
69 Thread.sleep(ms);
70 } catch (InterruptedException e) {
71 throw new RuntimeException("Interrupted", e);
72 }
73 }
74
tom53efab52014-10-07 17:43:48 -070075 /**
76 * Slurps the contents of a file into a list of strings, one per line.
77 *
78 * @param path file path
79 * @return file contents
80 */
81 public static List<String> slurp(File path) {
82 try (BufferedReader br = new BufferedReader(new FileReader(path))) {
83 List<String> lines = new ArrayList<>();
84 String line;
85 while ((line = br.readLine()) != null) {
86 lines.add(line);
87 }
88 return lines;
89
90 } catch (IOException e) {
91 return null;
92 }
93 }
94
tom5f38b3a2014-08-27 23:50:54 -070095}