Add profile list support
[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     public List<String> getUserProfiles() {
98         return paramCache.getProfiles();
99     }
100
101     private static OnapCommandRegistrar registrar = null;
102
103     /**
104      * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command.
105      *
106      * @param name
107      *            Command Name
108      * @param cmd
109      *            Command Class
110      * @throws OnapCommandInvalidRegistration
111      *             Invalid registration exception
112      * @throws OnapCommandRegistrationProductInfoMissing
113      */
114     private void register(String name, String version, Class<? extends OnapCommand> cmd) throws OnapCommandInvalidRegistration, OnapCommandRegistrationProductInfoMissing {
115         if (version == null || version.isEmpty()) {
116             throw new OnapCommandRegistrationProductInfoMissing(name);
117         }
118
119         this.registry.put(name + ":" + version, cmd);
120         this.availableProductVersions.add(version);
121
122     }
123
124     private void registerProfilePlugin(String profile, Class<? extends OnapCommand> cmd) {
125         this.registryProfilePlugins.put(profile, cmd);
126     }
127
128     private OnapCommandRegistrar() {
129         this.enabledProductVersion = System.getenv(OnapCommandConstants.OPEN_CLI_PRODUCT_IN_USE_ENV_NAME);
130         if (this.enabledProductVersion  == null) {
131             this.enabledProductVersion  = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_PRODUCT_NAME);
132         }
133     }
134
135     /**
136      * Get global registrar.
137      *
138      * @throws OnapCommandException
139      *             exception
140      */
141     public static OnapCommandRegistrar getRegistrar() throws OnapCommandException {
142         if (registrar == null) {
143             registrar = new OnapCommandRegistrar();
144             registrar.autoDiscoverSchemas();
145         }
146
147         return registrar;
148     }
149
150     /**
151      * Get the list of discovered commands by registrar.
152      *
153      * @return set
154      */
155     public Set<String> listCommands() {
156         return this.registry.keySet();
157     }
158
159     /**
160      * Get the list of discovered commands for a given product version in registrar.
161      *
162      * @return set
163      */
164     public Set<String> listCommandsForEnabledProductVersion() {
165         String version = this.getEnabledProductVersion();
166
167         Set<String> cmds = new HashSet<>();
168         if (!this.availableProductVersions.contains(version)) {
169             return cmds;
170         }
171
172         for (String cmd: this.registry.keySet()) {
173             if (cmd.split(":")[1].equalsIgnoreCase(version)) {
174                 cmds.add(cmd.split(":")[0]);
175             }
176         }
177         return cmds;
178     }
179
180     public Class<? extends OnapCommand> getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile {
181         if (!this.registryProfilePlugins.containsKey(profile)) {
182             throw new OnapUnsupportedSchemaProfile(profile);
183         }
184
185         return this.registryProfilePlugins.get(profile);
186     }
187
188     public Set<String> getAvailableProductVersions() {
189         return this.availableProductVersions;
190     }
191
192     public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid {
193         if (!this.availableProductVersions.contains(version)) {
194             throw new OnapCommandProductVersionInvalid(version, availableProductVersions);
195         }
196
197         this.enabledProductVersion = version;
198     }
199
200     public String getEnabledProductVersion() {
201         return this.enabledProductVersion;
202     }
203
204     /**
205      * Returns command details.
206      *
207      * @return map
208      * @throws OnapCommandException
209      *             exception
210      */
211     public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException {
212         return OnapCommandDiscoveryUtils.discoverSchemas();
213     }
214
215     /**
216      * Get the OnapCommand, which CLI main would use to find the command based on the command name.
217      *
218      * @param cmdName
219      *            Name of command
220      * @return OnapCommand
221      * @throws OnapCommandException
222      *             Exception
223      */
224     public OnapCommand get(String cmdName) throws OnapCommandException {
225         return this.get(cmdName, this.getEnabledProductVersion());
226     }
227
228     /**
229      * Get the OnapCommand, which CLI main would use to find the command based on the command name.
230      *
231      * @param cmdName
232      *            Name of command
233      * @param version
234      *            product version
235      * @return OnapCommand
236      * @throws OnapCommandException
237      *             Exception
238      */
239     public OnapCommand get(String cmdName, String version) throws OnapCommandException {
240         Class<? extends OnapCommand> cls = registry.get(cmdName + ":" + version);
241         //mrkanag: Restrict auth/catalog type commands only available during devMode. in production
242         //don't expose the auth type and catalog type commands
243
244         if (cls == null) {
245             throw new OnapCommandNotFound(cmdName, version);
246         }
247
248         OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls);
249         String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName();
250         cmd.initializeSchema(schemaName);
251
252         return cmd;
253     }
254
255     private Map<String, Class<OnapCommand>> autoDiscoverCommandPlugins() throws OnapCommandException {
256         List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
257         Map<String, Class<OnapCommand>> map = new HashMap<>();
258
259         for (Class<OnapCommand> cmd : cmds) {
260             if (cmd.isAnnotationPresent(OnapCommandSchema.class)) {
261                 OnapCommandSchema ano = cmd.getAnnotation(OnapCommandSchema.class);
262                 if (ano.schema() != null && !ano.schema().isEmpty()) {
263                     map.put(ano.schema(), cmd);
264                 } else if (ano.type() != null && !ano.type().isEmpty()) {
265                     this.registerProfilePlugin(ano.type(), cmd);
266                     map.put(ano.type(), cmd);
267                 } else {
268                     throw new OnapUnsupportedSchemaProfile(ano.schema());
269                 }
270             }
271         }
272
273         return map;
274     }
275
276     private void autoDiscoverSchemas() throws OnapCommandException {
277         List<OnapCommandSchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true);
278
279         Map<String, Class<OnapCommand>> plugins = this.autoDiscoverCommandPlugins();
280
281         for (OnapCommandSchemaInfo schema : schemas) {
282             if (schema.isIgnore()) {
283                 LOG.info("Ignoring schema " + schema.getSchemaURI());
284                 continue;
285             }
286
287             //First check if there is an specific plugin exist, otherwise check for profile plugin
288              if (plugins.containsKey(schema.getSchemaName())) {
289                  this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaName()));
290              } else if (plugins.containsKey(schema.getSchemaProfile())) {
291                 this.register(schema.getCmdName(), schema.getProduct(), plugins.get(schema.getSchemaProfile()));
292             } else {
293                 LOG.info("Ignoring schema " + schema.getSchemaURI());
294             }
295         }
296     }
297
298     /**
299      * Helps to find the Oclip CLI version, could be used with --version or -v option.
300      *
301      * @return string
302      */
303     public String getVersion() {
304         String version = this.getClass().getPackage().getImplementationVersion();
305         if (version == null) {
306             version = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_VERSION);
307         }
308
309         String buildTime = OnapCommandHelperUtils.findLastBuildTime();
310         if (buildTime!= null && !buildTime.isEmpty()) {
311             buildTime = " [" + buildTime + "]";
312         } else {
313             buildTime = "";
314         }
315
316         String configuredProductVersion = this.getEnabledProductVersion();
317
318         String versionInfo = "";
319         try {
320             versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(OnapCommandConstants.VERSION_INFO));
321         } catch (IOException e) { // NOSONAR
322             //Never occurs
323         }
324
325         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_ENB_PRD_VER, configuredProductVersion);
326         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_AVL_PRD_VER, this.availableProductVersions.toString());
327         versionInfo = versionInfo.replaceAll(OnapCommandConstants.VERSION_INFO_PLACE_HOLDER_VERSION + "", version + buildTime);
328
329         return versionInfo;
330     }
331
332     /**
333      * Provides the help message in tabular format for all commands registered in this registrar.
334      *
335      * @return string
336      * @throws OnapCommandHelpFailed
337      *             Help cmd failed
338      */
339     public String getHelp() throws OnapCommandHelpFailed {
340         return this.getHelp(false);
341     }
342
343     public String getHelpForEnabledProductVersion() throws OnapCommandHelpFailed {
344         return this.getHelp(true);
345     }
346
347     private String getHelp(boolean isEnabledProductVersionOnly) throws OnapCommandHelpFailed {
348         OnapCommandResult help = new OnapCommandResult();
349         help.setType(OnapCommandResultType.TABLE);
350         help.setPrintDirection(OnapCommandPrintDirection.LANDSCAPE);
351
352         OnapCommandResultAttribute attr = new OnapCommandResultAttribute();
353         attr.setName(OnapCommandConstants.NAME.toUpperCase());
354         attr.setDescription(OnapCommandConstants.DESCRIPTION);
355         attr.setScope(OnapCommandResultAttributeScope.SHORT);
356         help.getRecords().add(attr);
357
358         OnapCommandResultAttribute attrVer = new OnapCommandResultAttribute();
359         if (!isEnabledProductVersionOnly) {
360             attrVer.setName(OnapCommandConstants.INFO_PRODUCT.toUpperCase());
361             attrVer.setDescription(OnapCommandConstants.DESCRIPTION);
362             attrVer.setScope(OnapCommandResultAttributeScope.SHORT);
363             help.getRecords().add(attrVer);
364         }
365
366         OnapCommandResultAttribute attrSrv = new OnapCommandResultAttribute();
367         attrSrv.setName(OnapCommandConstants.INFO_SERVICE.toUpperCase());
368         attrSrv.setDescription(OnapCommandConstants.INFO_SERVICE);
369         attrSrv.setScope(OnapCommandResultAttributeScope.SHORT);
370         help.getRecords().add(attrSrv);
371
372         OnapCommandResultAttribute attrDesc = new OnapCommandResultAttribute();
373         attrDesc.setName(OnapCommandConstants.DESCRIPTION.toUpperCase());
374         attrDesc.setDescription(OnapCommandConstants.DESCRIPTION);
375         attrDesc.setScope(OnapCommandResultAttributeScope.SHORT);
376         help.getRecords().add(attrDesc);
377
378         for (String cmdName : isEnabledProductVersionOnly ? OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) : OnapCommandUtils.sort(this.listCommands())) {
379             OnapCommand cmd;
380             try {
381                 if (!isEnabledProductVersionOnly) {
382                     String []cmdVer = cmdName.split(":");
383                     cmd = this.get(cmdVer[0], cmdVer[1]);
384                     attr.getValues().add(cmdVer[0]);
385                     attrVer.getValues().add(cmdVer[1]);
386                 } else {
387                     cmd = this.get(cmdName);
388                     attr.getValues().add(cmdName);
389                 }
390
391                 attrSrv.getValues().add(cmd.printVersion());
392                 attrDesc.getValues().add(cmd.getDescription());
393             } catch (OnapCommandException e) {
394                 throw new OnapCommandHelpFailed(e);
395             }
396         }
397
398         try {
399             return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion());
400         } catch (OnapCommandException e) {
401             throw new OnapCommandHelpFailed(e);
402         }
403     }
404 }