Catalog alignment
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / http / client / api / HttpClient.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
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.common.http.client.api;
22
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;
43
44 import java.io.IOException;
45 import java.net.URI;
46 import java.util.Properties;
47
48 public class HttpClient {
49     private static final Logger logger = Logger.getLogger(HttpClient.class.getName());
50     
51     private final CloseableHttpClient client;
52     private final HttpClientConfigImmutable configImmutable;
53     
54     public HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
55         this.client = client;
56         this.configImmutable = configImmutable; 
57     }
58     
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);
62     }
63
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);
68     }
69
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);
74     }
75
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);
80     }
81
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);
85     }
86     
87     void close() {
88         try {
89             client.close();
90         }
91         catch (IOException e) {
92             logger.debug("Close http client failed with exception ", e);
93         }
94     }
95     
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);
99         }
100
101         if (headers != null) {
102             headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
103         }
104
105         HttpClientContext httpClientContext = null;
106         if(request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
107             httpClientContext = createHttpContext(request.getURI());
108         }
109
110         logger.debug("Execute request {}", request.getRequestLine());
111         try (CloseableHttpResponse response = client.execute(request, httpClientContext)) {
112             return responseBuilder.apply(response);
113         }
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);
118
119             throw new HttpExecuteException(description, e);
120         } 
121     }
122
123     private HttpClientContext createHttpContext(URI uri) {
124         if(StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
125             return null;
126         }
127
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()));
132
133         HttpClientContext localContext = HttpClientContext.create();
134         localContext.setCredentialsProvider(credentialsProvider);
135
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);
140
141         return localContext;
142     }
143
144     private int getPort(URI uri) {
145         int port = uri.getPort(); 
146         if(port < 0) {
147             if(Constants.HTTPS.equals(uri.getScheme())) {
148                 port = 443;
149             }
150             else
151             if (Constants.HTTP.equals(uri.getScheme())) {
152                 port = 80;
153             }
154             else {
155                 port = AuthScope.ANY_PORT;
156                 logger.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);
157             }
158         }
159         return port;
160     }
161 }