2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2019 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.common.http.client.api;
23 import org.apache.commons.lang3.StringUtils;
24 import org.apache.http.HttpEntity;
25 import org.apache.http.HttpHeaders;
26 import org.apache.http.HttpHost;
27 import org.apache.http.auth.AuthScheme;
28 import org.apache.http.auth.AuthScope;
29 import org.apache.http.auth.UsernamePasswordCredentials;
30 import org.apache.http.client.AuthCache;
31 import org.apache.http.client.CredentialsProvider;
32 import org.apache.http.client.methods.CloseableHttpResponse;
33 import org.apache.http.client.methods.HttpDelete;
34 import org.apache.http.client.methods.HttpGet;
35 import org.apache.http.client.methods.HttpPatch;
36 import org.apache.http.client.methods.HttpPost;
37 import org.apache.http.client.methods.HttpPut;
38 import org.apache.http.client.methods.HttpRequestBase;
39 import org.apache.http.client.protocol.HttpClientContext;
40 import org.apache.http.impl.auth.BasicScheme;
41 import org.apache.http.impl.client.BasicAuthCache;
42 import org.apache.http.impl.client.BasicCredentialsProvider;
43 import org.apache.http.impl.client.CloseableHttpClient;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
46 import org.openecomp.sdc.common.api.Constants;
47 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
48 import org.openecomp.sdc.common.log.wrappers.Logger;
50 import java.io.IOException;
52 import java.util.Properties;
54 public class HttpClient {
55 private static final Logger LOGGER = Logger.getLogger(HttpClient.class.getName());
56 public static final int HTTPS_PORT = 443;
57 public static final int HTTP_PORT = 80;
59 private final CloseableHttpClient client;
60 private final HttpClientConfigImmutable configImmutable;
62 HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
64 this.configImmutable = configImmutable;
67 <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
68 HttpGet httpGet = new HttpGet(url);
69 return execute(httpGet, headers, responseBuilder);
72 <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
73 HttpPut httpPut = new HttpPut(url);
74 httpPut.setEntity(entity);
75 return execute(httpPut, headers, responseBuilder);
78 <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
79 HttpPost httpPost = new HttpPost(url);
80 httpPost.setEntity(entity);
81 return execute(httpPost, headers, responseBuilder);
84 <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
85 HttpPatch httpPatch = new HttpPatch(url);
86 httpPatch.setEntity(entity);
87 return execute(httpPatch, headers, responseBuilder);
90 <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
91 HttpDelete httpDelete = new HttpDelete(url);
92 return execute(httpDelete, headers, responseBuilder);
98 } catch (IOException e) {
99 LOGGER.debug("Close http client failed with exception ", e);
103 private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
104 if (configImmutable.getHeaders() != null) {
105 configImmutable.getHeaders().forEach(request::addHeader);
108 if (headers != null) {
109 headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
112 HttpClientContext httpClientContext = null;
113 if (request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
114 httpClientContext = createHttpContext(request.getURI());
117 LOGGER.debug("Execute request {}", request.getRequestLine());
118 try (CloseableHttpResponse response = client.execute(request, httpClientContext)) {
119 return responseBuilder.apply(response);
120 } catch (Exception e) {
121 String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage());
122 BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR);
123 LOGGER.debug("{}: ", description, e);
125 throw new HttpExecuteException(description, e);
129 private HttpClientContext createHttpContext(URI uri) {
130 if (StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
134 CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
135 int port = getPort(uri);
136 credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port),
137 new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword()));
139 HttpClientContext localContext = HttpClientContext.create();
140 localContext.setCredentialsProvider(credentialsProvider);
142 AuthCache authCache = new BasicAuthCache();
143 authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme());
144 localContext.setAuthCache(authCache);
149 private int getPort(URI uri) {
150 int port = uri.getPort();
152 if (Constants.HTTPS.equals(uri.getScheme())) {
154 } else if (Constants.HTTP.equals(uri.getScheme())) {
157 port = AuthScope.ANY_PORT;
158 LOGGER.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);