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