Fixed CloseableHttpClient close issue
[so.git] / adapters / mso-network-adapter / src / main / java / org / openecomp / mso / adapters / network / BpelRestClient.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  * 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
11  *
12  *      http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  */
21
22 package org.openecomp.mso.adapters.network;
23
24
25 import java.io.IOException;
26 import java.util.Set;
27 import java.util.TreeSet;
28
29 import javax.xml.bind.DatatypeConverter;
30
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
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;
46
47 /**
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")
58  */
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);
70
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 = "";
83
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;
91
92         // last response from BPEL engine
93         private int lastResponseCode;
94         private String lastResponse;
95
96         /**
97          * Create a client to send results to the BPEL engine, using configuration from the
98          * MSO_PROP_NETWORK_ADAPTER properties.
99          */
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;
108                 lastResponse = "";
109
110                 try {
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);
122                 }
123         }
124
125         public int getSocketTimeout() {
126                 return socketTimeout;
127         }
128
129         public void setSocketTimeout(int socketTimeout) {
130                 this.socketTimeout = socketTimeout;
131         }
132
133         public int getConnectTimeout() {
134                 return connectTimeout;
135         }
136
137         public void setConnectTimeout(int connectTimeout) {
138                 this.connectTimeout = connectTimeout;
139         }
140
141         public int getRetryCount() {
142                 return retryCount;
143         }
144
145         public void setRetryCount(int retryCount) {
146             int retCnt = 0;
147                 if (retryCount < 0)
148                         retCnt = DEFAULT_RETRY_COUNT;
149                 this.retryCount = retCnt;
150         }
151
152         public int getRetryInterval() {
153                 return retryInterval;
154         }
155
156         public void setRetryInterval(int retryInterval) {
157                 this.retryInterval = retryInterval;
158         }
159
160         public String getCredentials() {
161                 return credentials;
162         }
163
164         public void setCredentials(String credentials) {
165                 this.credentials = credentials;
166         }
167
168         public String getRetryList() {
169                 if (retryList.isEmpty())
170                         return "";
171                 String t = retryList.toString();
172                 return t.substring(1, t.length()-1);
173         }
174
175         public void setRetryList(String retryList) {
176                 Set<Integer> s = new TreeSet<>();
177                 for (String t : retryList.split("[, ]")) {
178                         try {
179                                 s.add(Integer.parseInt(t));
180                         } catch (NumberFormatException x) {
181                                 LOGGER.debug("Exception while parsing", x);
182                         }
183                 }
184                 this.retryList = s;
185         }
186
187         public int getLastResponseCode() {
188                 return lastResponseCode;
189         }
190
191         public String getLastResponse() {
192                 return lastResponse;
193         }
194
195         /**
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
204          */
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;
209                 while (true) {
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.");
214                                 return true;
215                         }
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");
219                                 return false;
220                         }
221                         totalretries++;
222                         int sleepinterval = retryint;
223                         if (retryint < 0) {
224                                 // if retry interval is negative double the retry on each pass
225                                 sleepinterval = -retryint;
226                                 retryint *= 2;
227                         }
228                         debug("Sleeping for " + sleepinterval + " seconds.");
229                         try {
230                                 Thread.sleep(sleepinterval * 1000L);
231                         } catch (InterruptedException e) {
232                                 LOGGER.debug("Exception while Thread sleep", e);
233                         }
234                 }
235         }
236         private void debug(String m) {
237                 LOGGER.debug(m);
238 //              System.err.println(m);
239         }
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);
243
244                 //POST
245                 HttpPost post = new HttpPost(bpelUrl);
246                 if (credentials != null && !credentials.isEmpty())
247                         post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
248
249         //ContentType
250         ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
251         post.setEntity(new StringEntity(toBpelStr, ctype));
252
253         //Timeouts
254                 RequestConfig requestConfig = RequestConfig
255                         .custom()
256                         .setSocketTimeout(socketTimeout * 1000)
257                         .setConnectTimeout(connectTimeout * 1000)
258                         .build();
259                 post.setConfig(requestConfig);
260
261         //Client 4.3+
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) : "";
269                         } else {
270                                 lastResponseCode = 900;
271                                 lastResponse = "";
272                         }
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;
277                         lastResponse = "";
278                 }
279                 LOGGER.debug("Response code from BPEL server: "+lastResponseCode);
280                 LOGGER.debug("Response body is: "+lastResponse);
281         }
282
283 }