2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.openecomp.mso.adapters.network;
25 import java.io.IOException;
27 import java.util.TreeSet;
29 import javax.xml.bind.DatatypeConverter;
31 import org.apache.http.HttpEntity;
32 import org.apache.http.client.config.RequestConfig;
33 import org.apache.http.client.methods.CloseableHttpResponse;
34 import org.apache.http.client.methods.HttpPost;
35 import org.apache.http.entity.ContentType;
36 import org.apache.http.entity.StringEntity;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.apache.http.impl.client.HttpClients;
39 import org.apache.http.util.EntityUtils;
41 import org.openecomp.mso.logger.MessageEnum;
42 import org.openecomp.mso.logger.MsoLogger;
43 import org.openecomp.mso.properties.MsoJavaProperties;
44 import org.openecomp.mso.properties.MsoPropertiesException;
45 import org.openecomp.mso.properties.MsoPropertiesFactory;
48 * This is the class that is used to POST replies from the MSO adapters to the BPEL engine.
49 * It can be configured via property file, or modified using the member methods.
50 * The properties to use are:
51 * org.openecomp.mso.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine
52 * org.openecomp.mso.adapters.vnf.sockettimeout socket timeout value
53 * org.openecomp.mso.adapters.vnf.connecttimeout connect timeout value
54 * org.openecomp.mso.adapters.vnf.retrycount number of times to retry failed connections
55 * org.openecomp.mso.adapters.vnf.retryinterval interval (in seconds) between retries
56 * org.openecomp.mso.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code
57 * 900 means "connection was not established")
59 public class BpelRestClient {
60 public static final String MSO_PROP_NETWORK_ADAPTER = "MSO_PROP_NETWORK_ADAPTER";
61 private static final String PROPERTY_DOMAIN = "org.openecomp.mso.adapters.network";
62 private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth";
63 private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout";
64 private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout";
65 private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount";
66 private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval";
67 private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist";
68 private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
69 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
71 /** Default socket timeout (in seconds) */
72 public static final int DEFAULT_SOCKET_TIMEOUT = 5;
73 /** Default connect timeout (in seconds) */
74 public static final int DEFAULT_CONNECT_TIMEOUT = 5;
75 /** By default, retry up to five times */
76 public static final int DEFAULT_RETRY_COUNT = 5;
77 /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */
78 public static final int DEFAULT_RETRY_INTERVAL = -15;
79 /** Default list of response codes to trigger a retry */
80 public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed"
81 /** Default credentials */
82 public static final String DEFAULT_CREDENTIALS = "";
84 // Properties of the BPEL client -- all are configurable
85 private int socketTimeout;
86 private int connectTimeout;
87 private int retryCount;
88 private int retryInterval;
89 private Set<Integer> retryList;
90 private String credentials;
92 // last response from BPEL engine
93 private int lastResponseCode;
94 private String lastResponse;
97 * Create a client to send results to the BPEL engine, using configuration from the
98 * MSO_PROP_NETWORK_ADAPTER properties.
100 public BpelRestClient() {
101 socketTimeout = DEFAULT_SOCKET_TIMEOUT;
102 connectTimeout = DEFAULT_CONNECT_TIMEOUT;
103 retryCount = DEFAULT_RETRY_COUNT;
104 retryInterval = DEFAULT_RETRY_INTERVAL;
105 setRetryList(DEFAULT_RETRY_LIST);
106 credentials = DEFAULT_CREDENTIALS;
107 lastResponseCode = 0;
111 MsoPropertiesFactory msoPropertiesFactory = new MsoPropertiesFactory();
112 MsoJavaProperties jp = msoPropertiesFactory.getMsoJavaProperties (MSO_PROP_NETWORK_ADAPTER);
113 socketTimeout = jp.getIntProperty(SOCKET_TIMEOUT_PROPERTY, DEFAULT_SOCKET_TIMEOUT);
114 connectTimeout = jp.getIntProperty(CONN_TIMEOUT_PROPERTY, DEFAULT_CONNECT_TIMEOUT);
115 retryCount = jp.getIntProperty(RETRY_COUNT_PROPERTY, DEFAULT_RETRY_COUNT);
116 retryInterval = jp.getIntProperty(RETRY_INTERVAL_PROPERTY, DEFAULT_RETRY_INTERVAL);
117 setRetryList(jp.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST));
118 credentials = jp.getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY);
119 } catch (MsoPropertiesException e) {
120 String error = "Unable to get properties:" + MSO_PROP_NETWORK_ADAPTER;
121 LOGGER.error (MessageEnum.RA_CONFIG_EXC, error, "", "", MsoLogger.ErrorCode.DataError, "Unable to get properties", e);
125 public int getSocketTimeout() {
126 return socketTimeout;
129 public void setSocketTimeout(int socketTimeout) {
130 this.socketTimeout = socketTimeout;
133 public int getConnectTimeout() {
134 return connectTimeout;
137 public void setConnectTimeout(int connectTimeout) {
138 this.connectTimeout = connectTimeout;
141 public int getRetryCount() {
145 public void setRetryCount(int retryCount) {
148 retCnt = DEFAULT_RETRY_COUNT;
149 this.retryCount = retCnt;
152 public int getRetryInterval() {
153 return retryInterval;
156 public void setRetryInterval(int retryInterval) {
157 this.retryInterval = retryInterval;
160 public String getCredentials() {
164 public void setCredentials(String credentials) {
165 this.credentials = credentials;
168 public String getRetryList() {
169 if (retryList.isEmpty())
171 String t = retryList.toString();
172 return t.substring(1, t.length()-1);
175 public void setRetryList(String retryList) {
176 Set<Integer> s = new TreeSet<>();
177 for (String t : retryList.split("[, ]")) {
179 s.add(Integer.parseInt(t));
180 } catch (NumberFormatException x) {
181 LOGGER.debug("Exception while parsing", x);
187 public int getLastResponseCode() {
188 return lastResponseCode;
191 public String getLastResponse() {
196 * Post a response to the URL of the BPEL engine. As long as the response code is one of those in
197 * the retryList, the post will be retried up to "retrycount" times with an interval (in seconds)
198 * of "retryInterval". If retryInterval is negative, then each successive retry interval will be
199 * double the previous one.
200 * @param toBpelStr the content (XML or JSON) to post
201 * @param bpelUrl the URL to post to
202 * @param isxml true if the content is XML, otherwise assumed to be JSON
203 * @return true if the post succeeded, false if all retries failed
205 public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) {
206 debug("Sending response to BPEL: " + toBpelStr);
207 int totalretries = 0;
208 int retryint = retryInterval;
210 sendOne(toBpelStr, bpelUrl, isxml);
211 // Note: really should handle response code 415 by switching between content types if needed
212 if (!retryList.contains(lastResponseCode)) {
213 debug("Got response code: " + lastResponseCode + ": returning.");
216 if (totalretries >= retryCount) {
217 debug("Retried " + totalretries + " times, giving up.");
218 LOGGER.error(MessageEnum.RA_SEND_VNF_NOTIF_ERR, "Could not deliver response to BPEL after "+totalretries+" tries: "+toBpelStr, "Camunda", "", MsoLogger.ErrorCode.DataError, "Could not deliver response to BPEL");
222 int sleepinterval = retryint;
224 // if retry interval is negative double the retry on each pass
225 sleepinterval = -retryint;
228 debug("Sleeping for " + sleepinterval + " seconds.");
230 Thread.sleep(sleepinterval * 1000L);
231 } catch (InterruptedException e) {
232 LOGGER.debug("Exception while Thread sleep", e);
236 private void debug(String m) {
238 // System.err.println(m);
240 private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) {
241 LOGGER.debug("Sending to BPEL server: "+bpelUrl);
242 LOGGER.debug("Content is: "+toBpelStr);
245 HttpPost post = new HttpPost(bpelUrl);
246 if (credentials != null && !credentials.isEmpty())
247 post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
250 ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
251 post.setEntity(new StringEntity(toBpelStr, ctype));
254 RequestConfig requestConfig = RequestConfig
256 .setSocketTimeout(socketTimeout * 1000)
257 .setConnectTimeout(connectTimeout * 1000)
259 post.setConfig(requestConfig);
262 //Execute & GetResponse
263 try (CloseableHttpClient client = HttpClients.createDefault()) {
264 CloseableHttpResponse response = client.execute(post);
265 if (response != null) {
266 lastResponseCode = response.getStatusLine().getStatusCode();
267 HttpEntity entity = response.getEntity();
268 lastResponse = (entity != null) ? EntityUtils.toString(entity) : "";
270 lastResponseCode = 900;
273 } catch (Exception e) {
274 String error = "Error sending Bpel notification:" + toBpelStr;
275 LOGGER.error (MessageEnum.RA_SEND_VNF_NOTIF_ERR, error, "Camunda", "", MsoLogger.ErrorCode.AvailabilityError, "Exception sending Bpel notification", e);
276 lastResponseCode = 900;
279 LOGGER.debug("Response code from BPEL server: "+lastResponseCode);
280 LOGGER.debug("Response body is: "+lastResponse);