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