blob: 839d284144531af177f52c02b7c1995f9c4dbdd1 [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001package org.onlab.onos.cli;
2
tom32085cf2014-10-16 00:04:33 -07003import org.apache.karaf.shell.commands.Option;
tom0eb04ca2014-08-25 14:34:51 -07004import org.apache.karaf.shell.console.OsgiCommandSupport;
tom0872a172014-09-23 11:24:26 -07005import org.onlab.osgi.DefaultServiceDirectory;
6import org.onlab.osgi.ServiceNotFoundException;
tom0eb04ca2014-08-25 14:34:51 -07007
8/**
9 * Base abstraction of Karaf shell commands.
10 */
11public abstract class AbstractShellCommand extends OsgiCommandSupport {
12
tom32085cf2014-10-16 00:04:33 -070013 @Option(name = "-j", aliases = "--json", description = "Output JSON",
14 required = false, multiValued = false)
15 private boolean json = false;
16
tom0eb04ca2014-08-25 14:34:51 -070017 /**
tom6d2a43e2014-09-08 01:50:20 -070018 * Returns the reference to the implementation of the specified service.
tom0eb04ca2014-08-25 14:34:51 -070019 *
20 * @param serviceClass service class
21 * @param <T> type of service
22 * @return service implementation
tomcaf3bf72014-09-23 13:20:53 -070023 * @throws org.onlab.osgi.ServiceNotFoundException if service is unavailable
tom0eb04ca2014-08-25 14:34:51 -070024 */
tom6d2a43e2014-09-08 01:50:20 -070025 public static <T> T get(Class<T> serviceClass) {
tom0872a172014-09-23 11:24:26 -070026 return DefaultServiceDirectory.getService(serviceClass);
tom0eb04ca2014-08-25 14:34:51 -070027 }
28
tom6d2a43e2014-09-08 01:50:20 -070029 /**
30 * Prints the arguments using the specified format.
31 *
32 * @param format format string; see {@link String#format}
33 * @param args arguments
34 */
tomcaf3bf72014-09-23 13:20:53 -070035 public void print(String format, Object... args) {
tom6d2a43e2014-09-08 01:50:20 -070036 System.out.println(String.format(format, args));
37 }
38
tom9eb57fb2014-09-11 19:42:38 -070039 /**
40 * Prints the arguments using the specified format to error stream.
41 *
42 * @param format format string; see {@link String#format}
43 * @param args arguments
44 */
tomcaf3bf72014-09-23 13:20:53 -070045 public void error(String format, Object... args) {
tom9eb57fb2014-09-11 19:42:38 -070046 System.err.println(String.format(format, args));
47 }
48
tom0872a172014-09-23 11:24:26 -070049 /**
50 * Executes this command.
51 */
52 protected abstract void execute();
53
tom32085cf2014-10-16 00:04:33 -070054 /**
55 * Indicates whether JSON format should be output.
56 *
57 * @return true if JSON is requested
58 */
59 protected boolean outputJson() {
60 return json;
61 }
62
tom0872a172014-09-23 11:24:26 -070063 @Override
64 protected Object doExecute() throws Exception {
65 try {
66 execute();
67 } catch (ServiceNotFoundException e) {
68 error(e.getMessage());
69 }
70 return null;
71 }
72
tom0eb04ca2014-08-25 14:34:51 -070073}