6383f57693e82ba83ccf3520501e71f03cfc8d49
[so.git] / adapters / mso-openstack-adapters / src / main / java / org / onap / so / adapters / vnf / BpelRestClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.onap.so.adapters.vnf;
22
23
24 import java.security.GeneralSecurityException;
25 import java.util.Set;
26 import java.util.TreeSet;
27
28 import javax.annotation.PostConstruct;
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 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;
47
48 /**
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")
59  */
60 @Component("VnfBpel")
61 @Scope("prototype")
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);
73
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 = "";
86
87         @Autowired
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;
96
97         // last response from BPEL engine
98         private int lastResponseCode;
99         private String lastResponse;
100
101         /**
102          * Create a client to send results to the BPEL engine, using configuration from the
103          * MSO_PROP_VNF_ADAPTER properties.
104          */
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;
113                 lastResponse = "";
114                 
115         }
116         
117         @PostConstruct
118         protected void init() {
119
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);
126         }
127
128         public int getSocketTimeout() {
129                 return socketTimeout;
130         }
131
132         public void setSocketTimeout(int socketTimeout) {
133                 this.socketTimeout = socketTimeout;
134         }
135
136         public int getConnectTimeout() {
137                 return connectTimeout;
138         }
139
140         public void setConnectTimeout(int connectTimeout) {
141                 this.connectTimeout = connectTimeout;
142         }
143
144         public int getRetryCount() {
145                 return retryCount;
146         }
147
148         public void setRetryCount(int retryCount) {
149                 int newRetryCount = retryCount;
150                 if (newRetryCount < 0)
151                         newRetryCount = DEFAULT_RETRY_COUNT;
152                 this.retryCount = newRetryCount;
153         }
154
155         public int getRetryInterval() {
156                 return retryInterval;
157         }
158
159         public void setRetryInterval(int retryInterval) {
160                 this.retryInterval = retryInterval;
161         }
162
163         public String getCredentials() {
164                 return credentials;
165         }
166
167         public void setCredentials(String credentials) {
168                 this.credentials = credentials;
169         }
170
171         public String getRetryList() {
172                 if (retryList.isEmpty())
173                         return "";
174                 String t = retryList.toString();
175                 return t.substring(1, t.length()-1);
176         }
177
178         public void setRetryList(String retryList) {
179                 Set<Integer> s = new TreeSet<>();
180                 for (String t : retryList.split("[, ]")) {
181                         try {
182                                 s.add(Integer.parseInt(t));
183                         } catch (NumberFormatException x) {
184                                 // ignore
185                         }
186                 }
187                 this.retryList = s;
188         }
189
190         public int getLastResponseCode() {
191                 return lastResponseCode;
192         }
193
194         public String getLastResponse() {
195                 return lastResponse;
196         }
197
198         /**
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
207          */
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;
212                 while (true) {
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.");
217                                 return true;
218                         }
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");
222                                 return false;
223                         }
224                         totalretries++;
225                         int sleepinterval = retryint;
226                         if (retryint < 0) {
227                                 // if retry interval is negative double the retry on each pass
228                                 sleepinterval = -retryint;
229                                 retryint *= 2;
230                         }
231                         debug("Sleeping for " + sleepinterval + " seconds.");
232                         try {
233                                 Thread.sleep(sleepinterval * 1000L);
234                         } catch (InterruptedException e) {
235                                 LOGGER.debug("Exception while Thread sleep", e);
236                                 Thread.currentThread().interrupt();
237                         }
238                 }
239         }
240         private void debug(String m) {
241                 LOGGER.debug(m);
242         }
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);
246
247                 //POST
248                 HttpPost post = new HttpPost(bpelUrl);
249                 if (credentials != null && !credentials.isEmpty())
250                         post.addHeader("Authorization", "Basic " + DatatypeConverter.printBase64Binary(credentials.getBytes()));
251
252         //ContentType
253         ContentType ctype = isxml ? ContentType.APPLICATION_XML : ContentType.APPLICATION_JSON;
254         post.setEntity(new StringEntity(toBpelStr, ctype));
255
256         //Timeouts
257                 RequestConfig requestConfig = RequestConfig
258                         .custom()
259                         .setSocketTimeout(socketTimeout * 1000)
260                         .setConnectTimeout(connectTimeout * 1000)
261                         .build();
262                 post.setConfig(requestConfig);
263                                 
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) : "";
270                         } else {
271                                 lastResponseCode = 900;
272                                 lastResponse = "";
273                         }
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;
278                         lastResponse = "";
279                 }
280
281                 LOGGER.debug("Response code from BPEL server: "+lastResponseCode);
282                 LOGGER.debug("Response body is: "+lastResponse);
283         }
284         
285         private String getEncryptedProperty(String key, String defaultValue, String encryptionKey) {
286                 if (env.getProperty(key) != null) {
287                         try {
288                                 return CryptoUtils.decrypt(env.getProperty(key), encryptionKey);
289                         } catch (GeneralSecurityException e) {
290                                 LOGGER.debug("Exception while decrypting property: " + env.getProperty(key), e);
291                         }
292                 }
293                 return defaultValue;
294         }
295
296 }