Merge "Reorder modifiers"
[so.git] / adapters / mso-workflow-message-adapter / src / main / java / org / openecomp / mso / adapters / workflowmessage / 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 package org.openecomp.mso.adapters.workflowmessage;
22
23 import javax.xml.bind.DatatypeConverter;
24
25 import org.apache.http.HttpResponse;
26 import org.apache.http.client.HttpClient;
27 import org.apache.http.client.config.RequestConfig;
28 import org.apache.http.client.methods.HttpPost;
29 import org.apache.http.entity.ContentType;
30 import org.apache.http.entity.StringEntity;
31 import org.apache.http.impl.client.HttpClientBuilder;
32 import org.apache.http.util.EntityUtils;
33
34 import org.openecomp.mso.logger.MessageEnum;
35 import org.openecomp.mso.logger.MsoAlarmLogger;
36 import org.openecomp.mso.logger.MsoLogger;
37
38 /**
39  * Sends asynchronous messages to the BPMN WorkflowMessage service.
40  */
41 public class BPRestCallback {
42         private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
43         private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();
44
45         /**
46          * Sends a message to the BPMN workflow message service. The URL path is
47          * constructed using the specified message type and correlator.
48          * @param workflowMessageUrl the base BPMN WorkflowMessage URL
49          * @param messageType the message type
50          * @param correlator the message correlator
51          * @param contentType the value for the HTTP Content-Type header (possibly null)
52          * @param message the content (possibly null)
53          * @return true if the message was consumed successfully by the endpoint
54          */
55         public boolean send(String workflowMessageUrl, String messageType,
56                         String correlator, ContentType contentType, String message) {
57                 LOGGER.debug(getClass().getSimpleName() + ".send("
58                         + "workflowMessageUrl=" + workflowMessageUrl
59                         + " messageType=" + messageType
60                         + " correlator=" + correlator
61                         + " contentType=" + contentType
62                         + " message=" + message
63                         + ")");
64
65                 while (workflowMessageUrl.endsWith("/")) {
66                         workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
67                 }
68
69                 String endpoint = workflowMessageUrl + "/" + WMAdapterUtils.encodeURLPathSegment(messageType)
70                         + "/" + WMAdapterUtils.encodeURLPathSegment(correlator);
71
72                 return send(endpoint, contentType, message);
73         }
74
75         /**
76          * Sends a message to the BPMN workflow message service. The specified URL
77          * must have the message type and correlator already embedded in it.
78          * @param url the endpoint URL
79          * @param message the content (possibly null)
80          * @param contentType the value for the HTTP Content-Type header (possibly null)
81          * @return true if the message was consumed successfully by the endpoint
82          */
83         public boolean send(String url, ContentType contentType, String message) {
84                 LOGGER.debug(getClass().getSimpleName() + ".send("
85                         + "url=" + url
86                         + " contentType=" + contentType
87                         + " message=" + message
88                         + ")");
89
90                 LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, "Camunda", "");
91
92                 HttpPost method = null;
93                 HttpResponse httpResponse = null;
94
95                 try {
96                         // TODO: configurable timeout?
97                         int timeout = 60 * 1000;
98
99                         RequestConfig requestConfig = RequestConfig.custom()
100                                 .setSocketTimeout(timeout)
101                                 .setConnectTimeout(timeout)
102                                 .setConnectionRequestTimeout(timeout)
103                                 .build();
104
105                         HttpClient client = HttpClientBuilder.create().build();
106                         method = new HttpPost(url);
107                         method.setConfig(requestConfig);
108
109                         if (message != null) {
110                                 method.setEntity(new StringEntity(message, contentType));
111                         }
112
113                         boolean error = false;
114
115                         try {
116                                 // AAF Integration, disabled for now due to the constrains from other party
117                                 // String userCredentials = CredentialConstants.getDecryptedCredential(WMAdapterConstants.DEFAULT_BPEL_AUTH);
118                                 // Once AAF enabled, the credential shall be get by triggering the CredentialConstants.getDecryptedCredential -- remove line
119                                 String  userCredentials = WMAdapterProperties.getEncryptedProperty(WMAdapterConstants.BPEL_AUTH_PROP,
120                                         WMAdapterConstants.DEFAULT_BPEL_AUTH, WMAdapterConstants.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;
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                         }
148
149                         return true;
150                 } catch (Exception e) {
151                         LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError,
152                                 "Error sending callback request", e);
153                         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL,
154                                 "Error sending callback request: " + e.getMessage());
155                         return false;
156                 } finally {
157                         if (httpResponse != null) {
158                                 try {
159                                         EntityUtils.consume(httpResponse.getEntity());
160                                         httpResponse = null;
161                                 } catch (Exception e) {
162                                         LOGGER.debug("Exception :",e);
163                                 }
164                         }
165
166                         if (method != null) {
167                                 try {
168                                         method.reset();
169                                         method = null;
170                                 } catch (Exception e) {
171                                         LOGGER.debug("Exception :",e);
172                                 }
173                         }
174
175                         LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, "Camunda", "");
176                 }
177         }
178 }