2 * Copyright 2017 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.cli.fw.registrar;
19 import org.apache.commons.io.IOUtils;
20 import org.onap.cli.fw.cmd.OnapCommand;
21 import org.onap.cli.fw.conf.OnapCommandConfig;
22 import org.onap.cli.fw.conf.OnapCommandConstants;
23 import org.onap.cli.fw.error.OnapCommandException;
24 import org.onap.cli.fw.error.OnapCommandHelpFailed;
25 import org.onap.cli.fw.error.OnapCommandInvalidRegistration;
26 import org.onap.cli.fw.error.OnapCommandNotFound;
27 import org.onap.cli.fw.error.OnapCommandProductVersionInvalid;
28 import org.onap.cli.fw.error.OnapCommandRegistrationProductInfoMissing;
29 import org.onap.cli.fw.error.OnapUnsupportedSchemaProfile;
30 import org.onap.cli.fw.input.cache.OnapCommandParameterCache;
31 import org.onap.cli.fw.output.OnapCommandPrintDirection;
32 import org.onap.cli.fw.output.OnapCommandResult;
33 import org.onap.cli.fw.output.OnapCommandResultAttribute;
34 import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
35 import org.onap.cli.fw.output.OnapCommandResultType;
36 import org.onap.cli.fw.schema.OnapCommandSchema;
37 import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
38 import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
39 import org.onap.cli.fw.utils.OnapCommandHelperUtils;
40 import org.onap.cli.fw.utils.OnapCommandUtils;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import java.io.IOException;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.List;
53 * Oclip Command registrar provides a common place, where every command would get registered automatically when its
57 public class OnapCommandRegistrar {
59 private static Logger LOG = LoggerFactory.getLogger(OnapCommandRegistrar.class);
61 private Map<String, Class<? extends OnapCommand>> registry = new HashMap<>();
63 private Map<String, Class<? extends OnapCommand>> registryProfilePlugins = new HashMap<>();
65 private Set<String> availableProductVersions = new HashSet<>();
67 private String enabledProductVersion = null;
69 private boolean isInteractiveMode = false;
71 private OnapCommandParameterCache paramCache = OnapCommandParameterCache.getInstance();
73 public boolean isInteractiveMode() {
74 return isInteractiveMode;
77 public void setInteractiveMode(boolean isInteractiveMode) {
78 this.isInteractiveMode = isInteractiveMode;
81 public Map<String, String> getParamCache() {
82 return paramCache.getParams(this.getEnabledProductVersion());
85 public void addParamCache(String paramName, String paramValue) {
86 paramCache.add(this.getEnabledProductVersion(), paramName, paramValue);
89 public void removeParamCache(String paramName) {
90 paramCache.remove(this.getEnabledProductVersion(), paramName);
93 public void setProfile(String profileName, List<String> includes, List<String> excludes) {
94 this.paramCache.setProfile(profileName);
96 for (String profile : includes) {
97 this.paramCache.includeProfile(profile);
100 for (String profile : excludes) {
101 this.paramCache.excludeProfile(profile);
105 public List<String> getUserProfiles() {
106 return paramCache.getProfiles();
109 private static OnapCommandRegistrar registrar = null;
112 * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command.
114 * @param name Command Name
115 * @param cmd Command Class
116 * @throws OnapCommandRegistrationProductInfoMissing
118 private void register(String name, String version, Class<? extends OnapCommand> cmd) throws OnapCommandRegistrationProductInfoMissing {
119 if (version == null || version.isEmpty()) {
120 throw new OnapCommandRegistrationProductInfoMissing(name);
123 this.registry.put(name + ":" + version, cmd);
124 this.availableProductVersions.add(version);
128 private void registerProfilePlugin(String profile, Class<? extends OnapCommand> cmd) {
129 this.registryProfilePlugins.put(profile, cmd);
132 private OnapCommandRegistrar() {
133 this.enabledProductVersion = System.getenv(OnapCommandConstants.OPEN_CLI_PRODUCT_IN_USE_ENV_NAME);
134 if (this.enabledProductVersion == null) {
135 this.enabledProductVersion = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME);
140 * Get global registrar.
142 * @throws OnapCommandException exception
144 public static OnapCommandRegistrar getRegistrar() throws OnapCommandException {
145 if (registrar == null) {
146 registrar = new OnapCommandRegistrar();
147 registrar.autoDiscoverSchemas();
154 * Get the list of discovered commands by registrar.
158 public Set<String> listCommands() {
159 return this.registry.keySet();
163 * Get the list of discovered commands for a given product version in registrar.
167 public Set<String> listCommandsForEnabledProductVersion() {
168 String version = this.getEnabledProductVersion();
170 Set<String> cmds = new HashSet<>();
171 if (!this.availableProductVersions.contains(version)) {
175 for (String cmd : this.registry.keySet()) {
176 if (cmd.split(":")[1].equalsIgnoreCase(version)) {
177 cmds.add(cmd.split(":")[0]);
183 public Class<? extends OnapCommand> getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile {
184 if (!this.registryProfilePlugins.containsKey(profile)) {
185 throw new OnapUnsupportedSchemaProfile(profile);
188 return this.registryProfilePlugins.get(profile);
191 public Set<String> getAvailableProductVersions() {
192 return this.availableProductVersions;
195 public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid {
196 if (!this.availableProductVersions.contains(version)) {
197 throw new OnapCommandProductVersionInvalid(version, availableProductVersions);
200 this.enabledProductVersion = version;
203 public String getEnabledProductVersion() {
204 return this.enabledProductVersion;
208 * Returns command details.
211 * @throws OnapCommandException exception
213 public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException {
214 return OnapCommandDiscoveryUtils.discoverSchemas();
218 * Get the OnapCommand, which CLI main would use to find the command based on the command name.
220 * @param cmdName Name of command
221 * @return OnapCommand
222 * @throws OnapCommandException Exception
224 public OnapCommand get(String cmdName) throws OnapCommandException {
225 return this.get(cmdName, this.getEnabledProductVersion());
229 * Get the OnapCommand, which CLI main would use to find the command based on the command name.
231 * @param cmdName Name of command
232 * @param version product version
233 * @return OnapCommand
234 * @throws OnapCommandException Exception
236 public OnapCommand get(String cmdName, String version) throws OnapCommandException {
237 Class<? extends OnapCommand> cls = registry.get(cmdName + ":" + version);
238 //mrkanag: Restrict auth/catalog type commands only available during devMode. in production
239 //don't expose the auth type and catalog type commands
242 throw new OnapCommandNotFound(cmdName, version);
245 OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls);
246 String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName();
247 cmd.initializeSchema(schemaName);
252 private Map<String, Class<OnapCommand>> autoDiscoverCommandPlugins() throws OnapCommandException {
253 List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
254 Map<String, Class<OnapCommand>> map = new HashMap<>();
256 for (Class<OnapCommand> cmd : cmds) {
257 if (cmd.isAnnotationPresent(OnapCommandSchema.class)) {
258 OnapCommandSchema ano = cmd.getAnnotation(OnapCommandSchema.class);
259 if (ano.schema() != null && !ano.schema().isEmpty()) {
260 map.put(ano.schema(), cmd);
261 } else if (ano.type() != null && !ano.type().isEmpty()) {
262 this.registerProfilePlugin(ano.type(), cmd);
263 map.put(ano.type(), cmd);
265 throw new OnapUnsupportedSchemaProfile(ano.schema());
273 private void autoDiscoverSchemas() throws OnapCommandException {
274 List<OnapCommandSchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true);
276 Map<String, Class<OnapCommand>> plugins = this.autoDiscoverCommandPlugins();
278 for (OnapCommandSchemaInfo schema : schemas) {
279 if (schema.isIgnore()) {
280 LOG.info("Ignoring schema " + schema.getSchemaURI());
284 //First check if there is an specific plugin exist, otherwise check for profile plugin
285 if (plugins.containsKey(schema.getSchemaName())) {
286 this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName()));
287 } else if (plugins.containsKey(schema.getSchemaProfile())) {
288 this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaProfile()));
290 LOG.info("Ignoring schema " + schema.getSchemaURI());
296 * Helps to find the Oclip CLI version, could be used with --version or -v option.
300 public String getVersion() {
301 String version = this.getClass().getPackage().getImplementationVersion();
302 if (version == null) {
303 version = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_VERSION);
306 String buildTime = OnapCommandHelperUtils.findLastBuildTime();
307 if (buildTime != null && !buildTime.isEmpty()) {
308 buildTime = " [" + buildTime + "]";
313 String configuredProductVersion = this.getEnabledProductVersion();
315 String versionInfo = "";
317 versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(OnapCommandConstants.VERSION_INFO));
318 } catch (IOException e) { // NOSONAR
322 versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER, configuredProductVersion);
323 versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER, this.availableProductVersions.toString());
324 versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_VERSION + "", version + buildTime);
330 * Provides the help message in tabular format for all commands registered in this registrar.
333 * @throws OnapCommandHelpFailed Help cmd failed
335 public String getHelp() throws OnapCommandHelpFailed {
336 return this.getHelp(false);
339 public String getHelpForEnabledProductVersion() throws OnapCommandHelpFailed {
340 return this.getHelp(true);
343 private String getHelp(boolean isEnabledProductVersionOnly) throws OnapCommandHelpFailed {
344 OnapCommandResult help = new OnapCommandResult();
345 help.setType(OnapCommandResultType.TABLE);
346 help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
348 OnapCommandResultAttribute attr = new OnapCommandResultAttribute();
349 attr.setName(OnapCommandConstants.NAME.toUpperCase());
350 attr.setDescription(OnapCommandConstants.DESCRIPTION);
351 attr.setScope(OnapCommandResultAttributeScope.SHORT);
352 help.getRecords().add(attr);
354 OnapCommandResultAttribute attrVer = new OnapCommandResultAttribute();
355 if (!isEnabledProductVersionOnly) {
356 attrVer.setName(OnapCommandConstants.INFO_PRODUCT.toUpperCase());
357 attrVer.setDescription(OnapCommandConstants.DESCRIPTION);
358 attrVer.setScope(OnapCommandResultAttributeScope.SHORT);
359 help.getRecords().add(attrVer);
362 OnapCommandResultAttribute attrSrv = new OnapCommandResultAttribute();
363 attrSrv.setName(OnapCommandConstants.INFO_SERVICE.toUpperCase());
364 attrSrv.setDescription(OnapCommandConstants.INFO_SERVICE);
365 attrSrv.setScope(OnapCommandResultAttributeScope.SHORT);
366 help.getRecords().add(attrSrv);
368 OnapCommandResultAttribute attrState = new OnapCommandResultAttribute();
369 attrState.setName(OnapCommandConstants.INFO_STATE.toUpperCase());
370 attrState.setDescription(OnapCommandConstants.INFO_STATE);
371 attrState.setScope(OnapCommandResultAttributeScope.SHORT);
372 help.getRecords().add(attrState);
375 OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
376 attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase());
377 attrDesc.setDescription(OnapCommandConstants.DESCRIPTION);
378 attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
379 help.getRecords().add(attrDesc);
381 for (String cmdName : isEnabledProductVersionOnly ?
382 OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) :
383 OnapCommandUtils.sort(this.listCommands())) {
386 if (!isEnabledProductVersionOnly) {
387 String[] cmdVer = cmdName.split(":");
388 cmd = this.get(cmdVer[0], cmdVer[1]);
389 attr.getValues().add(cmdVer[0]);
390 attrVer.getValues().add(cmdVer[1]);
392 cmd = this.get(cmdName);
393 attr.getValues().add(cmdName);
396 attrSrv.getValues().add(cmd.getInfo().getService());
397 attrDesc.getValues().add(cmd.getDescription());
398 attrState.getValues().add(cmd.getInfo().getState().name());
399 } catch (OnapCommandException e) {
400 throw new OnapCommandHelpFailed(e);
405 return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion());
406 } catch (OnapCommandException e) {
407 throw new OnapCommandHelpFailed(e);
411 public List<Map<String, ?>> getTestSuite(String cmd) throws OnapCommandException {
412 return OnapCommandDiscoveryUtils.createTestSuite(cmd, enabledProductVersion);