Merge "Reorder modifiers"
[so.git] / adapters / mso-sdnc-adapter / src / main / java / org / openecomp / mso / 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 package org.openecomp.mso.adapters.sdnc.sdncrest;
22
23 import org.openecomp.mso.adapters.sdnc.impl.Constants;
24 import org.openecomp.mso.logger.MessageEnum;
25 import org.openecomp.mso.logger.MsoAlarmLogger;
26 import org.openecomp.mso.logger.MsoLogger;
27 import org.apache.http.HttpResponse;
28 import org.apache.http.client.HttpClient;
29 import org.apache.http.client.config.RequestConfig;
30 import org.apache.http.client.methods.HttpPost;
31 import org.apache.http.entity.ContentType;
32 import org.apache.http.entity.StringEntity;
33 import org.apache.http.impl.client.HttpClientBuilder;
34 import org.apache.http.util.EntityUtils;
35
36 import javax.xml.bind.DatatypeConverter;
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 message the JSON content
52          * @return true if the message was consumed successfully by the endpoint
53          */
54         public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
55                 LOGGER.debug(getClass().getSimpleName() + ".send("
56                         + "workflowMessageUrl=" + workflowMessageUrl
57                         + " messageType=" + messageType
58                         + " correlator=" + correlator
59                         + " message=" + message
60                         + ")");
61
62                 while (workflowMessageUrl.endsWith("/")) {
63                         workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
64                 }
65
66                 String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType)
67                         + "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator);
68
69                 return send(endpoint, message);
70         }
71
72         /**
73          * Sends a message to the BPMN workflow message service. The specified URL
74          * must have the message type and correlator already embedded in it.
75          * @param url the endpoint URL
76          * @param message the JSON content
77          * @return true if the message was consumed successfully by the endpoint
78          */
79         public boolean send(String url, String message) {
80                 LOGGER.debug(getClass().getSimpleName() + ".send("
81                         + "url=" + url
82                         + " message=" + message
83                         + ")");
84
85                 LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, "Camunda", "");
86
87                 HttpPost method = null;
88                 HttpResponse httpResponse = null;
89
90                 try {
91                         // TODO: configurable timeout?
92                         int timeout = 60 * 1000;
93
94                         RequestConfig requestConfig = RequestConfig.custom()
95                                 .setSocketTimeout(timeout)
96                                 .setConnectTimeout(timeout)
97                                 .setConnectionRequestTimeout(timeout)
98                                 .build();
99
100                         HttpClient client = HttpClientBuilder.create().build();
101                         method = new HttpPost(url);
102                         method.setConfig(requestConfig);
103
104                         if (message != null) {
105                                 method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
106                         }
107
108                         boolean error = false;
109
110                         try {
111                                 // AAF Integration, disabled for now due to the constrains from other party
112                                 // String userCredentials = CredentialConstants.getDecryptedCredential(Constants.DEFAULT_BPEL_AUTH);
113                                 // Once AAF enabled, the credential shall be get by triggering the CredentialConstants.getDecryptedCredential -- remove line
114                                 String  userCredentials = SDNCAdapterProperties.getEncryptedProperty(Constants.BPEL_AUTH_PROP,
115                                         Constants.DEFAULT_BPEL_AUTH, Constants.ENCRYPTION_KEY);
116                                 String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
117                                 method.setHeader("Authorization", authorization);
118                         } catch (Exception e) {
119                                 LOGGER.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError,
120                                         "Unable to set authorization in callback request", e);
121                                 ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL,
122                                         "Unable to set authorization in callback request: " + e.getMessage());
123                                 error = true;
124                         }
125
126                         if (!error) {
127                                 httpResponse = client.execute(method);
128
129                                 @SuppressWarnings("unused")
130                                 String responseContent = null;
131
132                                 if (httpResponse.getEntity() != null) {
133                                         responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
134                                 }
135
136                                 if (httpResponse.getStatusLine().getStatusCode() >= 300) {
137                                         String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
138                                         LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, msg);
139                                         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, msg);
140                                 }
141                         }
142                         return true;
143                 } catch (Exception e) {
144                         LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError,
145                                 "Error sending callback request", e);
146                         ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL,
147                                 "Error sending callback request: " + e.getMessage());
148                         return false;
149                 } finally {
150                         if (httpResponse != null) {
151                                 try {
152                                         EntityUtils.consume(httpResponse.getEntity());
153                                         httpResponse = null;
154                                 } catch (Exception e) {
155                                         LOGGER.debug("Exception:", e);
156                                 }
157                         }
158
159                         if (method != null) {
160                                 try {
161                                         method.reset();
162                                 } catch (Exception e) {
163                                         LOGGER.debug("Exception:", e);
164                                 }
165                         }
166
167                         LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, "Camunda", "");
168                 }
169         }
170 }