2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.so.adapters.vnf;
24 import java.security.GeneralSecurityException;
26 import java.util.TreeSet;
28 import javax.annotation.PostConstruct;
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;
40 import org.onap.so.logger.MessageEnum;
41 import org.onap.so.logger.MsoLogger;
42 import org.onap.so.utils.CryptoUtils;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.context.annotation.Scope;
45 import org.springframework.core.env.Environment;
46 import org.springframework.stereotype.Component;
49 * This is the class that is used to POST replies from the MSO adapters to the BPEL engine.
50 * It can be configured via property file, or modified using the member methods.
51 * The properties to use are:
52 * org.onap.so.adapters.vnf.bpelauth encrypted authorization string to send to BEPL engine
53 * org.onap.so.adapters.vnf.sockettimeout socket timeout value
54 * org.onap.so.adapters.vnf.connecttimeout connect timeout value
55 * org.onap.so.adapters.vnf.retrycount number of times to retry failed connections
56 * org.onap.so.adapters.vnf.retryinterval interval (in seconds) between retries
57 * org.onap.so.adapters.vnf.retrylist list of response codes that will trigger a retry (the special code
58 * 900 means "connection was not established")
62 public class BpelRestClient {
63 public static final String MSO_PROP_VNF_ADAPTER = "MSO_PROP_VNF_ADAPTER";
64 private static final String PROPERTY_DOMAIN = "org.onap.so.adapters.vnf";
65 private static final String BPEL_AUTH_PROPERTY = PROPERTY_DOMAIN+".bpelauth";
66 private static final String SOCKET_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".sockettimeout";
67 private static final String CONN_TIMEOUT_PROPERTY = PROPERTY_DOMAIN+".connecttimeout";
68 private static final String RETRY_COUNT_PROPERTY = PROPERTY_DOMAIN+".retrycount";
69 private static final String RETRY_INTERVAL_PROPERTY = PROPERTY_DOMAIN+".retryinterval";
70 private static final String RETRY_LIST_PROPERTY = PROPERTY_DOMAIN+".retrylist";
71 private static final String ENCRYPTION_KEY = "aa3871669d893c7fb8abbcda31b88b4f";
72 private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA, BpelRestClient.class);
74 /** Default socket timeout (in seconds) */
75 public static final int DEFAULT_SOCKET_TIMEOUT = 5;
76 /** Default connect timeout (in seconds) */
77 public static final int DEFAULT_CONNECT_TIMEOUT = 5;
78 /** By default, retry up to five times */
79 public static final int DEFAULT_RETRY_COUNT = 5;
80 /** Default interval to wait between retries (in seconds), negative means use backoff algorithm */
81 public static final int DEFAULT_RETRY_INTERVAL = -15;
82 /** Default list of response codes to trigger a retry */
83 public static final String DEFAULT_RETRY_LIST = "408,429,500,502,503,504,900"; // 900 is "connection failed"
84 /** Default credentials */
85 public static final String DEFAULT_CREDENTIALS = "";
88 private Environment env;
89 // Properties of the BPEL client -- all are configurable
90 private int socketTimeout;
91 private int connectTimeout;
92 private int retryCount;
93 private int retryInterval;
94 private Set<Integer> retryList;
95 private String credentials;
97 // last response from BPEL engine
98 private int lastResponseCode;
99 private String lastResponse;
102 * Create a client to send results to the BPEL engine, using configuration from the
103 * MSO_PROP_VNF_ADAPTER properties.
105 public BpelRestClient() {
106 socketTimeout = DEFAULT_SOCKET_TIMEOUT;
107 connectTimeout = DEFAULT_CONNECT_TIMEOUT;
108 retryCount = DEFAULT_RETRY_COUNT;
109 retryInterval = DEFAULT_RETRY_INTERVAL;
110 setRetryList(DEFAULT_RETRY_LIST);
111 credentials = DEFAULT_CREDENTIALS;
112 lastResponseCode = 0;
118 protected void init() {
120 socketTimeout = env.getProperty(SOCKET_TIMEOUT_PROPERTY, Integer.class, DEFAULT_SOCKET_TIMEOUT);
121 connectTimeout = env.getProperty(CONN_TIMEOUT_PROPERTY, Integer.class, DEFAULT_CONNECT_TIMEOUT);
122 retryCount = env.getProperty(RETRY_COUNT_PROPERTY, Integer.class, DEFAULT_RETRY_COUNT);
123 retryInterval = env.getProperty(RETRY_INTERVAL_PROPERTY, Integer.class, DEFAULT_RETRY_INTERVAL);
124 setRetryList(env.getProperty(RETRY_LIST_PROPERTY, DEFAULT_RETRY_LIST));
125 credentials = getEncryptedProperty(BPEL_AUTH_PROPERTY, DEFAULT_CREDENTIALS, ENCRYPTION_KEY);
128 public int getSocketTimeout() {
129 return socketTimeout;
132 public void setSocketTimeout(int socketTimeout) {
133 this.socketTimeout = socketTimeout;
136 public int getConnectTimeout() {
137 return connectTimeout;
140 public void setConnectTimeout(int connectTimeout) {
141 this.connectTimeout = connectTimeout;
144 public int getRetryCount() {
148 public void setRetryCount(int retryCount) {
149 int newRetryCount = retryCount;
150 if (newRetryCount < 0)
151 newRetryCount = DEFAULT_RETRY_COUNT;
152 this.retryCount = newRetryCount;
155 public int getRetryInterval() {
156 return retryInterval;
159 public void setRetryInterval(int retryInterval) {
160 this.retryInterval = retryInterval;
163 public String getCredentials() {
167 public void setCredentials(String credentials) {
168 this.credentials = credentials;
171 public String getRetryList() {
172 if (retryList.isEmpty())
174 String t = retryList.toString();
175 return t.substring(1, t.length()-1);
178 public void setRetryList(String retryList) {
179 Set<Integer> s = new TreeSet<>();
180 for (String t : retryList.split("[, ]")) {
182 s.add(Integer.parseInt(t));
183 } catch (NumberFormatException x) {
190 public int getLastResponseCode() {
191 return lastResponseCode;
194 public String getLastResponse() {
199 * Post a response to the URL of the BPEL engine. As long as the response code is one of those in
200 * the retryList, the post will be retried up to "retrycount" times with an interval (in seconds)
201 * of "retryInterval". If retryInterval is negative, then each successive retry interval will be
202 * double the previous one.
203 * @param toBpelStr the content (XML or JSON) to post
204 * @param bpelUrl the URL to post to
205 * @param isxml true if the content is XML, otherwise assumed to be JSON
206 * @return true if the post succeeded, false if all retries failed
208 public boolean bpelPost(final String toBpelStr, final String bpelUrl, final boolean isxml) {
209 debug("Sending response to BPEL: " + toBpelStr);
210 int totalretries = 0;
211 int retryint = retryInterval;
213 sendOne(toBpelStr, bpelUrl, isxml);
214 // Note: really should handle response code 415 by switching between content types if needed
215 if (!retryList.contains(lastResponseCode)) {
216 debug("Got response code: " + lastResponseCode + ": returning.");
219 if (totalretries >= retryCount) {
220 debug("Retried " + totalretries + " times, giving up.");
221 LOGGER.error(MessageEnum.RA_SEND_VNF_NOTIF_ERR, "Could not deliver response to BPEL after "+totalretries+" tries: "+toBpelStr, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, "Could not deliver response to BPEL");
225 int sleepinterval = retryint;
227 // if retry interval is negative double the retry on each pass
228 sleepinterval = -retryint;
231 debug("Sleeping for " + sleepinterval + " seconds.");
233 Thread.sleep(sleepinterval * 1000L);
234 } catch (InterruptedException e) {
235 LOGGER.debug("Exception while Thread sleep", e);
236 Thread.currentThread().interrupt();
240 private void debug(String m) {
243 private void sendOne(final String toBpelStr, final String bpelUrl, final boolean isxml) {
244 LOGGER.debug("Sending to BPEL server: "+bpelUrl);
245 LOGGER.debug("Content is: "+toBpelStr);
248 HttpPost post = new HttpPost(bpelUrl);
249 if (credentials != null && !credentials.isEmpty())
250 post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
253 ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
254 post.setEntity(new StringEntity(toBpelStr, ctype));
257 RequestConfig requestConfig = RequestConfig
259 .setSocketTimeout(socketTimeout * 1000)
260 .setConnectTimeout(connectTimeout * 1000)
262 post.setConfig(requestConfig);
264 try (CloseableHttpClient client = HttpClients.createDefault()) {
265 CloseableHttpResponse response = client.execute(post);
266 if (response != null) {
267 lastResponseCode = response.getStatusLine().getStatusCode();
268 HttpEntity entity = response.getEntity();
269 lastResponse = (entity != null) ? EntityUtils.toString(entity) : "";
271 lastResponseCode = 900;
274 } catch (Exception e) {
275 String error = "Error sending Bpel notification:" + toBpelStr;
276 LOGGER.error (MessageEnum.RA_SEND_VNF_NOTIF_ERR, error, "Camunda", "", MsoLogger.ErrorCode.BusinessProcesssError, "Exception - Error sending Bpel notification", e);
277 lastResponseCode = 900;
281 LOGGER.debug("Response code from BPEL server: "+lastResponseCode);
282 LOGGER.debug("Response body is: "+lastResponse);
285 private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
286 if (env.getProperty(key) != null) {
288 return CryptoUtils.decrypt(env.getProperty(key), encryptionKey);
289 } catch (GeneralSecurityException e) {
290 LOGGER.debug("Exception while decrypting property: " + env.getProperty(key), e);