Bugfixes for December 2018
[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  * ================================================================================
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.adapters.sdnc.sdncrest;
25
26 import javax.xml.bind.DatatypeConverter;
27
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.HttpClient;
30 import org.apache.http.client.config.RequestConfig;
31 import org.apache.http.client.methods.HttpPost;
32 import org.apache.http.entity.ContentType;
33 import org.apache.http.entity.StringEntity;
34 import org.apache.http.impl.client.HttpClientBuilder;
35 import org.apache.http.util.EntityUtils;
36 import org.onap.logging.ref.slf4j.ONAPLogConstants;
37 import org.onap.so.adapters.sdnc.impl.Constants;
38 import org.onap.so.logger.MessageEnum;
39
40 import org.onap.so.logger.MsoLogger;
41 import org.springframework.beans.factory.annotation.Autowired;
42 import org.springframework.stereotype.Component;
43 import org.onap.so.utils.CryptoUtils;
44 import org.slf4j.MDC;
45 import org.springframework.core.env.Environment;
46
47 /**
48  * Sends asynchronous messages to the BPMN WorkflowMessage service.
49  */
50 @Component
51 public class BPRestCallback {
52         private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA,BPRestCallback.class);
53
54         private static final String CAMUNDA="Camunda";
55         private static final String MSO_INTERNAL_ERROR="MsoInternalError";
56         @Autowired
57         private Environment env;
58
59         /**
60          * Sends a message to the BPMN workflow message service. The URL path is
61          * constructed using the specified message type and correlator.
62          * @param workflowMessageUrl the base BPMN WorkflowMessage URL
63          * @param messageType the message type
64          * @param correlator the message correlator
65          * @param message the JSON content
66          * @return true if the message was consumed successfully by the endpoint
67          */
68         public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
69                 LOGGER.debug(getClass().getSimpleName() + ".send("
70                         + "workflowMessageUrl=" + workflowMessageUrl
71                         + " messageType=" + messageType
72                         + " correlator=" + correlator
73                         + " message=" + message
74                         + ")");
75
76                 while (workflowMessageUrl.endsWith("/")) {
77                         workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
78                 }
79
80                 String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType)
81                         + "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator);
82
83                 return send(endpoint, message);
84         }
85
86         /**
87          * Sends a message to the BPMN workflow message service. The specified URL
88          * must have the message type and correlator already embedded in it.
89          * @param url the endpoint URL
90          * @param message the JSON content
91          * @return true if the message was consumed successfully by the endpoint
92          */
93         public boolean send(String url, String message) {
94                 LOGGER.debug(getClass().getSimpleName() + ".send("
95                         + "url=" + url
96                         + " message=" + message
97                         + ")");
98
99                 LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, CAMUNDA, "");
100
101                 HttpPost method = null;
102                 HttpResponse httpResponse = null;
103
104                 try {           
105                         int timeout = 60 * 1000;
106
107                         RequestConfig requestConfig = RequestConfig.custom()
108                                 .setSocketTimeout(timeout)
109                                 .setConnectTimeout(timeout)
110                                 .setConnectionRequestTimeout(timeout)
111                                 .build();
112
113                         HttpClient client = HttpClientBuilder.create().build();
114                         method = new HttpPost(url);
115                         method.setConfig(requestConfig);
116
117                         if (message != null) {
118                                 method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
119                         }
120
121                         boolean error = false;
122
123                         try {   
124                                 String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
125                                         env.getProperty(Constants.ENCRYPTION_KEY_PROP));
126                                 String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
127                                 method.setHeader("Authorization", authorization);
128                                 method.setHeader(ONAPLogConstants.Headers.REQUEST_ID,MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
129                                 method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID,MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
130                                 method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME,"SO-SDNCAdapter");
131                         } catch (Exception e) {
132                                 LOGGER.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError,
133                                         "Unable to set authorization in callback request", e);                  
134                                 error = true;
135                         }
136
137                         if (!error) {
138                                 httpResponse = client.execute(method);
139
140                                 @SuppressWarnings("unused")
141                                 String responseContent = null;
142
143                                 if (httpResponse.getEntity() != null) {
144                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
145                                 }
146
147                                 if (httpResponse.getStatusLine().getStatusCode() >= 300) {
148                                         String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
149                                         LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError, msg);
150
151                                 }
152                         }
153                         return true;
154                 } catch (Exception e) {
155                         LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, CAMUNDA, "", MsoLogger.ErrorCode.BusinessProcesssError,
156                                 "Error sending callback request", e);                   
157                         return false;
158                 } finally {
159                         if (httpResponse != null) {
160                                 try {
161                                         EntityUtils.consume(httpResponse.getEntity());
162                                         httpResponse = null;
163                                 } catch (Exception e) {
164                                         LOGGER.debug("Exception:", e);
165                                 }
166                         }
167
168                         if (method != null) {
169                                 try {
170                                         method.reset();
171                                 } catch (Exception e) {
172                                         LOGGER.debug("Exception:", e);
173                                 }
174                         }
175                         LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, CAMUNDA, "","");
176                 }
177         }
178 }