aboutsummaryrefslogtreecommitdiffstats
path: root/adapters/mso-sdnc-adapter/src/main/java/org/openecomp/mso/adapters/sdnc/sdncrest/BPRestCallback.java
blob: 0e3e6278b52379a6898720458288ec2545f6b14d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
/*-
 * ============LICENSE_START=======================================================
 * OPENECOMP - MSO
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */
package org.openecomp.mso.adapters.sdnc.sdncrest;

import org.openecomp.mso.adapters.sdnc.impl.Constants;
import org.openecomp.mso.logger.MessageEnum;
import org.openecomp.mso.logger.MsoAlarmLogger;
import org.openecomp.mso.logger.MsoLogger;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.xml.bind.DatatypeConverter;

/**
 * Sends asynchronous messages to the BPMN WorkflowMessage service.
 */
public class BPRestCallback {
	private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
	private static final MsoAlarmLogger ALARMLOGGER = new MsoAlarmLogger();

	/**
	 * Sends a message to the BPMN workflow message service. The URL path is
	 * constructed using the specified message type and correlator.
	 * @param workflowMessageUrl the base BPMN WorkflowMessage URL
	 * @param messageType the message type
	 * @param correlator the message correlator
	 * @param message the JSON content
	 * @return true if the message was consumed successfully by the endpoint
	 */
	public boolean send(String workflowMessageUrl, String messageType, String correlator, String message) {
		LOGGER.debug(getClass().getSimpleName() + ".send("
			+ "workflowMessageUrl=" + workflowMessageUrl
			+ " messageType=" + messageType
			+ " correlator=" + correlator
			+ " message=" + message
			+ ")");

		while (workflowMessageUrl.endsWith("/")) {
			workflowMessageUrl = workflowMessageUrl.substring(0, workflowMessageUrl.length()-1);
		}

		String endpoint = workflowMessageUrl + "/" + SDNCAdapterUtils.encodeURLPathSegment(messageType)
			+ "/" + SDNCAdapterUtils.encodeURLPathSegment(correlator);

		return send(endpoint, message);
	}

	/**
	 * Sends a message to the BPMN workflow message service. The specified URL
	 * must have the message type and correlator already embedded in it.
	 * @param url the endpoint URL
	 * @param message the JSON content
	 * @return true if the message was consumed successfully by the endpoint
	 */
	public boolean send(String url, String message) {
		LOGGER.debug(getClass().getSimpleName() + ".send("
			+ "url=" + url
			+ " message=" + message
			+ ")");

		LOGGER.info(MessageEnum.RA_CALLBACK_BPEL, message == null ? "[no content]" : message, "Camunda", "");

		HttpPost method = null;
		HttpResponse httpResponse = null;

		try {
			// TODO: configurable timeout?
			int timeout = 60 * 1000;

			RequestConfig requestConfig = RequestConfig.custom()
				.setSocketTimeout(timeout)
				.setConnectTimeout(timeout)
				.setConnectionRequestTimeout(timeout)
				.build();

			HttpClient client = HttpClientBuilder.create().build();
			method = new HttpPost(url);
			method.setConfig(requestConfig);

			if (message != null) {
				method.setEntity(new StringEntity(message, ContentType.APPLICATION_JSON));
			}

			boolean error = false;

			try {
				// AAF Integration, disabled for now due to the constrains from other party
				// String userCredentials = CredentialConstants.getDecryptedCredential(Constants.DEFAULT_BPEL_AUTH);
				// Once AAF enabled, the credential shall be get by triggering the CredentialConstants.getDecryptedCredential -- remove line
				String  userCredentials = SDNCAdapterProperties.getEncryptedProperty(Constants.BPEL_AUTH_PROP,
					Constants.DEFAULT_BPEL_AUTH, Constants.ENCRYPTION_KEY);
				String authorization = "Basic " + DatatypeConverter.printBase64Binary(userCredentials.getBytes());
				method.setHeader("Authorization", authorization);
			} catch (Exception e) {
				LOGGER.error(MessageEnum.RA_SET_CALLBACK_AUTH_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError,
					"Unable to set authorization in callback request", e);
				ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL,
					"Unable to set authorization in callback request: " + e.getMessage());
				error = true;
			}

			if (!error) {
				httpResponse = client.execute(method);

				@SuppressWarnings("unused")
				String responseContent = null;

				if (httpResponse.getEntity() != null) {
					responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
				}

				if (httpResponse.getStatusLine().getStatusCode() >= 300) {
					String msg = "Received error response to callback request: " + httpResponse.getStatusLine();
					LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, msg);
					ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL, msg);
				}

				httpResponse = null;
			}

			method.reset();
			method = null;
			return true;
		} catch (Exception e) {
			LOGGER.error(MessageEnum.RA_CALLBACK_BPEL_EXC, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError,
				"Error sending callback request", e);
			ALARMLOGGER.sendAlarm("MsoInternalError", MsoAlarmLogger.CRITICAL,
				"Error sending callback request: " + e.getMessage());
			return false;
		} finally {
			if (httpResponse != null) {
				try {
					EntityUtils.consume(httpResponse.getEntity());
				} catch (Exception e) {
					// Ignore
				}
			}

			if (method != null) {
				try {
					method.reset();
				} catch (Exception e) {
					// Ignore
				}
			}

			LOGGER.info(MessageEnum.RA_CALLBACK_BPEL_COMPLETE, "Camunda", "");
		}
	}
}