Fix for radio buttons
[sdc.git] / catalog-dao / src / main / java / org / openecomp / sdc / be / dao / rest / HttpRestClient.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.be.dao.rest;
22
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Map.Entry;
26 import java.util.Properties;
27
28 import org.apache.commons.io.IOUtils;
29 import org.apache.http.HttpEntity;
30 import org.apache.http.client.config.RequestConfig;
31 import org.apache.http.client.methods.CloseableHttpResponse;
32 import org.apache.http.client.methods.HttpGet;
33 import org.apache.http.client.methods.HttpPost;
34 import org.apache.http.client.methods.HttpPut;
35 import org.apache.http.client.methods.HttpRequestBase;
36 import org.apache.http.entity.ContentType;
37 import org.apache.http.entity.StringEntity;
38 import org.apache.http.impl.client.CloseableHttpClient;
39 import org.apache.http.impl.client.HttpClients;
40 import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
41 import org.apache.http.util.EntityUtils;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
44 import org.openecomp.sdc.common.rest.api.RestResponse;
45 import org.openecomp.sdc.common.rest.api.RestResponseAsByteArray;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 public class HttpRestClient {
50
51         public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
52
53         public final static int DEFAULT_READ_TIMEOUT_IN_SEC = 30;
54
55         public final static int DEFAULT_CONNECT_TIMEOUT = 30;
56
57         public final static int DEFAULT_SOCKET_TIMEOUT = 30;
58
59         private CloseableHttpClient httpClient = null;
60
61         private PoolingHttpClientConnectionManager cm = null;
62
63         private static Logger logger = LoggerFactory.getLogger(HttpRestClient.class.getName());
64
65         private RestResponse errorRestResponse = new RestResponse("internal server error", null, 500);
66         private RestResponseAsByteArray errorRestResponseAsByteArray = new RestResponseAsByteArray(
67                         "internal server error".getBytes(), null, 500);
68
69         boolean isInitialized = false;
70
71         // public static void main(String[] argv) {
72         // try {
73         // RestClientService restClientService =
74         // RestClientServiceFactory.createHttpRestClientService(new
75         // RestConfigurationInfo());
76         //
77         // String uriCreateCell =
78         // "http://172.20.37.245:9082/topology/management/cell/update";
79         // String jsonStr = " { \"cellName\" : \"mycell118\" }";
80         // String jsonUpdateStr =
81         // " { \"cellName\" : \"mycell118\", \"hostName\" : \"myhost333\" }";
82         //
83         //
84         // // jsonStr = " <note>dfd</note>";
85         //
86         // Properties headers = new Properties();
87         // headers.put("Content-type", "application/json");
88         // headers.put("Accept", "*/*");
89         //
90         // // RestResponse restResponse = restClientService.doPOST(uriCreateCell,
91         // headers, jsonStr);
92         //
93         // RestResponse restResponse = restClientService.doPUT(uriCreateCell,
94         // headers, jsonUpdateStr);
95         //
96         // System.out.println(restResponse);
97         //
98         //
99         // } catch (RestClientServiceExeption e) {
100         // e.printStackTrace();
101         // }
102         //
103         // }
104
105         public HttpRestClient() {
106                 super();
107                 isInitialized = init(new RestConfigurationInfo());
108         }
109
110         public HttpRestClient(RestConfigurationInfo restConfigurationInfo) {
111                 super();
112                 isInitialized = init(restConfigurationInfo);
113         }
114
115         public boolean init(RestConfigurationInfo restConfigurationInfo) {
116
117                 logger.debug("create HttpRestClient: restConfigurationInfo= {}", restConfigurationInfo);
118                 boolean result = false;
119                 createHttpClient(restConfigurationInfo);
120                 result = true;
121                 
122                 logger.debug("Finish creating HttpRestClient. Result is {}", result);
123                 return result;
124         }
125
126         public void destroy() {
127
128                 try {
129                         httpClient.close();
130                         logger.debug("Http client closed");
131                 } catch (Exception e) {
132                         logger.trace("Failed to close http client", e);
133                 }
134
135         }
136
137         private void createHttpClient(RestConfigurationInfo restConfigurationInfo) {
138                 // throws KeyManagementException, NoSuchAlgorithmException {
139
140                 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
141
142                 int connPoolSize = getConnectionPoolSize(restConfigurationInfo);
143                 connManager.setMaxTotal(connPoolSize);
144                 connManager.setDefaultMaxPerRoute(10);
145                 connManager.setValidateAfterInactivity(15000);
146
147                 // Create common default configuration
148                 int socketTimeout = getTimeout(restConfigurationInfo.getSocketTimeoutInSec(), DEFAULT_SOCKET_TIMEOUT);
149
150                 int connectTimeoutInSec = getTimeout(restConfigurationInfo.getConnectTimeoutInSec(), DEFAULT_CONNECT_TIMEOUT);
151
152                 int readTimeOut = getTimeout(restConfigurationInfo.getReadTimeoutInSec(), DEFAULT_READ_TIMEOUT_IN_SEC);
153
154                 RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(connectTimeoutInSec)
155                                 .setSocketTimeout(socketTimeout).setConnectionRequestTimeout(readTimeOut).build();
156
157                 this.cm = connManager;
158
159                 this.httpClient = HttpClients.custom().setDefaultRequestConfig(clientConfig).setConnectionManager(connManager)
160                                 .build();
161
162         }
163
164         private int getConnectionPoolSize(RestConfigurationInfo restConfigurationInfo) {
165                 Integer connPoolSizeObj = restConfigurationInfo.getConnectionPoolSize();
166                 int connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
167                 if (connPoolSizeObj != null) {
168                         connPoolSize = connPoolSizeObj.intValue();
169                         if (connPoolSize <= 0) {
170                                 connPoolSize = DEFAULT_CONNECTION_POOL_SIZE;
171                         }
172                 }
173                 return connPoolSize;
174         }
175
176         private int getTimeout(Integer value, Integer defaultValue) {
177
178                 int defaultTimeout = defaultValue != null ? defaultValue.intValue() * 1000 : 0;
179
180                 int timeout = defaultTimeout;
181
182                 if (value != null) {
183                         timeout = defaultValue.intValue() * 1000;
184                         if (timeout <= 0) {
185                                 timeout = defaultTimeout;
186                         }
187                 }
188
189                 return timeout;
190         }
191
192         /**
193          * Executes RS-GET to perform FIND.
194          * 
195          * @param headerParameterKey
196          *            String
197          * @param headerParameterValue
198          *            String
199          * @return String
200          */
201         public RestResponse doGET(String uri, Properties headers) {
202
203                 logger.debug("Before executing uri {}. headers = {}", uri, headers);
204
205                 HttpGet httpGet = new HttpGet(uri);
206
207                 RestResponse response = execute(httpGet, headers);
208
209                 return response;
210         }
211
212         public RestResponse doPUT(String uri, Properties headers, String body) {
213
214                 logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
215
216                 HttpPut httpPut = new HttpPut(uri);
217                 StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
218                 httpPut.setEntity(data);
219                 RestResponse response = execute(httpPut, headers);
220
221                 return response;
222         }
223
224         public RestResponse doPOST(String uri, Properties headers, String body) {
225
226                 logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
227
228                 HttpPost httpPost = new HttpPost(uri);
229                 StringEntity data = new StringEntity(body, ContentType.APPLICATION_JSON);
230                 httpPost.setEntity(data);
231                 RestResponse response = execute(httpPost, headers);
232
233                 return response;
234         }
235
236         public RestResponseAsByteArray doGetAsByteArray(String uri, Properties headers) {
237
238                 logger.debug("Before executing uri {}. headers = {}", uri, headers);
239
240                 HttpGet httpGet = new HttpGet(uri);
241
242                 RestResponseAsByteArray response = executeAndReturnByteArray(httpGet, headers);
243
244                 return response;
245         }
246
247         private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
248
249                 if (headers != null) {
250                         for (Entry<Object, Object> entry : headers.entrySet()) {
251                                 httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
252                         }
253                 }
254
255         }
256
257         private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
258
259                 RestResponse restResponse = null;
260
261                 CloseableHttpResponse httpResponse = null;
262
263                 try {
264
265                         addHeadersToRequest(httpRequestBase, headers);
266
267                         httpResponse = this.httpClient.execute(httpRequestBase);
268
269                         restResponse = buildRestResponseFromResult(httpResponse);
270
271                         logger.debug("After executing uri {}. response = {}", httpRequestBase.getURI().toString(), restResponse);
272
273                 } catch (Exception exception) {
274                         httpRequestBase.abort();
275
276                         String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
277                                         + httpRequestBase.getMethod() + ")";
278                         BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
279                                         ErrorSeverity.ERROR);
280                         restResponse = errorRestResponse;
281                 } finally {
282                         // ensure the connection gets released to the manager
283                         releaseResource(httpResponse);
284                 }
285
286                 return restResponse;
287         }
288
289         private RestResponse buildRestResponseFromResult(CloseableHttpResponse httpResponse) throws IOException {
290
291                 int statusCode = httpResponse.getStatusLine().getStatusCode();
292                 String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
293
294                 HttpEntity entity = httpResponse.getEntity();
295                 String response = null;
296                 if (entity != null) {
297                         response = EntityUtils.toString(entity);
298                 }
299
300                 RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
301
302                 return restResponse;
303         }
304
305         private RestResponseAsByteArray buildRestResponseByteArrayFromResult(CloseableHttpResponse httpResponse)
306                         throws IOException {
307
308                 int statusCode = httpResponse.getStatusLine().getStatusCode();
309                 String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
310
311                 HttpEntity entity = httpResponse.getEntity();
312
313                 byte[] response = null;
314                 if (entity != null) {
315                         InputStream content = entity.getContent();
316                         if (content != null) {
317                                 response = IOUtils.toByteArray(content);
318                         }
319                 }
320
321                 RestResponseAsByteArray restResponse = new RestResponseAsByteArray(response, statusDesc, statusCode);
322
323                 return restResponse;
324         }
325
326         private RestResponseAsByteArray executeAndReturnByteArray(HttpRequestBase httpRequestBase, Properties headers) {
327
328                 RestResponseAsByteArray restResponse = null;
329
330                 CloseableHttpResponse httpResponse = null;
331
332                 try {
333
334                         addHeadersToRequest(httpRequestBase, headers);
335
336                         httpResponse = this.httpClient.execute(httpRequestBase);
337
338                         restResponse = buildRestResponseByteArrayFromResult(httpResponse);
339
340                         if (restResponse != null) {
341                                 logger.debug("After executing uri {}. Response: {}", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
342                         }
343
344                 } catch (Exception exception) {
345                         httpRequestBase.abort();
346                         String description = "Failed executing http request " + httpRequestBase.getURI().toString() + "("
347                                         + httpRequestBase.getMethod() + ")";
348                         BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description,
349                                         ErrorSeverity.ERROR);
350                         logger.debug(description, exception);
351                         restResponse = errorRestResponseAsByteArray;
352                 } finally {
353                         // ensure the connection gets released to the manager
354                         releaseResource(httpResponse);
355                 }
356
357                 return restResponse;
358         }
359
360         /**
361          * This method print the JSON response from the REST Server
362          * 
363          * @param response
364          *            the JSON response from the REST server
365          * @param method
366          *            name of method
367          */
368         private void logResponse(String response, String method) {
369                 logger.trace("{} response = {}", method, response);
370         }
371
372         private void releaseResource(CloseableHttpResponse response) {
373                 if (response != null) {
374                         try {
375                                 HttpEntity entity = response.getEntity();
376                                 if (entity != null) {
377                                         EntityUtils.consume(entity);
378                                 }
379                                 response.close();
380                         } catch (Exception e) {
381                                 logger.error("failed to close connection exception", e);
382                         }
383                 }
384         }
385
386         public boolean isInitialized() {
387                 return isInitialized;
388         }
389
390 }