blob: 0046e03b6b2c1225c201af67a3bc7b987403b74f [file] [log] [blame]
Ray Milkeyd84f89b2018-08-17 14:54:17 -07001/*
2 * Copyright 2014-present Open Networking Foundation
3 *
4 * 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
7 *
8 * 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.
15 */
16package org.onosproject.cli2;
17
18import org.apache.karaf.shell.api.action.Option;
19import org.apache.karaf.shell.api.action.Action;
20import org.onlab.osgi.DefaultServiceDirectory;
21import org.onlab.osgi.ServiceNotFoundException;
22import org.onosproject.codec.CodecContext;
23import org.onosproject.codec.CodecService;
24import org.onosproject.codec.JsonCodec;
25import org.onosproject.core.ApplicationId;
26import org.onosproject.core.CoreService;
27import org.onosproject.net.Annotations;
28
29import com.fasterxml.jackson.databind.ObjectMapper;
30import com.fasterxml.jackson.databind.node.ObjectNode;
31import org.onosproject.net.DefaultAnnotations;
32
33import java.util.Set;
34import java.util.TreeSet;
35
36/**
37 * Base abstraction of Karaf shell commands.
38 */
39public abstract class AbstractShellCommand implements Action, CodecContext {
40
41 @Option(name = "-j", aliases = "--json", description = "Output JSON",
42 required = false, multiValued = false)
43 private boolean json = false;
44
45 /**
46 * Returns the reference to the implementation of the specified service.
47 *
48 * @param serviceClass service class
49 * @param <T> type of service
50 * @return service implementation
51 * @throws org.onlab.osgi.ServiceNotFoundException if service is unavailable
52 */
53 public static <T> T get(Class<T> serviceClass) {
54 return DefaultServiceDirectory.getService(serviceClass);
55 }
56
57 /**
58 * Returns application ID for the CLI.
59 *
60 * @return command-line application identifier
61 */
62 protected ApplicationId appId() {
63 return get(CoreService.class)
64 .registerApplication("org.onosproject.cli");
65 }
66
67 /**
68 * Prints the arguments using the specified format.
69 *
70 * @param format format string; see {@link String#format}
71 * @param args arguments
72 */
73 public void print(String format, Object... args) {
74 System.out.println(String.format(format, args));
75 }
76
77 /**
78 * Prints the arguments using the specified format to error stream.
79 *
80 * @param format format string; see {@link String#format}
81 * @param args arguments
82 */
83 public void error(String format, Object... args) {
84 System.err.println(String.format(format, args));
85 }
86
87 /**
88 * Produces a string image of the specified key/value annotations.
89 *
90 * @param annotations key/value annotations
91 * @return string image with ", k1=v1, k2=v2, ..." pairs
92 */
93 public static String annotations(Annotations annotations) {
94 if (annotations == null) {
95 annotations = DefaultAnnotations.EMPTY;
96 }
97 StringBuilder sb = new StringBuilder();
98 Set<String> keys = new TreeSet<>(annotations.keys());
99 for (String key : keys) {
100 sb.append(", ").append(key).append('=').append(annotations.value(key));
101 }
102 return sb.toString();
103 }
104
105 /**
106 * Produces a string image of the specified key/value annotations.
107 * Excludes the keys in the given Set.
108 *
109 * @param annotations key/value annotations
110 * @param excludedKeys keys not to add in the resulting string
111 * @return string image with ", k1=v1, k2=v2, ..." pairs
112 */
113 public static String annotations(Annotations annotations, Set<String> excludedKeys) {
114 StringBuilder sb = new StringBuilder();
115 Set<String> keys = new TreeSet<>(annotations.keys());
116 keys.removeAll(excludedKeys);
117 for (String key : keys) {
118 sb.append(", ").append(key).append('=').append(annotations.value(key));
119 }
120 return sb.toString();
121 }
122
123 /**
124 * Produces a JSON object from the specified key/value annotations.
125 *
126 * @param mapper ObjectMapper to use while converting to JSON
127 * @param annotations key/value annotations
128 * @return JSON object
129 */
130 public static ObjectNode annotations(ObjectMapper mapper, Annotations annotations) {
131 ObjectNode result = mapper.createObjectNode();
132 for (String key : annotations.keys()) {
133 result.put(key, annotations.value(key));
134 }
135 return result;
136 }
137
138 /**
139 * Indicates whether JSON format should be output.
140 *
141 * @return true if JSON is requested
142 */
143 protected boolean outputJson() {
144 return json;
145 }
146
147 @Override
148 public Object execute() throws Exception {
149 try {
150 doExecute();
151 } catch (ServiceNotFoundException e) {
152 error(e.getMessage());
153 }
154 return null;
155 }
156
157 protected void doExecute() throws Exception {
158 try {
159 execute();
160 } catch (ServiceNotFoundException e) {
161 error(e.getMessage());
162 }
163 }
164
165 private final ObjectMapper mapper = new ObjectMapper();
166
167 @Override
168 public ObjectMapper mapper() {
169 return mapper;
170 }
171
172 @Override
173 @SuppressWarnings("unchecked")
174 public <T> JsonCodec<T> codec(Class<T> entityClass) {
175 return get(CodecService.class).getCodec(entityClass);
176 }
177
178 @Override
179 public <T> T getService(Class<T> serviceClass) {
180 return get(serviceClass);
181 }
182
183 /**
184 * Generates a Json representation of an object.
185 *
186 * @param entity object to generate JSON for
187 * @param entityClass class to format with - this chooses which codec to use
188 * @param <T> Type of the object being formatted
189 * @return JSON object representation
190 */
191 public <T> ObjectNode jsonForEntity(T entity, Class<T> entityClass) {
192 return codec(entityClass).encode(entity, this);
193 }
194}