Make the var names compliant to standard
[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 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;
43
44 import java.io.IOException;
45 import java.util.HashMap;
46 import java.util.HashSet;
47 import java.util.List;
48 import java.util.Map;
49 import java.util.Set;
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, List<String> includes, List<String> excludes) {
94         this.paramCache.setProfile(profileName);
95
96         for (String profile : includes) {
97             this.paramCache.includeProfile(profile);
98         }
99
100         for (String profile : excludes) {
101             this.paramCache.excludeProfile(profile);
102         }
103     }
104
105     public List<String> getUserProfiles() {
106         return paramCache.getProfiles();
107     }
108
109     private static OnapCommandRegistrar registrar = null;
110
111     /**
112      * Register the command into registrar and throws OnapInvalidCommandRegistration for invalid command.
113      *
114      * @param name Command Name
115      * @param cmd  Command Class
116      * @throws OnapCommandRegistrationProductInfoMissing
117      */
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);
121         }
122
123         this.registry.put(name + ":" + version, cmd);
124         this.availableProductVersions.add(version);
125
126     }
127
128     private void registerProfilePlugin(String profile, Class<? extends OnapCommand> cmd) {
129         this.registryProfilePlugins.put(profile, cmd);
130     }
131
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);
136         }
137     }
138
139     /**
140      * Get global registrar.
141      *
142      * @throws OnapCommandException exception
143      */
144     public static OnapCommandRegistrar getRegistrar() throws OnapCommandException {
145         if (registrar == null) {
146             registrar = new OnapCommandRegistrar();
147             registrar.autoDiscoverSchemas();
148         }
149
150         return registrar;
151     }
152
153     /**
154      * Get the list of discovered commands by registrar.
155      *
156      * @return set
157      */
158     public Set<String> listCommands() {
159         return this.registry.keySet();
160     }
161
162     /**
163      * Get the list of discovered commands for a given product version in registrar.
164      *
165      * @return set
166      */
167     public Set<String> listCommandsForEnabledProductVersion() {
168         String version = this.getEnabledProductVersion();
169
170         Set<String> cmds = new HashSet<>();
171         if (!this.availableProductVersions.contains(version)) {
172             return cmds;
173         }
174
175         for (String cmd : this.registry.keySet()) {
176             if (cmd.split(":")[1].equalsIgnoreCase(version)) {
177                 cmds.add(cmd.split(":")[0]);
178             }
179         }
180         return cmds;
181     }
182
183     public Class<? extends OnapCommand> getProfilePlugin(String profile) throws OnapUnsupportedSchemaProfile {
184         if (!this.registryProfilePlugins.containsKey(profile)) {
185             throw new OnapUnsupportedSchemaProfile(profile);
186         }
187
188         return this.registryProfilePlugins.get(profile);
189     }
190
191     public Set<String> getAvailableProductVersions() {
192         return this.availableProductVersions;
193     }
194
195     public void setEnabledProductVersion(String version) throws OnapCommandProductVersionInvalid {
196         if (!this.availableProductVersions.contains(version)) {
197             throw new OnapCommandProductVersionInvalid(version, availableProductVersions);
198         }
199
200         this.enabledProductVersion = version;
201     }
202
203     public String getEnabledProductVersion() {
204         return this.enabledProductVersion;
205     }
206
207     /**
208      * Returns command details.
209      *
210      * @return map
211      * @throws OnapCommandException exception
212      */
213     public List<OnapCommandSchemaInfo> listCommandInfo() throws OnapCommandException {
214         return OnapCommandDiscoveryUtils.discoverSchemas();
215     }
216
217     /**
218      * Get the OnapCommand, which CLI main would use to find the command based on the command name.
219      *
220      * @param cmdName Name of command
221      * @return OnapCommand
222      * @throws OnapCommandException 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 Name of command
232      * @param version product version
233      * @return OnapCommand
234      * @throws OnapCommandException Exception
235      */
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
240
241         if (cls == null) {
242             throw new OnapCommandNotFound(cmdName, version);
243         }
244
245         OnapCommand cmd = OnapCommandDiscoveryUtils.loadCommandClass(cls);
246         String schemaName = OnapCommandDiscoveryUtils.getSchemaInfo(cmdName, version).getSchemaName();
247         cmd.initializeSchema(schemaName);
248
249         return cmd;
250     }
251
252     private Map<String, Class<OnapCommand>> autoDiscoverCommandPlugins() throws OnapCommandException {
253         List<Class<OnapCommand>> cmds = OnapCommandDiscoveryUtils.discoverCommandPlugins();
254         Map<String, Class<OnapCommand>> map = new HashMap<>();
255
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);
264                 } else {
265                     throw new OnapUnsupportedSchemaProfile(ano.schema());
266                 }
267             }
268         }
269
270         return map;
271     }
272
273     private void autoDiscoverSchemas() throws OnapCommandException {
274         List<OnapCommandSchemaInfo> schemas = OnapCommandDiscoveryUtils.discoverOrLoadSchemas(true);
275
276         Map<String, Class<OnapCommand>> plugins = this.autoDiscoverCommandPlugins();
277
278         for (OnapCommandSchemaInfo schema : schemas) {
279             if (schema.isIgnore()) {
280                 log.info("Ignoring schema " + schema.getSchemaURI());
281                 continue;
282             }
283
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()));
289             } else {
290                 log.info("Ignoring schema " + schema.getSchemaURI());
291             }
292         }
293     }
294
295     /**
296      * Helps to find the Oclip CLI version, could be used with --version or -v option.
297      *
298      * @return string
299      */
300     public String getVersion() {
301         String version = this.getClass().getPackage().getImplementationVersion();
302         if (version == null) {
303             version = OnapCommandConfig.getPropertyValue(OnapCommandConstants.OPEN_CLI_VERSION);
304         }
305
306         String buildTime = OnapCommandHelperUtils.findLastBuildTime();
307         if (buildTime != null && !buildTime.isEmpty()) {
308             buildTime = " [" + buildTime + "]";
309         } else {
310             buildTime = "";
311         }
312
313         String configuredProductVersion = this.getEnabledProductVersion();
314
315         String versionInfo = "";
316         try {
317             versionInfo = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(OnapCommandConstants.VERSION_INFO));
318         } catch (IOException e) { // NOSONAR
319             //Never occurs
320         }
321
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);
325
326         return versionInfo;
327     }
328
329     /**
330      * Provides the help message in tabular format for all commands registered in this registrar.
331      *
332      * @return string
333      * @throws OnapCommandHelpFailed 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 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);
373
374
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);
380
381         for (String cmdName : isEnabledProductVersionOnly ?
382                 OnapCommandUtils.sort(this.listCommandsForEnabledProductVersion()) :
383                     OnapCommandUtils.sort(this.listCommands())) {
384             OnapCommand cmd;
385             try {
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]);
391                 } else {
392                     cmd = this.get(cmdName);
393                     attr.getValues().add(cmdName);
394                 }
395
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);
401             }
402         }
403
404         try {
405             return "\n\nCommands:\n" + help.print() + (isEnabledProductVersionOnly ? "" : "\n" + this.getVersion());
406         } catch (OnapCommandException e) {
407             throw new OnapCommandHelpFailed(e);
408         }
409     }
410
411     public List<Map<String, ?>> getTestSuite(String cmd) throws OnapCommandException {
412         return OnapCommandDiscoveryUtils.createTestSuite(cmd, enabledProductVersion);
413     }
414 }