re base code
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / http / client / api / HttpClient.java
1 package org.openecomp.sdc.common.http.client.api;
2
3 import org.apache.commons.lang3.StringUtils;
4 import org.apache.http.HttpEntity;
5 import org.apache.http.HttpHeaders;
6 import org.apache.http.HttpHost;
7 import org.apache.http.auth.AuthScheme;
8 import org.apache.http.auth.AuthScope;
9 import org.apache.http.auth.UsernamePasswordCredentials;
10 import org.apache.http.client.AuthCache;
11 import org.apache.http.client.CredentialsProvider;
12 import org.apache.http.client.methods.*;
13 import org.apache.http.client.protocol.HttpClientContext;
14 import org.apache.http.impl.auth.BasicScheme;
15 import org.apache.http.impl.client.BasicAuthCache;
16 import org.apache.http.impl.client.BasicCredentialsProvider;
17 import org.apache.http.impl.client.CloseableHttpClient;
18 import org.openecomp.sdc.be.config.BeEcompErrorManager;
19 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
20 import org.openecomp.sdc.common.api.Constants;
21 import org.openecomp.sdc.common.datastructure.FunctionalInterfaces.FunctionThrows;
22 import org.openecomp.sdc.common.log.wrappers.Logger;
23
24 import java.io.IOException;
25 import java.net.URI;
26 import java.util.Properties;
27
28 public class HttpClient {
29     private static final Logger logger = Logger.getLogger(HttpClient.class.getName());
30     
31     private final CloseableHttpClient client;
32     private final HttpClientConfigImmutable configImmutable;
33     
34     HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
35         this.client = client;
36         this.configImmutable = configImmutable; 
37     }
38     
39     <T> HttpResponse<T> get(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
40         HttpGet httpGet = new HttpGet(url);
41         return execute(httpGet, headers, responseBuilder);
42     }
43
44     <T> HttpResponse<T> put(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
45         HttpPut httpPut = new HttpPut(url);
46         httpPut.setEntity(entity);
47         return execute(httpPut, headers, responseBuilder);
48     }
49
50     <T> HttpResponse<T> post(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
51         HttpPost httpPost = new HttpPost(url);
52         httpPost.setEntity(entity);
53         return execute(httpPost, headers, responseBuilder);
54     }
55
56     <T> HttpResponse<T> patch(String url, Properties headers, HttpEntity entity, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
57         HttpPatch httpPatch = new HttpPatch(url);
58         httpPatch.setEntity(entity);
59         return execute(httpPatch, headers, responseBuilder);
60     }
61
62     <T> HttpResponse<T> delete(String url, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
63         HttpDelete httpDelete = new HttpDelete(url);
64         return execute(httpDelete, headers, responseBuilder);
65     }
66     
67     void close() {
68         try {
69             client.close();
70         }
71         catch (IOException e) {
72             logger.debug("Close http client failed with exception ", e);
73         }
74     }
75     
76     private <T> HttpResponse<T> execute(HttpRequestBase request, Properties headers, FunctionThrows<CloseableHttpResponse, HttpResponse<T>, Exception> responseBuilder) throws HttpExecuteException {
77         if(configImmutable.getHeaders() != null) {
78             configImmutable.getHeaders().forEach(request::addHeader);
79         }
80
81         if (headers != null) {
82             headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
83         }
84
85         HttpClientContext httpClientContext = null;
86         if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
87             httpClientContext = createHttpContext(request.getURI());
88         }
89
90         logger.debug("Execute request {}", request.getRequestLine());
91         try (CloseableHttpResponse response = client.execute(request, httpClientContext)) {
92             return responseBuilder.apply(response);
93         }
94         catch (Exception e) {
95             String description = String.format("Execute request %s failed with exception: %s", request.getRequestLine(), e.getMessage()); 
96             BeEcompErrorManager.getInstance().logInternalFlowError("ExecuteRestRequest", description, ErrorSeverity.ERROR);
97             logger.debug("{}: ",description, e);
98
99             throw new HttpExecuteException(description, e);
100         } 
101     }
102
103     private HttpClientContext createHttpContext(URI uri) {
104         if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
105             return null;
106         }
107
108         CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
109         int port = getPort(uri);
110         credentialsProvider.setCredentials(new AuthScope(uri.getHost(), port), 
111                 new UsernamePasswordCredentials(configImmutable.getBasicAuthUserName(), configImmutable.getBasicAuthPassword()));
112
113         HttpClientContext localContext = HttpClientContext.create();
114         localContext.setCredentialsProvider(credentialsProvider);
115
116         AuthCache authCache = new BasicAuthCache();
117         authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme());
118         localContext.setAuthCache(authCache);
119
120         return localContext;
121     }
122
123     private int getPort(URI uri) {
124         int port = uri.getPort(); 
125         if(port < 0) {
126             if(Constants.HTTPS.equals(uri.getScheme())) {
127                 port = 443;
128             }
129             else
130             if (Constants.HTTP.equals(uri.getScheme())) {
131                 port = 80;
132             }
133             else {
134                 port = AuthScope.ANY_PORT;
135                 logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);
136             }
137         }
138         return port;
139     }
140 }