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.openecomp.sdc.be.dao.rest;
23 import java.io.IOException;
24 import java.io.InputStream;
25 import java.util.Map.Entry;
26 import java.util.Properties;
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;
49 public class HttpRestClient {
51 public final static int DEFAULT_CONNECTION_POOL_SIZE = 10;
53 public final static int DEFAULT_READ_TIMEOUT_IN_SEC = 30;
55 public final static int DEFAULT_CONNECT_TIMEOUT = 30;
57 public final static int DEFAULT_SOCKET_TIMEOUT = 30;
59 private CloseableHttpClient httpClient = null;
61 private PoolingHttpClientConnectionManager cm = null;
63 private static Logger logger = LoggerFactory.getLogger(HttpRestClient.class.getName());
65 private RestResponse errorRestResponse = new RestResponse("internal server error", null, 500);
66 private RestResponseAsByteArray errorRestResponseAsByteArray = new RestResponseAsByteArray(
67 "internal server error".getBytes(), null, 500);
69 boolean isInitialized = false;
71 // public static void main(String[] argv) {
73 // RestClientService restClientService =
74 // RestClientServiceFactory.createHttpRestClientService(new
75 // RestConfigurationInfo());
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\" }";
84 // // jsonStr = " <note>dfd</note>";
86 // Properties headers = new Properties();
87 // headers.put("Content-type", "application/json");
88 // headers.put("Accept", "*/*");
90 // // RestResponse restResponse = restClientService.doPOST(uriCreateCell,
93 // RestResponse restResponse = restClientService.doPUT(uriCreateCell,
94 // headers, jsonUpdateStr);
96 // System.out.println(restResponse);
99 // } catch (RestClientServiceExeption e) {
100 // e.printStackTrace();
105 public HttpRestClient() {
107 isInitialized = init(new RestConfigurationInfo());
110 public HttpRestClient(RestConfigurationInfo restConfigurationInfo) {
112 isInitialized = init(restConfigurationInfo);
115 public boolean init(RestConfigurationInfo restConfigurationInfo) {
117 logger.debug("create HttpRestClient: restConfigurationInfo= {}", restConfigurationInfo);
118 boolean result = false;
119 createHttpClient(restConfigurationInfo);
122 logger.debug("Finish creating HttpRestClient. Result is {}", result);
126 public void destroy() {
130 logger.debug("Http client closed");
131 } catch (Exception e) {
132 logger.trace("Failed to close http client", e);
137 private void createHttpClient(RestConfigurationInfo restConfigurationInfo) {
138 // throws KeyManagementException, NoSuchAlgorithmException {
140 PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
142 int connPoolSize = getConnectionPoolSize(restConfigurationInfo);
143 connManager.setMaxTotal(connPoolSize);
144 connManager.setDefaultMaxPerRoute(10);
145 connManager.setValidateAfterInactivity(15000);
147 // Create common default configuration
148 int socketTimeout = getTimeout(restConfigurationInfo.getSocketTimeoutInSec(), DEFAULT_SOCKET_TIMEOUT);
150 int connectTimeoutInSec = getTimeout(restConfigurationInfo.getConnectTimeoutInSec(), DEFAULT_CONNECT_TIMEOUT);
152 int readTimeOut = getTimeout(restConfigurationInfo.getReadTimeoutInSec(), DEFAULT_READ_TIMEOUT_IN_SEC);
154 RequestConfig clientConfig = RequestConfig.custom().setConnectTimeout(connectTimeoutInSec)
155 .setSocketTimeout(socketTimeout).setConnectionRequestTimeout(readTimeOut).build();
157 this.cm = connManager;
159 this.httpClient = HttpClients.custom().setDefaultRequestConfig(clientConfig).setConnectionManager(connManager)
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;
176 private int getTimeout(Integer value, Integer defaultValue) {
178 int defaultTimeout = defaultValue != null ? defaultValue.intValue() * 1000 : 0;
180 int timeout = defaultTimeout;
183 timeout = defaultValue.intValue() * 1000;
185 timeout = defaultTimeout;
193 * Executes RS-GET to perform FIND.
195 * @param headerParameterKey
197 * @param headerParameterValue
201 public RestResponse doGET(String uri, Properties headers) {
203 logger.debug("Before executing uri {}. headers = {}", uri, headers);
205 HttpGet httpGet = new HttpGet(uri);
207 RestResponse response = execute(httpGet, headers);
212 public RestResponse doPUT(String uri, Properties headers, String body) {
214 logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
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);
224 public RestResponse doPOST(String uri, Properties headers, String body) {
226 logger.debug("Before executing uri {}. headers = {}.body = {}", uri, headers, body);
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);
236 public RestResponseAsByteArray doGetAsByteArray(String uri, Properties headers) {
238 logger.debug("Before executing uri {}. headers = {}", uri, headers);
240 HttpGet httpGet = new HttpGet(uri);
242 RestResponseAsByteArray response = executeAndReturnByteArray(httpGet, headers);
247 private void addHeadersToRequest(HttpRequestBase httpRequestBase, Properties headers) {
249 if (headers != null) {
250 for (Entry<Object, Object> entry : headers.entrySet()) {
251 httpRequestBase.addHeader(entry.getKey().toString(), entry.getValue().toString());
257 private RestResponse execute(HttpRequestBase httpRequestBase, Properties headers) {
259 RestResponse restResponse = null;
261 CloseableHttpResponse httpResponse = null;
265 addHeadersToRequest(httpRequestBase, headers);
267 httpResponse = this.httpClient.execute(httpRequestBase);
269 restResponse = buildRestResponseFromResult(httpResponse);
271 logger.debug("After executing uri {}. response = {}", httpRequestBase.getURI().toString(), restResponse);
273 } catch (Exception exception) {
274 httpRequestBase.abort();
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;
282 // ensure the connection gets released to the manager
283 releaseResource(httpResponse);
289 private RestResponse buildRestResponseFromResult(CloseableHttpResponse httpResponse) throws IOException {
291 int statusCode = httpResponse.getStatusLine().getStatusCode();
292 String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
294 HttpEntity entity = httpResponse.getEntity();
295 String response = null;
296 if (entity != null) {
297 response = EntityUtils.toString(entity);
300 RestResponse restResponse = new RestResponse(response, statusDesc, statusCode);
305 private RestResponseAsByteArray buildRestResponseByteArrayFromResult(CloseableHttpResponse httpResponse)
308 int statusCode = httpResponse.getStatusLine().getStatusCode();
309 String statusDesc = httpResponse.getStatusLine().getReasonPhrase();
311 HttpEntity entity = httpResponse.getEntity();
313 byte[] response = null;
314 if (entity != null) {
315 InputStream content = entity.getContent();
316 if (content != null) {
317 response = IOUtils.toByteArray(content);
321 RestResponseAsByteArray restResponse = new RestResponseAsByteArray(response, statusDesc, statusCode);
326 private RestResponseAsByteArray executeAndReturnByteArray(HttpRequestBase httpRequestBase, Properties headers) {
328 RestResponseAsByteArray restResponse = null;
330 CloseableHttpResponse httpResponse = null;
334 addHeadersToRequest(httpRequestBase, headers);
336 httpResponse = this.httpClient.execute(httpRequestBase);
338 restResponse = buildRestResponseByteArrayFromResult(httpResponse);
340 if (restResponse != null) {
341 logger.debug("After executing uri {}. Response: {}", httpRequestBase.getURI().toString(), restResponse.toPrettyString());
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;
353 // ensure the connection gets released to the manager
354 releaseResource(httpResponse);
361 * This method print the JSON response from the REST Server
364 * the JSON response from the REST server
368 private void logResponse(String response, String method) {
369 logger.trace("{} response = {}", method, response);
372 private void releaseResource(CloseableHttpResponse response) {
373 if (response != null) {
375 HttpEntity entity = response.getEntity();
376 if (entity != null) {
377 EntityUtils.consume(entity);
380 } catch (Exception e) {
381 logger.error("failed to close connection exception", e);
386 public boolean isInitialized() {
387 return isInitialized;