Add auth mode in service
[cli.git] / framework / src / main / java / org / onap / cli / fw / OnapCommand.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;
18
19 import org.onap.cli.fw.ad.OnapAuthClient;
20 import org.onap.cli.fw.ad.OnapCredentials;
21 import org.onap.cli.fw.ad.OnapService;
22 import org.onap.cli.fw.conf.Constants;
23 import org.onap.cli.fw.conf.OnapCommandConfg;
24 import org.onap.cli.fw.error.OnapCommandException;
25 import org.onap.cli.fw.error.OnapCommandHelpFailed;
26 import org.onap.cli.fw.error.OnapCommandInvalidParameterType;
27 import org.onap.cli.fw.error.OnapCommandInvalidPrintDirection;
28 import org.onap.cli.fw.error.OnapCommandInvalidResultAttributeScope;
29 import org.onap.cli.fw.error.OnapCommandInvalidSchema;
30 import org.onap.cli.fw.error.OnapCommandInvalidSchemaVersion;
31 import org.onap.cli.fw.error.OnapCommandNotInitialized;
32 import org.onap.cli.fw.error.OnapCommandParameterMissing;
33 import org.onap.cli.fw.error.OnapCommandParameterNameConflict;
34 import org.onap.cli.fw.error.OnapCommandParameterOptionConflict;
35 import org.onap.cli.fw.error.OnapCommandRegistrationFailed;
36 import org.onap.cli.fw.error.OnapCommandSchemaNotFound;
37 import org.onap.cli.fw.input.OnapCommandParameter;
38 import org.onap.cli.fw.output.OnapCommandResult;
39 import org.onap.cli.fw.output.OnapCommandResultAttributeScope;
40 import org.onap.cli.fw.output.ResultType;
41 import org.onap.cli.fw.utils.OnapCommandUtils;
42
43 import java.util.ArrayList;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.Set;
47
48 /**
49  * Onap Command.
50  *
51  */
52 public abstract class OnapCommand {
53
54     private String cmdDescription;
55
56     private String cmdName;
57
58     private String cmdSchemaName;
59
60     private OnapService onapService = new OnapService();
61
62     private List<OnapCommandParameter> cmdParameters = new ArrayList<>();
63
64     private OnapCommandResult cmdResult = new OnapCommandResult();
65
66     protected OnapAuthClient authClient;
67
68     protected boolean isInitialzied = false;
69
70     public String getSchemaVersion() {
71         return Constants.ONAP_CMD_SCHEMA_VERSION_VALUE;
72     }
73
74     /**
75      * Onap command description, defined by derived command.
76      */
77     public String getDescription() {
78         return this.cmdDescription;
79     }
80
81     public void setDescription(String description) {
82         this.cmdDescription = description;
83     }
84
85     /*
86      * Onap command name like user-create, ns-list, etc , defined by derived command
87      */
88     public String getName() {
89         return this.cmdName;
90     }
91
92     public void setName(String name) {
93         this.cmdName = name;
94     }
95
96     public boolean isCommandInternal() {
97         return onapService.getName() != null
98                 && onapService.getName().equalsIgnoreCase(OnapCommandConfg.getInternalCmd());
99     }
100
101     /*
102      * Onap service, this command uses to execute it. , defined by derived command
103      */
104     public OnapService getService() {
105         return this.onapService;
106     }
107
108     public void setService(OnapService service) {
109         this.onapService = service;
110     }
111
112     public void setParameters(List<OnapCommandParameter> parameters) {
113         this.cmdParameters = parameters;
114     }
115
116     /*
117      * Onap command input parameters, defined by derived command
118      */
119     public List<OnapCommandParameter> getParameters() {
120         return this.cmdParameters;
121     }
122
123     /*
124      * Onap command input parameters, defined by derived command
125      */
126     public Map<String, OnapCommandParameter> getParametersMap() {
127         return OnapCommandUtils.getInputMap(this.getParameters());
128     }
129
130     /*
131      * Onap command output results, defined by derived command
132      */
133     public OnapCommandResult getResult() {
134         return this.cmdResult;
135     }
136
137     public void setResult(OnapCommandResult result) {
138         this.cmdResult = result;
139     }
140
141     public String getSchemaName() {
142         return cmdSchemaName;
143     }
144
145     protected void setSchemaName(String schemaName) {
146         this.cmdSchemaName = schemaName;
147     }
148
149     /**
150      * Initialize this command from command schema.
151      *
152      * @throws OnapCommandRegistrationFailed
153      *             Command Registration Exception
154      * @throws OnapCommandInvalidResultAttributeScope
155      *             InvalidResultAttribute Exception
156      * @throws OnapCommandInvalidPrintDirection
157      *             InvalidPrintDirection Exception
158      * @throws OnapCommandInvalidParameterType
159      *             InvalidParameterType Exception
160      * @throws OnapCommandSchemaNotFound
161      *             SchemaNotFound Exception
162      * @throws OnapCommandInvalidSchema
163      *             InvalidSchema Exception
164      * @throws OnapCommandParameterOptionConflict
165      *             ParameterOptionConflict Exception
166      * @throws OnapCommandParameterNameConflict
167      *             ParameterNameConflict Exception
168      * @throws OnapCommandInvalidSchemaVersion
169      *             InvalidSchemaVersion Exception
170      */
171     public void initializeSchema(String schema) throws OnapCommandException {
172         this.setSchemaName(schema);
173         OnapCommandUtils.loadSchema(this, schema, true);
174         this.initializeProfileSchema();
175         this.isInitialzied = true;
176     }
177
178     /**
179      * Any additional profile based such as http/swagger schema could be initialized.
180      */
181     protected void initializeProfileSchema() throws OnapCommandException {
182     }
183
184     /*
185      * Validate input parameters. This can be overridden in derived commands
186      */
187     protected void validate() throws OnapCommandException {
188         for (OnapCommandParameter param : this.getParameters()) {
189             try {
190                 param.validate();
191             } catch (OnapCommandParameterMissing e) {
192                 if (OnapCommandConfg.getExcludeParamsForNoAuthEnableExternalCmd().contains(param.getName())) {
193                     OnapCommandParameter noAuthParam = this.getParameters().stream().filter(p -> p.getName()
194                             .equalsIgnoreCase(Constants.DEFAULT_PARAMETER_OUTPUT_NO_AUTH)).findFirst().get();
195
196                     if ("true".equalsIgnoreCase(noAuthParam.getValue().toString())) {
197                         continue;
198                     }
199                 }
200                 throw e;
201             } catch (OnapCommandException e) {
202                 throw e;
203             }
204
205         }
206     }
207
208     /**
209      * Onap command execute with given parameters on service. Before calling this method, its mandatory to set all
210      * parameters value.
211      *
212      * @throws OnapCommandException
213      *             : General Command Exception
214      */
215     public OnapCommandResult execute() throws OnapCommandException {
216         if (!this.isInitialzied) {
217             throw new OnapCommandNotInitialized(this.getClass().getName());
218         }
219
220         Map<String, OnapCommandParameter> paramMap = this.getParametersMap();
221
222         // -h or --help is always higher precedence !, user can set this value to get help message
223         if ("true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_HELP).getValue())) {
224             OnapCommandResult result = new OnapCommandResult();
225             result.setType(ResultType.TEXT);
226             result.setOutput(this.printHelp());
227             return result;
228         }
229
230         // -v or --version is next higher precedence !, user can set this value to get help message
231         if ("true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_VERSION).getValue())) {
232             OnapCommandResult result = new OnapCommandResult();
233             result.setType(ResultType.TEXT);
234             result.setOutput(this.printVersion());
235             return result;
236         }
237
238         // validate
239         this.validate();
240
241         // -f or --format
242         this.cmdResult.setType(
243                 ResultType.get(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_FORMAT).getValue().toString()));
244         if ("true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_ATTR_LONG).getValue())) {
245             this.cmdResult.setScope(OnapCommandResultAttributeScope.LONG);
246         }
247         // --no-title
248         if ("true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_NO_TITLE).getValue())) {
249             this.cmdResult.setIncludeTitle(false);
250         }
251
252         // --debug
253         if ("true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_DEBUG).getValue())) {
254             this.cmdResult.setDebug(true);
255         }
256
257         try {
258             OnapCredentials creds = OnapCommandUtils.fromParameters(this.getParameters());
259             boolean isAuthRequired = !this.onapService.isNoAuth()
260                     && "true".equals(paramMap.get(Constants.DEFAULT_PARAMETER_OUTPUT_NO_AUTH).getValue());
261
262             if (!isCommandInternal()) {
263                 this.authClient = new OnapAuthClient(creds, this.getResult().isDebug());
264             }
265
266             if (isAuthRequired) {
267                 this.authClient.login();
268             }
269
270             this.run();
271
272             if (isAuthRequired) {
273                 this.authClient.logout();
274             }
275
276             if (this.cmdResult.isDebug() && authClient != null) {
277                 this.cmdResult.setDebugInfo(this.authClient.getDebugInfo());
278             }
279         } catch (OnapCommandException e) {
280             if (this.cmdResult.isDebug() && authClient != null) {
281                 this.cmdResult.setDebugInfo(this.authClient.getDebugInfo());
282             }
283             throw e;
284         }
285
286         return this.cmdResult;
287     }
288
289     /*
290      * Each command implements run method to executing the command.
291      *
292      */
293     protected abstract void run() throws OnapCommandException;
294
295     /*
296      * Get my service base path (endpoint).
297      */
298     protected String getBasePath() throws OnapCommandException {
299         return this.authClient.getServiceBasePath(this.getService());
300     }
301
302     protected String getAuthToken() {
303         return this.authClient.getAuthToken();
304     }
305
306     /**
307      * Returns the service service version it supports.
308      *
309      * @return version
310      */
311     public String printVersion() {
312         return this.getService().toString();
313     }
314
315     /**
316      * Provides help message for this command.
317      *
318      * @return help message
319      * @throws OnapCommandHelpFailed
320      *             Failed to execute Help command.
321      */
322     public String printHelp() throws OnapCommandHelpFailed {
323         return OnapCommandUtils.help(this);
324     }
325     // (mrkanag) Add toString for all command, parameter, result, etc objects in JSON format
326 }