blob: 184a7e6f00f0e72eaafe6a5ba7864030bd4772f5 [file] [log] [blame]
tom0eb04ca2014-08-25 14:34:51 -07001package org.onlab.onos.cli;
2
3import org.apache.karaf.shell.console.OsgiCommandSupport;
tom0872a172014-09-23 11:24:26 -07004import org.onlab.osgi.DefaultServiceDirectory;
5import org.onlab.osgi.ServiceNotFoundException;
tom0eb04ca2014-08-25 14:34:51 -07006
7/**
8 * Base abstraction of Karaf shell commands.
9 */
10public abstract class AbstractShellCommand extends OsgiCommandSupport {
11
12 /**
tom6d2a43e2014-09-08 01:50:20 -070013 * Returns the reference to the implementation of the specified service.
tom0eb04ca2014-08-25 14:34:51 -070014 *
15 * @param serviceClass service class
16 * @param <T> type of service
17 * @return service implementation
tomcaf3bf72014-09-23 13:20:53 -070018 * @throws org.onlab.osgi.ServiceNotFoundException if service is unavailable
tom0eb04ca2014-08-25 14:34:51 -070019 */
tom6d2a43e2014-09-08 01:50:20 -070020 public static <T> T get(Class<T> serviceClass) {
tom0872a172014-09-23 11:24:26 -070021 return DefaultServiceDirectory.getService(serviceClass);
tom0eb04ca2014-08-25 14:34:51 -070022 }
23
tom6d2a43e2014-09-08 01:50:20 -070024 /**
25 * Prints the arguments using the specified format.
26 *
27 * @param format format string; see {@link String#format}
28 * @param args arguments
29 */
tomcaf3bf72014-09-23 13:20:53 -070030 public void print(String format, Object... args) {
tom6d2a43e2014-09-08 01:50:20 -070031 System.out.println(String.format(format, args));
32 }
33
tom9eb57fb2014-09-11 19:42:38 -070034 /**
35 * Prints the arguments using the specified format to error stream.
36 *
37 * @param format format string; see {@link String#format}
38 * @param args arguments
39 */
tomcaf3bf72014-09-23 13:20:53 -070040 public void error(String format, Object... args) {
tom9eb57fb2014-09-11 19:42:38 -070041 System.err.println(String.format(format, args));
42 }
43
tom0872a172014-09-23 11:24:26 -070044 /**
45 * Executes this command.
46 */
47 protected abstract void execute();
48
49 @Override
50 protected Object doExecute() throws Exception {
51 try {
52 execute();
53 } catch (ServiceNotFoundException e) {
54 error(e.getMessage());
55 }
56 return null;
57 }
58
tom0eb04ca2014-08-25 14:34:51 -070059}