fixing warnings from checkstyle in common-app-api
[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.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;
49
50 import java.io.IOException;
51 import java.net.URI;
52 import java.util.Properties;
53
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;
58
59     private final CloseableHttpClient client;
60     private final HttpClientConfigImmutable configImmutable;
61
62     HttpClient(CloseableHttpClient client, HttpClientConfigImmutable configImmutable) {
63         this.client = client;
64         this.configImmutable = configImmutable;
65     }
66
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);
70     }
71
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);
76     }
77
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);
82     }
83
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);
88     }
89
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);
93     }
94
95     void close() {
96         try {
97             client.close();
98         } catch (IOException e) {
99             LOGGER.debug("Close http client failed with exception ", e);
100         }
101     }
102
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);
106         }
107
108         if (headers != null) {
109             headers.forEach((k, v) -> request.addHeader(k.toString(), v.toString()));
110         }
111
112         HttpClientContext httpClientContext = null;
113         if (request.getHeaders(HttpHeaders.AUTHORIZATION).length == 0) {
114             httpClientContext = createHttpContext(request.getURI());
115         }
116
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);
124
125             throw new HttpExecuteException(description, e);
126         }
127     }
128
129     private HttpClientContext createHttpContext(URI uri) {
130         if (StringUtils.isEmpty(configImmutable.getBasicAuthUserName()) || StringUtils.isEmpty(configImmutable.getBasicAuthPassword())) {
131             return null;
132         }
133
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()));
138
139         HttpClientContext localContext = HttpClientContext.create();
140         localContext.setCredentialsProvider(credentialsProvider);
141
142         AuthCache authCache = new BasicAuthCache();
143         authCache.put(new HttpHost(uri.getHost(), port), (AuthScheme) new BasicScheme());
144         localContext.setAuthCache(authCache);
145
146         return localContext;
147     }
148
149     private int getPort(URI uri) {
150         int port = uri.getPort();
151         if (port < 0) {
152             if (Constants.HTTPS.equals(uri.getScheme())) {
153                 port = HTTPS_PORT;
154             } else if (Constants.HTTP.equals(uri.getScheme())) {
155                 port = HTTP_PORT;
156             } else {
157                 port = AuthScope.ANY_PORT;
158                 LOGGER.debug("Protocol \"{}\" is not supported, set port to {}", uri.getScheme(), port);
159             }
160         }
161         return port;
162     }
163 }