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.*;
33 import org.apache.http.client.protocol.HttpClientContext;
34 import org.apache.http.impl.auth.BasicScheme;
35 import org.apache.http.impl.client.BasicAuthCache;
36 import org.apache.http.impl.client.BasicCredentialsProvider;
37 import org.apache.http.impl.client.CloseableHttpClient;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
40 import org.openecomp.sdc.common.api.Constants;
41 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
42 import org.openecomp.sdc.common.log.wrappers.Logger;
44 import java.io.IOException;
46 import java.util.Properties;
48 public class HttpClient {
49 private static final Logger logger = Logger.getLogger(HttpClient.class.getName());
51 private final CloseableHttpClient client;
52 private final HttpClientConfigImmutable configImmutable;
54 public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
56 this.configImmutable = configImmutable;
59 public <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
60 HttpGet httpGet = new HttpGet(url);
61 return execute(httpGet, headers, responseBuilder);
64 <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
65 HttpPut httpPut = new HttpPut(url);
66 httpPut.setEntity(entity);
67 return execute(httpPut, headers, responseBuilder);
70 <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
71 HttpPost httpPost = new HttpPost(url);
72 httpPost.setEntity(entity);
73 return execute(httpPost, headers, responseBuilder);
76 <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
77 HttpPatch httpPatch = new HttpPatch(url);
78 httpPatch.setEntity(entity);
79 return execute(httpPatch, headers, responseBuilder);
82 <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
83 HttpDelete httpDelete = new HttpDelete(url);
84 return execute(httpDelete, headers, responseBuilder);
91 catch (IOException e) {
92 logger.debug("Close http client failed with exception ", e);
96 private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
97 if(configImmutable.getHeaders() != null) {
98 configImmutable.getHeaders().forEach(request::addHeader);
101 if (headers != null) {
102 headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
105 HttpClientContext httpClientContext = null;
106 if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
107 httpClientContext = createHttpContext(request.getURI());
110 logger.debug("Execute request {}", request.getRequestLine());
111 try (CloseableHttpResponse response = client.execute(request, httpClientContext)) {
112 return responseBuilder.apply(response);
114 catch (Exception e) {
115 String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage());
116 BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR);
117 logger.debug("{}: ",description, e);
119 throw new HttpExecuteException(description, e);
123 private HttpClientContext createHttpContext(URI uri) {
124 if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
128 CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
129 int port = getPort(uri);
130 credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port),
131 new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword()));
133 HttpClientContext localContext = HttpClientContext.create();
134 localContext.setCredentialsProvider(credentialsProvider);
136 AuthCache authCache = new BasicAuthCache();
137 HttpHost target = new HttpHost(uri.getHost(), port, "https");
138 authCache.put(target, (AuthScheme) new BasicScheme());
139 localContext.setAuthCache(authCache);
144 private int getPort(URI uri) {
145 int port = uri.getPort();
147 if(Constants.HTTPS.equals(uri.getScheme())) {
151 if (Constants.HTTP.equals(uri.getScheme())) {
155 port = AuthScope.ANY_PORT;
156 logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);