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