Ignore those exceptions never occurs
[cli.git] / framework / src / main / java / org / onap / cli / fw / registrar / OnapCommandRegistrar.java
1 /*
2  * Copyright 2017 Huawei Technologies Co., Ltd.
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  */
16
17 package org.onap.cli.fw.registrar;
18
19 import java.io.IOException;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.apache.commons.io.IOUtils;
27 import org.onap.cli.fw.cmd.OnapCommand;
28 import org.onap.cli.fw.conf.OnapCommandConfig;
29 import org.onap.cli.fw.conf.OnapCommandConstants;
30 import org.onap.cli.fw.error.OnapCommandException;
31 import org.onap.cli.fw.error.OnapCommandHelpFailed;
32 import org.onap.cli.fw.error.OnapCommandInvalidRegistration;
33 import org.onap.cli.fw.error.OnapCommandNotFound;
34 import org.onap.cli.fw.error.OnapCommandProductVersionInvalid;
35 import org.onap.cli.fw.error.OnapCommandRegistrationProductInfoMissing;
36 import org.onap.cli.fw.error.OnapUnsupportedSchemaProfile;
37 import org.onap.cli.fw.input.cache.OnapCommandParameterCache;
38 import org.onap.cli.fw.output.OnapCommandPrintDirection;
39 import org.onap.cli.fw.output.OnapCommandResult;
40 import org.onap.cli.fw.output.OnapCommandResultAttribute;
41 import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
42 import org.onap.cli.fw.output.OnapCommandResultType;
43 import org.onap.cli.fw.schema.OnapCommandSchema;
44 import org.onap.cli.fw.schema.OnapCommandSchemaInfo;
45 import org.onap.cli.fw.utils.OnapCommandDiscoveryUtils;
46 import org.onap.cli.fw.utils.OnapCommandHelperUtils;
47 import org.onap.cli.fw.utils.OnapCommandUtils;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51
52 /**
53  * Oclip Command registrar provides a common place, where every command would get registered automatically when its
54  * loaded into JVM.
55  *
56  */
57 public class OnapCommandRegistrar {
58
59     private static Logger LOG = LoggerFactory.getLogger(OnapCommandRegistrar.class);
60
61     private Map<String, Class<? extends OnapCommand>> registry = new HashMap<>();
62
63     private Map<String, Class<? extends OnapCommand>> registryProfilePlugins = new HashMap<>();
64
65     private Set<String> availableProductVersions = new HashSet<>();
66
67     private String enabledProductVersion = null;
68
69     private boolean isInteractiveMode = false;
70
71     private OnapCommandParameterCache paramCache = OnapCommandParameterCache.getInstance();
72
73     public boolean isInteractiveMode() {
74         return isInteractiveMode;
75     }
76
77     public void setInteractiveMode(boolean isInteractiveMode) {
78         this.isInteractiveMode = isInteractiveMode;
79     }
80
81     public Map<String, String> getParamCache() {
82         return paramCache.getParams(this.getEnabledProductVersion());
83     }
84
85     public void addParamCache(String paramName, String paramValue) {
86         paramCache.add(this.getEnabledProductVersion(), paramName, paramValue);
87     }
88
89     public void removeParamCache(String paramName) {
90         paramCache.remove(this.getEnabledProductVersion(), paramName);
91     }
92
93     public void setProfile(String profileName) {
94         this.paramCache.setProfile(profileName);
95     }
96
97     private static OnapCommandRegistrar registrar = null;
98
99     /**
100      * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command.
101      *
102      * @param name
103      *            Command Name
104      * @param cmd
105      *            Command Class
106      * @throws OnapCommandInvalidRegistration
107      *             Invalid registration exception
108      * @throws OnapCommandRegistrationProductInfoMissing
109      */
110     private void register(String name, String version, Class<? extends OnapCommand> cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing {
111         if (version == null || version.isEmpty()) {
112             throw new OnapCommandRegistrationProductInfoMissing(name);
113         }
114
115         this.registry.put(name + ":" + version, cmd);
116         this.availableProductVersions.add(version);
117
118     }
119
120     private void registerProfilePlugin(String profile, Class<? extends OnapCommand> cmd) {
121         this.registryProfilePlugins.put(profile, cmd);
122     }
123
124     private OnapCommandRegistrar() {
125         this.enabledProductVersion = System.getenv(OnapCommandConstants.OPEN_CLI_PRODUCT_IN_USE_ENV_NAME);
126         if (this.enabledProductVersion  == null) {
127             this.enabledProductVersion  = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME);
128         }
129     }
130
131     /**
132      * Get global registrar.
133      *
134      * @throws OnapCommandException
135      *             exception
136      */
137     public static OnapCommandRegistrar getRegistrar() throws OnapCommandException {
138         if (registrar == null) {
139             registrar = new OnapCommandRegistrar();
140             registrar.autoDiscoverSchemas();
141         }
142
143         return registrar;
144     }
145
146     /**
147      * Get the list of discovered commands by registrar.
148      *
149      * @return set
150      */
151     public Set<String> listCommands() {
152         return this.registry.keySet();
153     }
154
155     /**
156      * Get the list of discovered commands for a given product version in registrar.
157      *
158      * @return set
159      */
160     public Set<String> listCommandsForEnabledProductVersion() {
161         String version = this.getEnabledProductVersion();
162
163         Set<String> cmds = new HashSet<>();
164         if (!this.availableProductVersions.contains(version)) {
165             return cmds;
166         }
167
168         for (String cmd: this.registry.keySet()) {
169             if (cmd.split(":")[1].equalsIgnoreCase(version)) {
170                 cmds.add(cmd.split(":")[0]);
171             }
172         }
173         return cmds;
174     }
175
176     public Class<? extends OnapCommand> getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile {
177         if (!this.registryProfilePlugins.containsKey(profile)) {
178             throw new OnapUnsupportedSchemaProfile(profile);
179         }
180
181         return this.registryProfilePlugins.get(profile);
182     }
183
184     public Set<String> getAvailableProductVersions() {
185         return this.availableProductVersions;
186     }
187
188     public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid {
189         if (!this.availableProductVersions.contains(version)) {
190             throw new OnapCommandProductVersionInvalid(version, availableProductVersions);
191         }
192
193         this.enabledProductVersion = version;
194     }
195
196     public String getEnabledProductVersion() {
197         return this.enabledProductVersion;
198     }
199
200     /**
201      * Returns command details.
202      *
203      * @return map
204      * @throws OnapCommandException
205      *             exception
206      */
207     public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException {
208         return OnapCommandDiscoveryUtils.discoverSchemas();
209     }
210
211     /**
212      * Get the OnapCommand, which CLI main would use to find the command based on the command name.
213      *
214      * @param cmdName
215      *            Name of command
216      * @return OnapCommand
217      * @throws OnapCommandException
218      *             Exception
219      */
220     public OnapCommand get(String cmdName) throws OnapCommandException {
221         return this.get(cmdName, this.getEnabledProductVersion());
222     }
223
224     /**
225      * Get the OnapCommand, which CLI main would use to find the command based on the command name.
226      *
227      * @param cmdName
228      *            Name of command
229      * @param version
230      *            product version
231      * @return OnapCommand
232      * @throws OnapCommandException
233      *             Exception
234      */
235     public OnapCommand get(String cmdName, String version) throws OnapCommandException {
236         Class<? extends OnapCommand> cls = registry.get(cmdName + ":" + version);
237         //mrkanag: Restrict auth/catalog type commands only available during devMode. in production
238         //don't expose the auth type and catalog type commands
239
240         if (cls == null) {
241             throw new OnapCommandNotFound(cmdName, version);
242         }
243
244         OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls);
245         String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName();
246         cmd.initializeSchema(schemaName);
247
248         return cmd;
249     }
250
251     private Map<String, Class<OnapCommand>> autoDiscoverCommandPlugins() throws OnapCommandException {
252         List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
253         Map<String, Class<OnapCommand>> map = new HashMap<>();
254
255         for (Class<OnapCommand> cmd : cmds) {
256             if (cmd.isAnnotationPresent(OnapCommandSchema.class)) {
257                 OnapCommandSchema ano = cmd.getAnnotation(OnapCommandSchema.class);
258                 if (ano.schema() != null && !ano.schema().isEmpty()) {
259                     map.put(ano.schema(), cmd);
260                 } else if (ano.type() != null && !ano.type().isEmpty()) {
261                     this.registerProfilePlugin(ano.type(), cmd);
262                     map.put(ano.type(), cmd);
263                 } else {
264                     throw new OnapUnsupportedSchemaProfile(ano.schema());
265                 }
266             }
267         }
268
269         return map;
270     }
271
272     private void autoDiscoverSchemas() throws OnapCommandException {
273         List<OnapCommandSchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true);
274
275         Map<String, Class<OnapCommand>> plugins = this.autoDiscoverCommandPlugins();
276
277         for (OnapCommandSchemaInfo schema : schemas) {
278             if (schema.isIgnore()) {
279                 LOG.info("Ignoring schema " + schema.getSchemaURI());
280                 continue;
281             }
282
283             //First check if there is an specific plugin exist, otherwise check for profile plugin
284              if (plugins.containsKey(schema.getSchemaName())) {
285                  this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName()));
286              } else if (plugins.containsKey(schema.getSchemaProfile())) {
287                 this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaProfile()));
288             } else {
289                 LOG.info("Ignoring schema " + schema.getSchemaURI());
290             }
291         }
292     }
293
294     /**
295      * Helps to find the Oclip CLI version, could be used with --version or -v option.
296      *
297      * @return string
298      */
299     public String getVersion() {
300         String version = this.getClass().getPackage().getImplementationVersion();
301         if (version == null) {
302             version = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_VERSION);
303         }
304
305         String buildTime = OnapCommandHelperUtils.findLastBuildTime();
306         if (buildTime!= null && !buildTime.isEmpty()) {
307             buildTime = " [" + buildTime + "]";
308         } else {
309             buildTime = "";
310         }
311
312         String configuredProductVersion = this.getEnabledProductVersion();
313
314         String versionInfo = "";
315         try {
316             versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(OnapCommandConstants.VERSION_INFO));
317         } catch (IOException e) { // NOSONAR
318             //Never occurs
319         }
320
321         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER, configuredProductVersion);
322         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER, this.availableProductVersions.toString());
323         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_VERSION + "", version + buildTime);
324
325         return versionInfo;
326     }
327
328     /**
329      * Provides the help message in tabular format for all commands registered in this registrar.
330      *
331      * @return string
332      * @throws OnapCommandHelpFailed
333      *             Help cmd failed
334      */
335     public String getHelp() throws OnapCommandHelpFailed {
336         return this.getHelp(false);
337     }
338
339     public String getHelpForEnabledProductVersion() throws OnapCommandHelpFailed {
340         return this.getHelp(true);
341     }
342
343     private String getHelp(boolean isEnabledProductVersionOnly) throws OnapCommandHelpFailed {
344         OnapCommandResult help = new OnapCommandResult();
345         help.setType(OnapCommandResultType.TABLE);
346         help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
347
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);
353
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);
360         }
361
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);
367
368         OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
369         attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase());
370         attrDesc.setDescription(OnapCommandConstants.DESCRIPTION);
371         attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
372         help.getRecords().add(attrDesc);
373
374         for (String cmdName : isEnabledProductVersionOnly ? OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) : OnapCommandUtils.sort(this.listCommands())) {
375             OnapCommand cmd;
376             try {
377                 if (!isEnabledProductVersionOnly) {
378                     String []cmdVer = cmdName.split(":");
379                     cmd = this.get(cmdVer[0], cmdVer[1]);
380                     attr.getValues().add(cmdVer[0]);
381                     attrVer.getValues().add(cmdVer[1]);
382                 } else {
383                     cmd = this.get(cmdName);
384                     attr.getValues().add(cmdName);
385                 }
386
387                 attrSrv.getValues().add(cmd.printVersion());
388                 attrDesc.getValues().add(cmd.getDescription());
389             } catch (OnapCommandException e) {
390                 throw new OnapCommandHelpFailed(e);
391             }
392         }
393
394         try {
395             return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion());
396         } catch (OnapCommandException e) {
397             throw new OnapCommandHelpFailed(e);
398         }
399     }
400 }