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