Replaced all tabs with spaces in java and pom.xml
[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  * Modifications Copyright (c) 2019 Samsung
10  * ================================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.so.adapters.sdnc.sdncrest;
26
27 import javax.xml.bind.DatatypeConverter;
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.logging.ref.slf4j.ONAPLogConstants;
37 import org.onap.so.adapters.sdnc.impl.Constants;
38 import org.onap.so.logger.ErrorCode;
39 import org.onap.so.logger.MessageEnum;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.stereotype.Component;
44 import org.onap.so.utils.CryptoUtils;
45 import org.slf4j.MDC;
46 import org.springframework.core.env.Environment;
47
48 /**
49  * Sends asynchronous messages to the BPMN WorkflowMessage service.
50  */
51 @Component
52 public class BPRestCallback {
53     private static final Logger logger = LoggerFactory.getLogger(BPRestCallback.class);
54
55     private static final String CAMUNDA = "Camunda";
56     private static final String MSO_INTERNAL_ERROR = "MsoInternalError";
57     @Autowired
58     private Environment env;
59
60     /**
61      * Sends a message to the BPMN workflow message service. The URL path is constructed using the specified message
62      * type and correlator.
63      * 
64      * @param workflowMessageUrl the base BPMN WorkflowMessage URL
65      * @param messageType the message type
66      * @param correlator the message correlator
67      * @param message the JSON content
68      * @return true if the message was consumed successfully by the endpoint
69      */
70     public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
71         logger.debug(getClass().getSimpleName() + ".send(" + "workflowMessageUrl=" + workflowMessageUrl
72                 + " messageType=" + messageType + " correlator=" + correlator + " message=" + message + ")");
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 must have the message type and correlator
86      * already embedded in it.
87      * 
88      * @param url the endpoint URL
89      * @param message the JSON content
90      * @return true if the message was consumed successfully by the endpoint
91      */
92     public boolean send(String url, String message) {
93         logger.debug(getClass().getSimpleName() + ".send(" + "url=" + url + " message=" + message + ")");
94
95         logger.info("{} {} {}", MessageEnum.RA_CALLBACK_BPEL.toString(), message == null ? "[no content]" : message,
96                 CAMUNDA);
97
98         HttpPost method = null;
99         HttpResponse httpResponse = null;
100
101         try {
102             int timeout = 60 * 1000;
103
104             RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout)
105                     .setConnectionRequestTimeout(timeout).build();
106
107             HttpClient client = HttpClientBuilder.create().build();
108             method = new HttpPost(url);
109             method.setConfig(requestConfig);
110
111             if (message != null) {
112                 method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
113             }
114
115             boolean error = false;
116
117             try {
118                 String userCredentials = CryptoUtils.decrypt(env.getProperty(Constants.BPEL_AUTH_PROP),
119                         env.getProperty(Constants.ENCRYPTION_KEY_PROP));
120                 String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
121                 method.setHeader("Authorization", authorization);
122                 method.setHeader(ONAPLogConstants.Headers.REQUEST_ID, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID));
123                 method.setHeader(ONAPLogConstants.Headers.INVOCATION_ID, MDC.get(ONAPLogConstants.MDCs.INVOCATION_ID));
124                 method.setHeader(ONAPLogConstants.Headers.PARTNER_NAME, "SO-SDNCAdapter");
125             } catch (Exception e) {
126                 logger.error("{} {} {} {}", MessageEnum.RA_SET_CALLBACK_AUTH_EXC.toString(), CAMUNDA,
127                         ErrorCode.BusinessProcesssError.getValue(), "Unable to set authorization in callback request",
128                         e);
129                 error = true;
130             }
131
132             if (!error) {
133                 httpResponse = client.execute(method);
134
135                 @SuppressWarnings("unused")
136                 String responseContent = null;
137
138                 if (httpResponse.getEntity() != null) {
139                     responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
140                 }
141
142                 if (httpResponse.getStatusLine().getStatusCode() >= 300) {
143                     String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
144                     logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
145                             ErrorCode.BusinessProcesssError.getValue(), msg);
146
147                 }
148             }
149             return true;
150         } catch (Exception e) {
151             logger.error("{} {} {} {}", MessageEnum.RA_CALLBACK_BPEL_EXC.toString(), CAMUNDA,
152                     ErrorCode.BusinessProcesssError.getValue(), "Error sending callback request", e);
153             return false;
154         } finally {
155             if (httpResponse != null) {
156                 try {
157                     EntityUtils.consume(httpResponse.getEntity());
158                     httpResponse = null;
159                 } catch (Exception e) {
160                     logger.debug("Exception:", e);
161                 }
162             }
163
164             if (method != null) {
165                 try {
166                     method.reset();
167                 } catch (Exception e) {
168                     logger.debug("Exception:", e);
169                 }
170             }
171             logger.info("{} {}", MessageEnum.RA_CALLBACK_BPEL_COMPLETE.toString(), CAMUNDA);
172         }
173     }
174 }