4bbfa1d067734ab925050c61bfa7c06e650caf1e
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (C) 2018 IBM.
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.apihandler.common;
25
26
27 import java.io.IOException;
28 import java.security.GeneralSecurityException;
29 import java.util.ArrayList;
30 import java.util.List;
31 import javax.xml.bind.DatatypeConverter;
32 import org.apache.commons.lang3.StringUtils;
33 import org.apache.http.HttpStatus;
34 import org.onap.so.apihandler.camundabeans.CamundaBooleanInput;
35 import org.onap.so.apihandler.camundabeans.CamundaInput;
36 import org.onap.so.apihandler.camundabeans.CamundaIntegerInput;
37 import org.onap.so.apihandler.camundabeans.CamundaRequest;
38 import org.onap.so.apihandler.camundabeans.CamundaResponse;
39 import org.onap.so.apihandler.camundabeans.CamundaVIDRequest;
40 import org.onap.so.apihandlerinfra.exceptions.ApiException;
41 import org.onap.so.apihandlerinfra.exceptions.BPMNFailureException;
42 import org.onap.so.apihandlerinfra.exceptions.ClientConnectionException;
43 import org.onap.so.utils.CryptoUtils;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46 import org.springframework.beans.factory.annotation.Autowired;
47 import org.springframework.core.env.Environment;
48 import org.springframework.http.HttpEntity;
49 import org.springframework.http.HttpHeaders;
50 import org.springframework.http.HttpMethod;
51 import org.springframework.http.ResponseEntity;
52 import org.springframework.stereotype.Component;
53 import org.springframework.web.client.HttpStatusCodeException;
54 import org.springframework.web.client.ResourceAccessException;
55 import org.springframework.web.client.RestTemplate;
56 import com.fasterxml.jackson.databind.ObjectMapper;
57 import com.fasterxml.jackson.databind.SerializationFeature;
58
59 @Component
60 public class CamundaClient {
61     private static Logger logger = LoggerFactory.getLogger(CamundaClient.class);
62     private static final String BASIC = "Basic ";
63
64     @Autowired
65     private RestTemplate restTemplate;
66
67     @Autowired
68     private Environment env;
69
70     @Autowired
71     private ResponseHandler responseHandler;
72
73     public ResponseEntity<String> post(String camundaReqXML, String requestId, String requestTimeout,
74             String schemaVersion, String serviceInstanceId, String action, String orchestrationURI)
75             throws ApiException {
76         String jsonReq = wrapRequest(camundaReqXML, requestId, serviceInstanceId, requestTimeout, schemaVersion,
77                 orchestrationURI);
78         logger.info("Camunda Request Content: {}", jsonReq);
79
80         return post(jsonReq, orchestrationURI);
81     }
82
83     public ResponseEntity<String> post(RequestClientParameter parameterObject, String orchestrationURI)
84             throws ApiException {
85         String jsonReq = wrapVIDRequest(parameterObject.getRequestId(), parameterObject.isBaseVfModule(),
86                 parameterObject.getRecipeTimeout(), parameterObject.getRequestAction(),
87                 parameterObject.getServiceInstanceId(), parameterObject.getPnfCorrelationId(),
88                 parameterObject.getVnfId(), parameterObject.getVfModuleId(), parameterObject.getVolumeGroupId(),
89                 parameterObject.getNetworkId(), parameterObject.getConfigurationId(), parameterObject.getServiceType(),
90                 parameterObject.getVnfType(), parameterObject.getVfModuleType(), parameterObject.getNetworkType(),
91                 parameterObject.getRequestDetails(), parameterObject.getApiVersion(), parameterObject.isaLaCarte(),
92                 parameterObject.getRequestUri(), parameterObject.getRecipeParamXsd(),
93                 parameterObject.getInstanceGroupId(), parameterObject.isGenerateIdsOnly(),
94                 parameterObject.getOperationType());
95
96         return post(jsonReq, orchestrationURI);
97     }
98
99     public ResponseEntity<String> get(String url) throws ApiException {
100         url = env.getRequiredProperty(CommonConstants.CAMUNDA_URL) + url;
101         HttpEntity<?> requestEntity = new HttpEntity<>(setHeaders());
102         try {
103             return restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
104         } catch (HttpStatusCodeException e) {
105             logger.error("Error returned from sending GET request to BPMN", e);
106             throw createBPMNFailureException(e);
107         } catch (ResourceAccessException e) {
108             logger.error("Error sending GET to BPMN", e);
109             ClientConnectionException clientException = new ClientConnectionException.Builder(url,
110                     HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
111             throw clientException;
112         }
113     }
114
115     public ResponseEntity<String> post(String jsonReq, String url) throws ApiException {
116         url = env.getRequiredProperty(CommonConstants.CAMUNDA_URL) + url;
117         HttpEntity<String> request = new HttpEntity<String>(jsonReq, setHeaders());
118         try {
119             return restTemplate.postForEntity(url, request, String.class);
120         } catch (HttpStatusCodeException e) {
121             logger.error("Error returned after sending POST request to BPMN", e);
122             throw createBPMNFailureException(e);
123         } catch (ResourceAccessException e) {
124             logger.error("Error sending POST to BPMN", e);
125             ClientConnectionException clientException = new ClientConnectionException.Builder(url,
126                     HttpStatus.SC_BAD_GATEWAY, ErrorNumbers.SVC_NO_SERVER_RESOURCES).build();
127             throw clientException;
128         }
129     }
130
131     protected String wrapRequest(String reqXML, String requestId, String serviceInstanceId, String requestTimeout,
132             String schemaVersion, String url) {
133         String jsonReq = null;
134         try {
135             CamundaRequest camundaRequest = new CamundaRequest();
136             CamundaInput camundaInput = new CamundaInput();
137             CamundaInput host = new CamundaInput();
138             CamundaInput schema = new CamundaInput();
139             CamundaInput reqid = new CamundaInput();
140             CamundaInput svcid = new CamundaInput();
141             CamundaInput timeout = new CamundaInput();
142             camundaInput.setValue(StringUtils.defaultString(reqXML));
143             host.setValue(CommonConstants.CAMUNDA_URL);
144             schema.setValue(StringUtils.defaultString(schemaVersion));
145             reqid.setValue(requestId);
146             svcid.setValue(serviceInstanceId);
147             timeout.setValue(StringUtils.defaultString(requestTimeout));
148             camundaRequest.setServiceInput(camundaInput);
149             camundaRequest.setHost(host);
150             camundaRequest.setReqid(reqid);
151             camundaRequest.setSvcid(svcid);
152             camundaRequest.setSchema(schema);
153             camundaRequest.setTimeout(timeout);
154             ObjectMapper mapper = new ObjectMapper();
155
156             mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
157
158             jsonReq = mapper.writeValueAsString(camundaRequest);
159             logger.trace("request body is {}", jsonReq);
160         } catch (Exception e) {
161             logger.error("Error in APIH Wrap request", e);
162         }
163         return jsonReq;
164     }
165
166
167     protected String wrapVIDRequest(String requestId, boolean isBaseVfModule, int recipeTimeout, String requestAction,
168             String serviceInstanceId, String pnfCorrelationId, String vnfId, String vfModuleId, String volumeGroupId,
169             String networkId, String configurationId, String serviceType, String vnfType, String vfModuleType,
170             String networkType, String requestDetails, String apiVersion, boolean aLaCarte, String requestUri,
171             String paramXsd, String instanceGroupId, boolean generateIdsOnly, String operationType) {
172         String jsonReq = null;
173
174         try {
175             CamundaVIDRequest camundaRequest = new CamundaVIDRequest();
176             CamundaInput serviceInput = new CamundaInput();
177             CamundaInput host = new CamundaInput();
178             CamundaInput requestIdInput = new CamundaInput();
179             CamundaBooleanInput isBaseVfModuleInput = new CamundaBooleanInput();
180             CamundaIntegerInput recipeTimeoutInput = new CamundaIntegerInput();
181             CamundaInput requestActionInput = new CamundaInput();
182             CamundaInput serviceInstanceIdInput = new CamundaInput();
183             CamundaInput operationTypeInput = new CamundaInput();
184             CamundaInput pnfCorrelationIdInput = new CamundaInput();
185             CamundaInput vnfIdInput = new CamundaInput();
186             CamundaInput vfModuleIdInput = new CamundaInput();
187             CamundaInput volumeGroupIdInput = new CamundaInput();
188             CamundaInput networkIdInput = new CamundaInput();
189             CamundaInput configurationIdInput = new CamundaInput();
190             CamundaInput serviceTypeInput = new CamundaInput();
191             CamundaInput vnfTypeInput = new CamundaInput();
192             CamundaInput vfModuleTypeInput = new CamundaInput();
193             CamundaInput networkTypeInput = new CamundaInput();
194             CamundaBooleanInput aLaCarteInput = new CamundaBooleanInput();
195             CamundaInput apiVersionInput = new CamundaInput();
196             CamundaInput requestUriInput = new CamundaInput();
197             CamundaInput recipeParamsInput = new CamundaInput();
198             CamundaInput instanceGroupIdInput = new CamundaInput();
199             CamundaBooleanInput generateIds = new CamundaBooleanInput();
200
201             operationTypeInput.setValue(StringUtils.defaultString(operationType));
202             requestIdInput.setValue(StringUtils.defaultString(requestId));
203             isBaseVfModuleInput.setValue(isBaseVfModule);
204             recipeTimeoutInput.setValue(recipeTimeout);
205             requestActionInput.setValue(StringUtils.defaultString(requestAction));
206             serviceInstanceIdInput.setValue(StringUtils.defaultString(serviceInstanceId));
207             pnfCorrelationIdInput.setValue(StringUtils.defaultString(pnfCorrelationId));
208             vnfIdInput.setValue(StringUtils.defaultString(vnfId));
209             vfModuleIdInput.setValue(StringUtils.defaultString(vfModuleId));
210             volumeGroupIdInput.setValue(StringUtils.defaultString(volumeGroupId));
211             networkIdInput.setValue(StringUtils.defaultString(networkId));
212             configurationIdInput.setValue(StringUtils.defaultString(configurationId));
213             serviceTypeInput.setValue(StringUtils.defaultString(serviceType));
214             vnfTypeInput.setValue(StringUtils.defaultString(vnfType));
215             vfModuleTypeInput.setValue(StringUtils.defaultString(vfModuleType));
216             networkTypeInput.setValue(StringUtils.defaultString(networkType));
217             aLaCarteInput.setValue(aLaCarte);
218             apiVersionInput.setValue(StringUtils.defaultString(apiVersion));
219             requestUriInput.setValue(StringUtils.defaultString(requestUri));
220             recipeParamsInput.setValue(paramXsd);
221             instanceGroupIdInput.setValue(StringUtils.defaultString(instanceGroupId));
222             generateIds.setValue(generateIdsOnly);
223
224             serviceInput.setValue(requestDetails);
225             camundaRequest.setServiceInput(serviceInput);
226             camundaRequest.setHost(host);
227             camundaRequest.setRequestId(requestIdInput);
228             camundaRequest.setMsoRequestId(requestIdInput);
229             camundaRequest.setIsBaseVfModule(isBaseVfModuleInput);
230             camundaRequest.setRecipeTimeout(recipeTimeoutInput);
231             camundaRequest.setRequestAction(requestActionInput);
232             camundaRequest.setServiceInstanceId(serviceInstanceIdInput);
233             camundaRequest.setOperationType(operationTypeInput);
234             camundaRequest.setPnfCorrelationId(pnfCorrelationIdInput);
235             camundaRequest.setVnfId(vnfIdInput);
236             camundaRequest.setVfModuleId(vfModuleIdInput);
237             camundaRequest.setVolumeGroupId(volumeGroupIdInput);
238             camundaRequest.setNetworkId(networkIdInput);
239             camundaRequest.setConfigurationId(configurationIdInput);
240             camundaRequest.setServiceType(serviceTypeInput);
241             camundaRequest.setVnfType(vnfTypeInput);
242             camundaRequest.setVfModuleType(vfModuleTypeInput);
243             camundaRequest.setNetworkType(networkTypeInput);
244             camundaRequest.setaLaCarte(aLaCarteInput);
245             camundaRequest.setApiVersion(apiVersionInput);
246             camundaRequest.setRequestUri(requestUriInput);
247             camundaRequest.setRecipeParams(recipeParamsInput);
248             camundaRequest.setInstanceGroupId(instanceGroupIdInput);
249             camundaRequest.setGenerateIds(generateIds);
250
251             ObjectMapper mapper = new ObjectMapper();
252             mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
253
254             jsonReq = mapper.writeValueAsString(camundaRequest);
255             logger.trace("request body is {}", jsonReq);
256         } catch (Exception e) {
257             logger.error("Error in wrapVIDRequest", e);
258         }
259         return jsonReq;
260     }
261
262     protected HttpHeaders setHeaders() {
263         HttpHeaders headers = new HttpHeaders();
264         List<org.springframework.http.MediaType> acceptableMediaTypes = new ArrayList<>();
265         acceptableMediaTypes.add(org.springframework.http.MediaType.APPLICATION_JSON);
266         headers.setAccept(acceptableMediaTypes);
267         headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
268         headers.add(HttpHeaders.AUTHORIZATION, addAuthorizationHeader(env.getRequiredProperty("mso.camundaAuth"),
269                 env.getRequiredProperty("mso.msoKey")));
270         return headers;
271     }
272
273     protected String addAuthorizationHeader(String auth, String msoKey) {
274         String basicAuth = null;
275         try {
276             String userCredentials = CryptoUtils.decrypt(auth, msoKey);
277             if (userCredentials != null) {
278                 basicAuth = BASIC + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
279             }
280         } catch (GeneralSecurityException e) {
281             logger.error("Security exception", e);
282         }
283         return basicAuth;
284     }
285
286     protected BPMNFailureException createBPMNFailureException(HttpStatusCodeException e) {
287         ObjectMapper mapper = new ObjectMapper();
288         String responseText = null;
289         String message = null;
290         try {
291             CamundaResponse response = mapper.readValue(e.getResponseBodyAsString(), CamundaResponse.class);
292             responseText = response.getResponse();
293         } catch (IOException ex) {
294             responseText = e.getResponseBodyAsString();
295         }
296         message = String.valueOf(e.getStatusCode());
297         if (responseText != null && !responseText.isEmpty()) {
298             message = message + " " + responseText;
299         }
300         BPMNFailureException bpmnException =
301                 new BPMNFailureException.Builder(message, responseHandler.setStatus(e.getStatusCode().value()),
302                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, e.getStatusCode()).build();
303         return bpmnException;
304     }
305
306 }