2 * Copyright 2017 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.cli.fw.http.cmd;
19 import java.io.IOException;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.List;
24 import java.util.Map.Entry;
25 import java.util.Optional;
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;
55 @OnapCommandSchema(type = OnapCommandHttpConstants.HTTP_SCHEMA_PROFILE)
56 public class OnapHttpCommand extends OnapCommand {
58 private HttpInput input = new HttpInput();
60 private HttpResult output = new HttpResult();
62 private List<Integer> successStatusCodes = new ArrayList<>();
64 private Map<String, String> resultMap = new HashMap<>();
66 protected OnapCommandHttpAuthClient authClient;
68 private OnapCommandHttpService oclipService = new OnapCommandHttpService();
70 private MocoServer mocoServer = null;
72 boolean shouldVerify = false;
74 boolean mockingEnabled;
76 public OnapHttpCommand() {
77 super.addDefaultSchemas(OnapCommandHttpConstants.DEFAULT_PARAMETER_HTTP_FILE_NAME);
80 public void setInput(HttpInput input) {
85 public String getSchemaVersion() {
86 return OnapCommandConstants.OPEN_CLI_SCHEMA_VERSION_VALUE_1_0;
89 public void setSuccessStatusCodes(List<Integer> successStatusCodes) {
90 this.successStatusCodes = successStatusCodes;
93 public void setResultMap(Map<String, String> resultMap) {
94 this.resultMap = resultMap;
97 public HttpInput getInput() {
101 public List<Integer> getSuccessStatusCodes() {
102 return successStatusCodes;
105 public Map<String, String> getResultMap() {
110 * Oclip service, this command uses to execute it.
112 public OnapCommandHttpService getService() {
113 return this.oclipService;
116 public void setService(OnapCommandHttpService service) {
117 this.oclipService = service;
121 protected List<String> initializeProfileSchema(Map<String, ?> schemaMap, boolean validate) throws OnapCommandException {
122 return OnapCommandSchemaHttpLoader.parseHttpSchema(this, schemaMap, validate);
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);
131 if (this.getParametersMap().containsKey(OnapCommandHttpConstants.DEAFULT_PARAMETER_PASSWORD)) {
132 this.getParametersMap().get(OnapCommandHttpConstants.DEAFULT_PARAMETER_PASSWORD).setOptional(true);
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));
146 private Optional<OnapCommandParameter> findParameterByName(String parameterName) {
147 return this.getParameters().stream()
148 .filter(e -> e.getName().equals(parameterName))
153 protected void preRun() throws OnapCommandException {
154 Optional<OnapCommandParameter> verifyOpt = this.getParameters().stream()
155 .filter(e -> "verify".equals(e.getName()))
157 if(verifyOpt.isPresent()) {
158 shouldVerify = (boolean) verifyOpt.get().getValue();
162 Optional<OnapCommandParameter> hostUrlParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_HOST_PARAMETER_OPT);
163 Optional<OnapCommandParameter> noAuthParamOpt = findParameterByName(OnapCommandHttpConstants.VERIFY_NO_AUTH_PARAMETER_OPT);
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));
172 if (noAuthParamOpt.isPresent()) {
173 OnapCommandParameter onapCommandParameter = noAuthParamOpt.get();
174 onapCommandParameter.setValue(true);
178 Optional<OnapCommandParameter> contextOpt = this.getParameters().stream()
179 .filter(e -> e.getName().equals(OnapCommandConstants.VERIFY_CONTEXT_PARAM))
182 if (contextOpt.isPresent()) {
183 OnapCommandParameter context = contextOpt.get();
184 Map<String, String> map = (Map<String, String>) context.getValue();
186 mockingEnabled = !(map.containsKey(OnapCommandHttpConstants.VERIFY_DISABLE_MOCKING)
187 && "true".equals(map.get(OnapCommandHttpConstants.VERIFY_DISABLE_MOCKING)));
189 if (mockingEnabled) {
190 String mockedFile = ((Map<String, String>) context.getValue()).get(OnapCommandConstants.VERIFY_MOCO);
191 mocoServer = new MocoServer(mockedFile);
199 protected void postRun() throws OnapCommandException {
200 if (mocoServer != null) {
206 protected void run() throws OnapCommandException {
207 this.authClient = new OnapCommandHttpAuthClient(this);
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();
216 this.processRequest();
218 if (isAuthRequired) {
219 this.authClient.logout();
221 } catch (OnapCommandException e) {
224 this.getResult().setDebugInfo(this.input.toString() + "\n" + this.output.toString());
228 protected void processRequest() throws OnapCommandException {
230 HttpInput httpInput = OnapCommandHttpUtils.populateParameters(this.getParametersMap(), this.getInput());
231 if (!httpInput.getUri().startsWith("http")) {
232 httpInput.setUri(this.authClient.getServiceUrl() + httpInput.getUri());
235 this.setInput(httpInput);
237 if (this.getExecutionContext() != null) {
238 OnapCommandExecutionStore.getStore().storeExectutionDebug(this.getExecutionContext(), this.getInput().toString());
240 this.getResult().setDebugInfo(this.getInput().toString());
242 this.output = this.authClient.run(this.getInput());
244 this.getResult().setOutput(output);
245 if (!this.getSuccessStatusCodes().contains(output.getStatus())) {
246 throw new OnapCommandExecutionFailed(this.getName(), output.getBody(), output.getStatus());
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);
256 Map<String, List<String>> results = OnapCommandHttpUtils.populateOutputs(this.getResultMap(), output);
257 //results = OnapCommandUtils.populateOutputsFromInputParameters(results, this.getParametersMap());
259 for (OnapCommandResultAttribute attr : this.getResult().getRecords()) {
260 attr.setValues(results.get(attr.getName()));
264 generateJsonMock(this.getInput(), output, this.getSchemaName());
265 } catch (OnapCommandFailedMocoGenerate e) {
270 private void generateJsonMock(HttpInput httpInput, HttpResult httpResult, String schemaName)
271 throws OnapCommandFailedMocoGenerate {
273 if (Boolean.parseBoolean(OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_ENABLED))) {
275 MockRequest mockRequest = new MockRequest();
276 mockRequest.setMethod(httpInput.getMethod());
277 mockRequest.setUri(httpInput.getUri());
278 mockRequest.setHeaders(httpInput.getReqHeaders());
279 mockRequest.setJson(httpInput.getBody());
281 MockResponse mockResponse = new MockResponse();
282 mockResponse.setStatus(httpResult.getStatus());
283 mockResponse.setJson(httpResult.getBody());
285 MockJsonGenerator.generateMocking(mockRequest, mockResponse,
286 OnapCommandConfig.getPropertyValue(OnapCommandConstants.SAMPLE_GEN_TARGET_FOLDER)
287 + "/" + schemaName.replace(".yaml", "") + "-moco.json");
288 } catch (IOException error) {
289 throw new OnapCommandFailedMocoGenerate(schemaName, error);