blob: 533563b8d46d4966a8032603aaa2d6a5e8d35aa9 [file] [log] [blame]
Thomas Vachuska24c849c2014-10-27 09:53:05 -07001/*
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07002 * Copyright 2014 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
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080018import com.google.common.base.Strings;
19import com.google.common.primitives.UnsignedLongs;
20import com.google.common.util.concurrent.ThreadFactoryBuilder;
Madan Jampani30a57f82015-03-02 12:19:41 -080021
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080022import org.slf4j.Logger;
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080023
tom53efab52014-10-07 17:43:48 -070024import java.io.BufferedReader;
25import java.io.File;
Ray Milkey705d9bc2014-11-18 08:19:00 -080026import java.io.FileInputStream;
tom53efab52014-10-07 17:43:48 -070027import java.io.IOException;
Ray Milkey705d9bc2014-11-18 08:19:00 -080028import java.io.InputStreamReader;
29import 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;
Brian O'Connore2eac102015-02-12 18:30:22 -080038import java.util.Collection;
tom53efab52014-10-07 17:43:48 -070039import java.util.List;
tom5f38b3a2014-08-27 23:50:54 -070040import java.util.concurrent.ThreadFactory;
41
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080042import static java.nio.file.Files.delete;
43import static java.nio.file.Files.walkFileTree;
44import static org.onlab.util.GroupedThreadFactory.groupedThreadFactory;
45import static org.slf4j.LoggerFactory.getLogger;
Ray Milkey705d9bc2014-11-18 08:19:00 -080046
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080047/**
48 * Miscellaneous utility methods.
49 */
tom5f38b3a2014-08-27 23:50:54 -070050public abstract class Tools {
51
52 private Tools() {
53 }
54
Thomas Vachuska02aeb032015-01-06 22:36:30 -080055 private static final Logger log = getLogger(Tools.class);
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080056
tom5f38b3a2014-08-27 23:50:54 -070057 /**
58 * Returns a thread factory that produces threads named according to the
59 * supplied name pattern.
60 *
61 * @param pattern name pattern
62 * @return thread factory
63 */
64 public static ThreadFactory namedThreads(String pattern) {
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080065 return new ThreadFactoryBuilder()
66 .setNameFormat(pattern)
Thomas Vachuska02aeb032015-01-06 22:36:30 -080067 // FIXME remove UncaughtExceptionHandler before release
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080068 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on {}", t.getName(), e)).build();
69 }
Yuta HIGUCHI683e9782014-11-25 17:26:36 -080070
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080071 /**
72 * Returns a thread factory that produces threads named according to the
73 * supplied name pattern and from the specified thread-group. The thread
74 * group name is expected to be specified in slash-delimited format, e.g.
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080075 * {@code onos/intent}. The thread names will be produced by converting
76 * the thread group name into dash-delimited format and pre-pended to the
77 * specified pattern.
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080078 *
79 * @param groupName group name in slash-delimited format to indicate hierarchy
80 * @param pattern name pattern
81 * @return thread factory
82 */
83 public static ThreadFactory groupedThreads(String groupName, String pattern) {
84 return new ThreadFactoryBuilder()
85 .setThreadFactory(groupedThreadFactory(groupName))
Thomas Vachuskac13b90a2015-02-18 18:19:55 -080086 .setNameFormat(groupName.replace(GroupedThreadFactory.DELIMITER, "-") + "-" + pattern)
Thomas Vachuska9c17a6d2015-02-17 23:36:43 -080087 // FIXME remove UncaughtExceptionHandler before release
88 .setUncaughtExceptionHandler((t, e) -> log.error("Uncaught exception on {}", t.getName(), e)).build();
tom5f38b3a2014-08-27 23:50:54 -070089 }
90
tom782a7cf2014-09-11 23:58:38 -070091 /**
Yuta HIGUCHI06586272014-11-25 14:27:03 -080092 * Returns a thread factory that produces threads with MIN_PRIORITY.
93 *
94 * @param factory backing ThreadFactory
95 * @return thread factory
96 */
97 public static ThreadFactory minPriority(ThreadFactory factory) {
98 return new ThreadFactoryBuilder()
Thomas Vachuska02aeb032015-01-06 22:36:30 -080099 .setThreadFactory(factory)
100 .setPriority(Thread.MIN_PRIORITY)
101 .build();
Yuta HIGUCHI06586272014-11-25 14:27:03 -0800102 }
103
104 /**
Brian O'Connore2eac102015-02-12 18:30:22 -0800105 * Returns true if the collection is null or is empty.
106 *
107 * @param collection collection to test
108 * @return true if null or empty; false otherwise
109 */
110 public static boolean isNullOrEmpty(Collection collection) {
111 return collection == null || collection.isEmpty();
112 }
113
114 /**
tom782a7cf2014-09-11 23:58:38 -0700115 * Converts a string from hex to long.
116 *
117 * @param string hex number in string form; sans 0x
118 * @return long value
119 */
120 public static long fromHex(String string) {
121 return UnsignedLongs.parseUnsignedLong(string, 16);
122 }
123
124 /**
125 * Converts a long value to hex string; 16 wide and sans 0x.
126 *
127 * @param value long value
128 * @return hex string
129 */
130 public static String toHex(long value) {
131 return Strings.padStart(UnsignedLongs.toString(value, 16), 16, '0');
132 }
133
134 /**
135 * Converts a long value to hex string; 16 wide and sans 0x.
136 *
137 * @param value long value
138 * @param width string width; zero padded
139 * @return hex string
140 */
141 public static String toHex(long value, int width) {
142 return Strings.padStart(UnsignedLongs.toString(value, 16), width, '0');
143 }
tomf110fff2014-09-26 00:38:18 -0700144
145 /**
146 * Suspends the current thread for a specified number of millis.
147 *
148 * @param ms number of millis
149 */
150 public static void delay(int ms) {
151 try {
152 Thread.sleep(ms);
153 } catch (InterruptedException e) {
154 throw new RuntimeException("Interrupted", e);
155 }
156 }
157
tom53efab52014-10-07 17:43:48 -0700158 /**
159 * Slurps the contents of a file into a list of strings, one per line.
160 *
161 * @param path file path
162 * @return file contents
163 */
164 public static List<String> slurp(File path) {
Ray Milkey705d9bc2014-11-18 08:19:00 -0800165 try {
166 BufferedReader br = new BufferedReader(
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800167 new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8));
Ray Milkey705d9bc2014-11-18 08:19:00 -0800168
tom53efab52014-10-07 17:43:48 -0700169 List<String> lines = new ArrayList<>();
170 String line;
171 while ((line = br.readLine()) != null) {
172 lines.add(line);
173 }
174 return lines;
175
176 } catch (IOException e) {
177 return null;
178 }
179 }
180
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800181
182 /**
183 * Purges the specified directory path.&nbsp;Use with great caution since
184 * no attempt is made to check for symbolic links, which could result in
185 * deletion of unintended files.
186 *
187 * @param path directory to be removed
188 * @throws java.io.IOException if unable to remove contents
189 */
190 public static void removeDirectory(String path) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800191 DirectoryDeleter visitor = new DirectoryDeleter();
192 walkFileTree(Paths.get(path), visitor);
193 if (visitor.exception != null) {
194 throw visitor.exception;
195 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800196 }
197
198 /**
199 * Purges the specified directory path.&nbsp;Use with great caution since
200 * no attempt is made to check for symbolic links, which could result in
201 * deletion of unintended files.
202 *
203 * @param dir directory to be removed
204 * @throws java.io.IOException if unable to remove contents
205 */
206 public static void removeDirectory(File dir) throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800207 DirectoryDeleter visitor = new DirectoryDeleter();
208 walkFileTree(Paths.get(dir.getAbsolutePath()), visitor);
209 if (visitor.exception != null) {
210 throw visitor.exception;
211 }
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800212 }
213
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800214 // Auxiliary path visitor for recursive directory structure removal.
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800215 private static class DirectoryDeleter extends SimpleFileVisitor<Path> {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800216
217 private IOException exception;
218
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800219 @Override
220 public FileVisitResult visitFile(Path file, BasicFileAttributes attributes)
221 throws IOException {
222 if (attributes.isRegularFile()) {
223 delete(file);
224 }
225 return FileVisitResult.CONTINUE;
226 }
227
228 @Override
229 public FileVisitResult postVisitDirectory(Path directory, IOException ioe)
230 throws IOException {
231 delete(directory);
232 return FileVisitResult.CONTINUE;
233 }
234
235 @Override
236 public FileVisitResult visitFileFailed(Path file, IOException ioe)
237 throws IOException {
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800238 this.exception = ioe;
239 return FileVisitResult.TERMINATE;
Thomas Vachuska02aeb032015-01-06 22:36:30 -0800240 }
241 }
242
Madan Jampani30a57f82015-03-02 12:19:41 -0800243 /**
244 * Returns a human friendly time ago string for a specified system time.
245 * @param unixTime system time in millis
246 * @return human friendly time ago
247 */
248 public static String timeAgo(long unixTime) {
249 long deltaMillis = System.currentTimeMillis() - unixTime;
250 long secondsSince = (long) (deltaMillis / 1000.0);
251 long minsSince = (long) (deltaMillis / (1000.0 * 60));
252 long hoursSince = (long) (deltaMillis / (1000.0 * 60 * 60));
253 long daysSince = (long) (deltaMillis / (1000.0 * 60 * 60 * 24));
254 if (daysSince > 0) {
255 return String.format("%dd ago", daysSince);
256 } else if (hoursSince > 0) {
257 return String.format("%dh ago", hoursSince);
258 } else if (minsSince > 0) {
259 return String.format("%dm ago", minsSince);
260 } else if (secondsSince > 0) {
261 return String.format("%ds ago", secondsSince);
262 } else {
263 return "just now";
264 }
265 }
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800266
267 /**
268 * Copies the specified directory path.&nbsp;Use with great caution since
269 * no attempt is made to check for symbolic links, which could result in
270 * copy of unintended files.
271 *
272 * @param src directory to be copied
273 * @param dst destination directory to be removed
274 * @throws java.io.IOException if unable to remove contents
275 */
276 public static void copyDirectory(String src, String dst) throws IOException {
277 walkFileTree(Paths.get(src), new DirectoryCopier(src, dst));
278 }
279
280 /**
281 * Copies the specified directory path.&nbsp;Use with great caution since
282 * no attempt is made to check for symbolic links, which could result in
283 * copy of unintended files.
284 *
285 * @param src directory to be copied
286 * @param dst destination directory to be removed
287 * @throws java.io.IOException if unable to remove contents
288 */
289 public static void copyDirectory(File src, File dst) throws IOException {
290 walkFileTree(Paths.get(src.getAbsolutePath()),
291 new DirectoryCopier(src.getAbsolutePath(),
292 dst.getAbsolutePath()));
293 }
294
Thomas Vachuska62ad95f2015-02-18 12:11:36 -0800295 // Auxiliary path visitor for recursive directory structure copying.
296 private static class DirectoryCopier extends SimpleFileVisitor<Path> {
Thomas Vachuska90b453f2015-01-30 18:57:14 -0800297 private Path src;
298 private Path dst;
299 private StandardCopyOption copyOption = StandardCopyOption.REPLACE_EXISTING;
300
301 DirectoryCopier(String src, String dst) {
302 this.src = Paths.get(src);
303 this.dst = Paths.get(dst);
304 }
305
306 @Override
307 public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
308 Path targetPath = dst.resolve(src.relativize(dir));
309 if (!Files.exists(targetPath)) {
310 Files.createDirectory(targetPath);
311 }
312 return FileVisitResult.CONTINUE;
313 }
314
315 @Override
316 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
317 Files.copy(file, dst.resolve(src.relativize(file)), copyOption);
318 return FileVisitResult.CONTINUE;
319 }
320 }
321
tom5f38b3a2014-08-27 23:50:54 -0700322}