6a66770d29cf33313709533faf4f29f8ecb31466
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / onap / so / adapters / sdnc / sdncrest / BPRestCallback.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (C) 2018 IBM.
9  * Modifications Copyright (c) 2019 Samsung
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.so.adapters.sdnc.sdncrest;
26
27 import javax.xml.bind.DatatypeConverter;
28
29 import org.apache.http.HttpResponse;
30 import org.apache.http.client.HttpClient;
31 import org.apache.http.client.config.RequestConfig;
32 import org.apache.http.client.methods.HttpPost;
33 import org.apache.http.entity.ContentType;
34 import org.apache.http.entity.StringEntity;
35 import org.apache.http.impl.client.HttpClientBuilder;
36 import org.apache.http.util.EntityUtils;
37 import org.onap.logging.ref.slf4j.ONAPLogConstants;
38 import org.onap.so.adapters.sdnc.impl.Constants;
39 import org.onap.so.logger.MessageEnum;
40
41 import org.onap.so.logger.MsoLogger;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.stereotype.Component;
46 import org.onap.so.utils.CryptoUtils;
47 import org.slf4j.MDC;
48 import org.springframework.core.env.Environment;
49
50 /**
51  * Sends asynchronous messages to the BPMN WorkflowMessage service.
52  */
53 @Component
54 public class BPRestCallback {
55         private static final Logger logger = LoggerFactory.getLogger(BPRestCallback.class);
56
57         private static final String CAMUNDA="Camunda";
58         private static final String MSO_INTERNAL_ERROR="MsoInternalError";
59         @Autowired
60         private Environment env;
61
62         /**
63          * Sends a message to the BPMN workflow message service. The URL path is
64          * constructed using the specified message type and correlator.
65          * @param workflowMessageUrl the base BPMN WorkflowMessage URL
66          * @param messageType the message type
67          * @param correlator the message correlator
68          * @param message the JSON content
69          * @return true if the message was consumed successfully by the endpoint
70          */
71         public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
72                 logger.debug(getClass().getSimpleName() + ".send("
73                         + "workflowMessageUrl=" + workflowMessageUrl
74                         + " messageType=" + messageType
75                         + " correlator=" + correlator
76                         + " message=" + message
77                         + ")");
78
79                 while (workflowMessageUrl.endsWith("/")) {
80                         workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
81                 }
82
83                 String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType)
84                         + "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator);
85
86                 return send(endpoint, message);
87         }
88
89         /**
90          * Sends a message to the BPMN workflow message service. The specified URL
91          * must have the message type and correlator already embedded in it.
92          * @param url the endpoint URL
93          * @param message the JSON content
94          * @return true if the message was consumed successfully by the endpoint
95          */
96         public boolean send(String url, String message) {
97                 logger.debug(getClass().getSimpleName() + ".send("
98                         + "url=" + url
99                         + " message=" + message
100                         + ")");
101
102                 logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message,
103                         CAMUNDA);
104
105                 HttpPost method = null;
106                 HttpResponse httpResponse = null;
107
108                 try {           
109                         int timeout = 60 * 1000;
110
111                         RequestConfig requestConfig = RequestConfig.custom()
112                                 .setSocketTimeout(timeout)
113                                 .setConnectTimeout(timeout)
114                                 .setConnectionRequestTimeout(timeout)
115                                 .build();
116
117                         HttpClient client = HttpClientBuilder.create().build();
118                         method = new HttpPost(url);
119                         method.setConfig(requestConfig);
120
121                         if (message != null) {
122                                 method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
123                         }
124
125                         boolean error = false;
126
127                         try {   
128                                 String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
129                                         env.getProperty(Constants.ENCRYPTION_KEY_PROP));
130                                 String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
131                                 method.setHeader("Authorization", authorization);
132                                 method.setHeader(ONAPLogConstants.Headers.REQUEST_ID,MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
133                                 method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID,MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
134                                 method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME,"SO-SDNCAdapter");
135                         } catch (Exception e) {
136                                 logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
137                                         MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request", e);
138                                 error = true;
139                         }
140
141                         if (!error) {
142                                 httpResponse = client.execute(method);
143
144                                 @SuppressWarnings("unused")
145                                 String responseContent = null;
146
147                                 if (httpResponse.getEntity() != null) {
148                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
149                                 }
150
151                                 if (httpResponse.getStatusLine().getStatusCode() >= 300) {
152                                         String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
153                                         logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA, MsoLogger.ErrorCode
154                                                 .BusinessProcesssError.getValue(), msg);
155
156                                 }
157                         }
158                         return true;
159                 } catch (Exception e) {
160                         logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
161                                 MsoLogger.ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e);
162                         return false;
163                 } finally {
164                         if (httpResponse != null) {
165                                 try {
166                                         EntityUtils.consume(httpResponse.getEntity());
167                                         httpResponse = null;
168                                 } catch (Exception e) {
169                                         logger.debug("Exception:", e);
170                                 }
171                         }
172
173                         if (method != null) {
174                                 try {
175                                         method.reset();
176                                 } catch (Exception e) {
177                                         logger.debug("Exception:", e);
178                                 }
179                         }
180                         logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA);
181                 }
182         }
183 }