Fix for radio buttons
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / rest / impl / HttpRestClientServiceImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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.openecomp.sdc.common.rest.impl;
22
23 import java.io.IOException;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URI;
26 import java.security.KeyManagementException;
27 import java.security.NoSuchAlgorithmException;
28 import java.security.cert.CertificateException;
29 import java.util.Map.Entry;
30 import java.util.Properties;
31
32 import javax.net.ssl.SSLContext;
33 import javax.net.ssl.SSLException;
34 import javax.net.ssl.SSLSession;
35 import javax.net.ssl.SSLSocket;
36 import javax.net.ssl.TrustManager;
37
38 import org.apache.http.ConnectionReuseStrategy;
39 import org.apache.http.HeaderElement;
40 import org.apache.http.HeaderElementIterator;
41 import org.apache.http.HeaderIterator;
42 import org.apache.http.HttpEntity;
43 import org.apache.http.HttpResponse;
44 import org.apache.http.HttpStatus;
45 import org.apache.http.client.methods.HttpDelete;
46 import org.apache.http.client.methods.HttpGet;
47 import org.apache.http.client.methods.HttpPost;
48 import org.apache.http.client.methods.HttpPut;
49 import org.apache.http.client.methods.HttpRequestBase;
50 import org.apache.http.conn.ConnectionKeepAliveStrategy;
51 import org.apache.http.conn.scheme.Scheme;
52 import org.apache.http.conn.ssl.SSLSocketFactory;
53 import org.apache.http.conn.ssl.X509HostnameVerifier;
54 import org.apache.http.entity.StringEntity;
55 import org.apache.http.impl.client.DefaultHttpClient;
56 import org.apache.http.impl.conn.PoolingClientConnectionManager;
57 import org.apache.http.message.BasicHeaderElementIterator;
58 import org.apache.http.params.BasicHttpParams;
59 import org.apache.http.params.CoreConnectionPNames;
60 import org.apache.http.params.HttpParams;
61 import org.apache.http.protocol.HTTP;
62 import org.apache.http.protocol.HttpContext;
63 import org.apache.http.util.EntityUtils;
64 import org.openecomp.sdc.common.rest.api.IRestClient;
65 import org.openecomp.sdc.common.rest.api.RestClientServiceExeption;
66 import org.openecomp.sdc.common.rest.api.RestConfigurationInfo;
67 import org.openecomp.sdc.common.rest.api.RestResponse;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 public class HttpRestClientServiceImpl implements IRestClient {
72
73         private Logger log = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName());
74
75         public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
76
77         public final static int DEFAULT_CONNECT_TIMEOUT = 10;
78
79         private DefaultHttpClient httpClient;
80
81         private SSLSocketFactory sslFactory;
82
83         private Logger logger = LoggerFactory.getLogger(HttpRestClientServiceImpl.class.getName());
84
85         PoolingClientConnectionManager cm = null;
86
87         public boolean init() {
88
89                 return init(new RestConfigurationInfo());
90
91         }
92
93         public boolean init(RestConfigurationInfo restConfigurationInfo) {
94
95                 boolean initialized = false;
96
97                 logger.debug("HttpRestClientServiceImpl::init - start. restConfigurationInfo= {}", restConfigurationInfo);
98
99                 try {
100                         createHttpClient(restConfigurationInfo);
101
102                         initialized = true;
103                 } catch (KeyManagementException e) {
104                         String msg = "Failed creating client config for rest. " + e.getMessage();
105                         logger.error(msg, e);
106                         // throw new RestClientServiceExeption(e.getMessage());
107                 } catch (NoSuchAlgorithmException e) {
108                         String msg = "Failed creating client config for rest. " + e.getMessage();
109                         logger.error(msg, e);
110                         // throw new RestClientServiceExeption(msg);
111                 }
112
113                 logger.debug("HttpRestClientServiceImpl::init - finish successfully");
114
115                 return initialized;
116         }
117
118         public void destroy() {
119
120                 if (this.httpClient != null) {
121                         this.httpClient.getConnectionManager().shutdown();
122                         logger.info("After closing connection Manager of rest Client.");
123                 }
124
125         }
126
127         private void createHttpClient(RestConfigurationInfo restConfigurationInfo) throws KeyManagementException, NoSuchAlgorithmException {
128
129                 PoolingClientConnectionManager cm = new PoolingClientConnectionManager();
130
131                 Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize();
132                 int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
133                 if (connPoolSizeObj != null) {
134                         connPoolSize = connPoolSizeObj.intValue();
135                         if (connPoolSize <= 0) {
136                                 connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
137                         }
138                 }
139                 cm.setMaxTotal(connPoolSize);
140
141                 this.httpClient = new DefaultHttpClient(cm);
142
143                 int timeoutInSec = restConfigurationInfo.getReadTimeoutInSec() == null ? 0 : restConfigurationInfo.getReadTimeoutInSec();
144                 int connectTimeoutInSec = restConfigurationInfo.getConnectTimeoutInSec() == null ? DEFAULT_CONNECT_TIMEOUT : restConfigurationInfo.getConnectTimeoutInSec();
145                 HttpParams params = new BasicHttpParams();
146                 params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutInSec * 1000);
147                 params.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeoutInSec * 1000);
148
149                 this.httpClient.setParams(params);
150
151                 Boolean ignoreCertificateObj = restConfigurationInfo.getIgnoreCertificate();
152                 boolean ignoreCertificate = false;
153                 if (ignoreCertificateObj != null) {
154                         ignoreCertificate = ignoreCertificateObj.booleanValue();
155                 }
156                 if (ignoreCertificate == true) {
157
158                         this.sslFactory = createSSLSocketFactory();
159
160                         Scheme scheme = new Scheme("https", 9443, sslFactory);
161                         this.httpClient.getConnectionManager().getSchemeRegistry().register(scheme);
162                 }
163
164                 // addKeepAlive();
165
166                 this.cm = cm;
167         }
168
169         private void addKeepAlive() {
170
171                 this.httpClient.setReuseStrategy(new ConnectionReuseStrategy() {
172
173                         public boolean keepAlive(HttpResponse response, HttpContext context) {
174                                 // TODO Auto-generated method stub
175                                 return true;
176                         }
177
178                 });
179
180                 this.httpClient.setKeepAliveStrategy(new ConnectionKeepAliveStrategy() {
181
182                         public long getKeepAliveDuration(HttpResponse response, HttpContext context) {
183                                 log.debug("============ In getKeepAliveDuration ================= ");
184
185                                 HeaderIterator headerIterator = response.headerIterator(HTTP.CONN_KEEP_ALIVE);
186                                 if (headerIterator != null) {
187                                         HeaderElementIterator it = new BasicHeaderElementIterator(headerIterator);
188                                         while (it.hasNext()) {
189                                                 HeaderElement he = it.nextElement();
190                                                 String param = he.getName();
191                                                 String value = he.getValue();
192                                                 if (value != null && param.equalsIgnoreCase("timeout")) {
193                                                         try {
194                                                                 log.debug("============ In getKeepAliveDuration ================= {}", value);
195
196                                                                 return Long.parseLong(value) * 1000;
197                                                         } catch (NumberFormatException ignore) {
198                                                                 log.error("Failed parsing retrieved value of timeout header.", ignore);
199                                                         }
200                                                 }
201                                         }
202                                 }
203                                 return 20;
204                         }
205                 });
206
207         }
208
209         protected SSLSocketFactory createSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
210                 TrustManager easyTrustManager = new javax.net.ssl.X509TrustManager() {
211
212                         public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
213                                 // TODO Auto-generated method stub
214
215                         }
216
217                         public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
218                                 // TODO Auto-generated method stub
219
220                         }
221
222                         public java.security.cert.X509Certificate[] getAcceptedIssuers() {
223                                 // TODO Auto-generated method stub
224                                 return null;
225                         }
226
227                 };
228
229                 SSLContext sslContext = SSLContext.getInstance("TLS");
230                 sslContext.init(null, new TrustManager[] { easyTrustManager }, null);
231                 SSLSocketFactory sslFactory = new SSLSocketFactory(sslContext);
232
233                 sslFactory.setHostnameVerifier(new X509HostnameVerifier() {
234
235                         public boolean verify(String arg0, SSLSession arg1) {
236                                 // TODO Auto-generated method stub
237                                 return false;
238                         }
239
240                         public void verify(String host, SSLSocket ssl) throws IOException {
241                                 // TODO Auto-generated method stub
242
243                         }
244
245                         public void verify(String host, java.security.cert.X509Certificate cert) throws SSLException {
246                                 // TODO Auto-generated method stub
247
248                         }
249
250                         public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
251                                 // TODO Auto-generated method stub
252
253                         }
254
255                 });
256                 return sslFactory;
257         }
258
259         /**
260          * Executes RS-GET to perform FIND.
261          * 
262          * @param headerParameterKey
263          *            String
264          * @param headerParameterValue
265          *            String
266          * @return String
267          */
268         public RestResponse doGET(String uri, Properties headers) {
269                 logger.debug("Before executing uri {}. headers = {}", uri, headers);
270
271                 HttpGet httpGet = new HttpGet(uri);
272
273                 RestResponse response = execute(httpGet, headers);
274
275                 return response;
276         }
277
278         private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
279
280                 if (headers != null) {
281                         for (Entry<Object, Object> entry : headers.entrySet()) {
282                                 httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
283                         }
284                 }
285
286         }
287
288         public RestResponse doPOST(String uri, Properties headers, Object objectToCreate) {
289
290                 logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
291
292                 HttpPost httpPost = new HttpPost(uri);
293
294                 if (objectToCreate != null) {
295                         StringEntity se;
296                         try {
297                                 se = new StringEntity(objectToCreate.toString());
298
299                                 // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
300                                 // "application/json"));
301                                 httpPost.setEntity(se);
302                         } catch (UnsupportedEncodingException e) {
303                                 String msg = "Failed creating Entity for post request." + e.getMessage();
304                                 log.error(msg, e);
305                                 return null;
306                                 // throw new RestClientServiceExeption(msg);
307                         }
308                 }
309
310                 RestResponse response = execute(httpPost, headers);
311
312                 return response;
313
314         }
315
316         public RestResponse doPUT(String uri, Properties headers, Object objectToCreate) {
317
318                 logger.debug("Before executing uri {}. body = {}. headers = {}", uri, (objectToCreate != null ? objectToCreate.toString() : null), headers);
319
320                 HttpPut httpPut = new HttpPut(uri);
321
322                 if (objectToCreate != null) {
323                         StringEntity se;
324                         try {
325                                 se = new StringEntity(objectToCreate.toString());
326
327                                 // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
328                                 // "application/json"));
329                                 httpPut.setEntity(se);
330                         } catch (UnsupportedEncodingException e) {
331                                 String msg = "Failed creating Entity for post request." + e.getMessage();
332                                 // throw new RestClientServiceExeption(msg);
333                                 log.error(msg, e);
334                                 return null;
335                         }
336                 }
337
338                 RestResponse response = execute(httpPut, headers);
339
340                 return response;
341         }
342
343         private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
344
345                 String response = null;
346                 String statusDesc = null;
347                 int statusCode = HttpStatus.SC_OK;
348
349                 try {
350
351                         addHeadersToRequest(httpRequestBase, headers);
352
353                         HttpResponse httpResponse = this.httpClient.execute(httpRequestBase);
354
355                         statusCode = httpResponse.getStatusLine().getStatusCode();
356                         statusDesc = httpResponse.getStatusLine().getReasonPhrase();
357
358                         HttpEntity entity = httpResponse.getEntity();
359                         if (entity != null) {
360                                 response = EntityUtils.toString(entity);
361                         }
362                         // ensure the connection gets released to the manager
363                         EntityUtils.consume(entity);
364
365                         logResponse(response, httpRequestBase.getMethod());
366
367                 } catch (Exception exception) {
368                         httpRequestBase.abort();
369                         log.error("Failed to execute the {} request {}", httpRequestBase.getMethod(), httpRequestBase.getURI(), exception);
370                         // processAndThrowException(exception);
371                         return null;
372                 }
373
374                 RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
375
376                 if (logger.isDebugEnabled()) {
377                         URI uri = httpRequestBase.getURI();
378                         String url = uri.toString();
379                         logger.debug("After executing uri {}. response = {}", url, restResponse);
380                 }
381
382                 return restResponse;
383         }
384
385         public RestResponse doDELETE(String uri, Properties headers) {
386
387                 if (logger.isDebugEnabled()) {
388                         logger.debug("Before executing uri {}. headers = {}", uri, headers);
389                 }
390
391                 HttpDelete httpDelete = new HttpDelete(uri);
392
393                 RestResponse restResponse = execute(httpDelete, headers);
394
395                 return restResponse;
396
397         }
398
399         /**
400          * This method print the JSON response from the REST Server
401          * 
402          * @param response
403          *            the JSON response from the REST server
404          * @param method
405          *            name of method
406          */
407         private void logResponse(String response, String method) {
408                 logger.debug("{} response = {}", method, response);
409         }
410
411         /**
412          * Exception during client invocation usually it happens when status code starting with 400 or 500 is returned
413          * 
414          * @param exception
415          *            Exception
416          * @throws RSClientServiceExeption
417          */
418         private void processAndThrowException(Exception exception) throws RestClientServiceExeption {
419
420                 logger.debug("\n------------------------");
421                 logger.debug("FAILURE: {}", exception.getMessage());
422
423                 throw new RestClientServiceExeption(exception);
424
425         }
426
427 }