Do not use the same named local var as memeber var
[cli.git] / profiles / http / src / main / java / org / onap / cli / fw / http / cmd / OnapHttpCommand.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.http.cmd;
18
19 import org.onap.cli.fw.cmd.OnapCommand;
20 import org.onap.cli.fw.cmd.OnapCommandType;
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.OnapCommandExecutionFailed;
25 import org.onap.cli.fw.http.auth.OnapCommandHttpAuthClient;
26 import org.onap.cli.fw.http.auth.OnapCommandHttpService;
27 import org.onap.cli.fw.http.conf.OnapCommandHttpConstants;
28 import org.onap.cli.fw.http.connect.HttpInput;
29 import org.onap.cli.fw.http.connect.HttpResult;
30 import org.onap.cli.fw.http.error.OnapCommandFailedMocoGenerate;
31 import org.onap.cli.fw.http.mock.MocoServer;
32 import org.onap.cli.fw.http.schema.OnapCommandSchemaHttpLoader;
33 import org.onap.cli.fw.http.utils.OnapCommandHttpUtils;
34 import org.onap.cli.fw.input.OnapCommandParameter;
35 import org.onap.cli.fw.output.OnapCommandResultAttribute;
36 import org.onap.cli.fw.schema.OnapCommandSchema;
37 import org.onap.cli.fw.utils.OnapCommandUtils;
38 import org.onap.cli.http.mock.MockJsonGenerator;
39 import org.onap.cli.http.mock.MockRequest;
40 import org.onap.cli.http.mock.MockResponse;
41
42 import java.io.IOException;
43 import java.util.ArrayList;
44 import java.util.HashMap;
45 import java.util.List;
46 import java.util.Map;
47 import java.util.Map.Entry;
48 import java.util.Optional;
49
50 /**
51  * Oclip http Command.
52  *
53  */
54 @OnapCommandSchema(type = OnapCommandHttpConstants.HTTP_SCHEMA_PROFILE)
55 public class OnapHttpCommand extends OnapCommand {
56
57     private HttpInput input = new HttpInput();
58
59     private List<Integer> successStatusCodes = new ArrayList<>();
60
61     private Map<String, String> resultMap = new HashMap<>();
62
63     protected OnapCommandHttpAuthClient authClient;
64
65     private OnapCommandHttpService oclipService = new OnapCommandHttpService();
66
67     private MocoServer mocoServer;
68
69     boolean shouldVerify = false;
70
71     boolean mockingEnabled;
72
73     public OnapHttpCommand() {
74         super.addDefaultSchemas(OnapCommandHttpConstants.DEFAULT_PARAMETER_HTTP_FILE_NAME);
75     }
76
77     public void setInput(HttpInput input) {
78         this.input = input;
79     }
80
81     @Override
82     public String getSchemaVersion() {
83         return OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0;
84     }
85
86     public void setSuccessStatusCodes(List<Integer> successStatusCodes) {
87         this.successStatusCodes = successStatusCodes;
88     }
89
90     public void setResultMap(Map<String, String> resultMap) {
91         this.resultMap = resultMap;
92     }
93
94     public HttpInput getInput() {
95         return input;
96     }
97
98     public List<Integer> getSuccessStatusCodes() {
99         return successStatusCodes;
100     }
101
102     public Map<String, String> getResultMap() {
103         return resultMap;
104     }
105
106     /*
107      * Oclip service, this command uses to execute it.
108      */
109     public OnapCommandHttpService getService() {
110         return this.oclipService;
111     }
112
113     public void setService(OnapCommandHttpService service) {
114         this.oclipService = service;
115     }
116
117     @Override
118     protected List<String> initializeProfileSchema(Map<String, ?> schemaMap, boolean validate) throws OnapCommandException {
119         return OnapCommandSchemaHttpLoader.parseHttpSchema(this, schemaMap, validate);
120     }
121
122     @Override
123     protected void validate() throws OnapCommandException {
124         if (! this.isAuthRequired()) {
125             if (this.getParametersMap().containsKey(OnapCommandHttpConstants.DEAFULT_PARAMETER_USERNAME)) {
126                 this.getParametersMap().get(OnapCommandHttpConstants.DEAFULT_PARAMETER_USERNAME).setOptional(true);
127             }
128             if (this.getParametersMap().containsKey(OnapCommandHttpConstants.DEAFULT_PARAMETER_PASSWORD)) {
129                 this.getParametersMap().get(OnapCommandHttpConstants.DEAFULT_PARAMETER_PASSWORD).setOptional(true);
130             }
131         }
132
133         super.validate();
134     }
135
136     private boolean isAuthRequired() {
137         return !this.getService().isNoAuth()
138                 && !(Boolean) (this.getParametersMap().get(OnapCommandHttpConstants.DEFAULT_PARAMETER_NO_AUTH).getValue())
139                 && (this.getInfo().getCommandType().equals(OnapCommandType.CMD) ||
140                         this.getInfo().getCommandType().equals(OnapCommandType.CATALOG));
141     }
142
143     private Optional<OnapCommandParameter> findParameterByName(String parameterName) {
144         return this.getParameters().stream()
145                 .filter(e -> e.getName().equals(parameterName))
146                 .findFirst();
147     }
148
149     @Override
150     protected void preRun() throws OnapCommandException {
151         Optional<OnapCommandParameter> verifyOpt = this.getParameters().stream()
152                 .filter(e -> "verify".equals(e.getName()))
153                 .findFirst();
154         if(verifyOpt.isPresent()) {
155             shouldVerify = (boolean) verifyOpt.get().getValue();
156         }
157
158         if (shouldVerify) {
159             Optional<OnapCommandParameter> hostUrlParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_HOST_PARAMETER_OPT);
160             Optional<OnapCommandParameter> noAuthParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_NO_AUTH_PARAMETER_OPT);
161
162             if (hostUrlParamOpt.isPresent()) {
163                 OnapCommandParameter onapCommandParameter = hostUrlParamOpt.get();
164                 onapCommandParameter.setValue(
165                         OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_HOST)
166                                 + ":" + OnapCommandConfig.getPropertyValue(OnapCommandHttpConstants.VERIFY_MOCO_PORT));
167             }
168
169             if (noAuthParamOpt.isPresent()) {
170                 OnapCommandParameter onapCommandParameter = noAuthParamOpt.get();
171                 onapCommandParameter.setValue(true);
172             }
173
174
175             Optional<OnapCommandParameter> contextOpt = this.getParameters().stream()
176                     .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
177                     .findFirst();
178
179             if (contextOpt.isPresent()) {
180                 OnapCommandParameter context = contextOpt.get();
181                 Map<String, String> map = (Map<String, String>) context.getValue();
182
183                 mockingEnabled =  map.containsKey(OnapCommandHttpConstants.VERIFY_DISABLE_MOCKING)
184                         && "true".equals(map.get(OnapCommandHttpConstants.VERIFY_DISABLE_MOCKING)) ? false : true;
185
186                 if (mockingEnabled) {
187                     String mockedFile = ((Map<String, String>) context.getValue()).get(OnapCommandConstants.VERIFY_MOCO);
188                     mocoServer = new MocoServer(mockedFile);
189                     mocoServer.start();
190                 }
191             }
192         }
193     }
194
195     @Override
196     protected void postRun() throws OnapCommandException {
197         if (shouldVerify && mockingEnabled) {
198             mocoServer.stop();
199         }
200     }
201
202     @Override
203     protected void run() throws OnapCommandException {
204         try {
205             // For auth/catalog type commands, login and logout logic is not required
206             boolean isAuthRequired = this.isAuthRequired();
207
208             this.authClient = new OnapCommandHttpAuthClient(
209                     this,
210                     this.getResult().isDebug());
211
212             if (isAuthRequired) {
213                 this.authClient.login();
214             }
215
216             this.processRequest();
217
218             if (isAuthRequired) {
219                 this.authClient.logout();
220             }
221
222             if (this.getResult().isDebug() && authClient != null) {
223                 this.getResult().setDebugInfo(this.authClient.getDebugInfo());
224             }
225         } catch (OnapCommandException e) {
226             if (this.getResult().isDebug() && authClient != null) {
227                 this.getResult().setDebugInfo(this.authClient.getDebugInfo());
228             }
229             throw e;
230         }
231     }
232
233     protected void processRequest() throws OnapCommandException {
234
235         HttpInput httpInput = OnapCommandHttpUtils.populateParameters(this.getParametersMap(), this.getInput());
236         httpInput.setUri(this.authClient.getServiceUrl() + httpInput.getUri());
237
238         HttpResult output = this.authClient.run(httpInput);
239
240         this.getResult().setOutput(output);
241         if (!this.getSuccessStatusCodes().contains(output.getStatus())) {
242             throw new OnapCommandExecutionFailed(this.getName(), output.getBody(), output.getStatus());
243         }
244
245         //pre-process result map for spl entries and input parameters
246         for (Entry<String, String> resultMapEntry : this.getResultMap().entrySet()) {
247             String value = OnapCommandUtils.replaceLineForSpecialValues(resultMapEntry.getValue());
248             value = OnapCommandUtils.replaceLineFromInputParameters(value, this.getParametersMap());
249             this.resultMap.put(resultMapEntry.getKey(), value);
250         }
251
252         Map<String, ArrayList<String>> results = OnapCommandHttpUtils.populateOutputs(this.getResultMap(), output);
253         results = OnapCommandUtils.populateOutputsFromInputParameters(results, this.getParametersMap());
254
255         for (OnapCommandResultAttribute attr : this.getResult().getRecords()) {
256             attr.setValues(results.get(attr.getName()));
257         }
258         generateJsonMock(httpInput, output, this.getSchemaName());
259     }
260
261     private void generateJsonMock(HttpInput httpInput, HttpResult httpResult, String schemaName)
262             throws OnapCommandFailedMocoGenerate {
263
264         if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED))) {
265             try {
266                 MockRequest mockRequest = new MockRequest();
267                 mockRequest.setMethod(httpInput.getMethod());
268                 mockRequest.setUri(httpInput.getUri());
269                 mockRequest.setHeaders(httpInput.getReqHeaders());
270                 mockRequest.setJson(httpInput.getBody());
271
272                 MockResponse mockResponse = new MockResponse();
273                 mockResponse.setStatus(httpResult.getStatus());
274                 mockResponse.setJson(httpResult.getBody());
275
276                 MockJsonGenerator.generateMocking(mockRequest, mockResponse,
277                         OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER)
278                         + "/" + schemaName.replace(".yaml", "") + "-moco.json");
279             } catch (IOException error) {
280                 throw new OnapCommandFailedMocoGenerate(schemaName, error);
281             }
282         }
283     }
284 }