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