d6e18d60dbc582e6ed621758066876e0278cd9fe
[institute/sw-backend.git] /
1 package com.supwisdom.institute.backend.thirdparty.poa;
2
3 import lombok.experimental.UtilityClass;
4 import lombok.extern.slf4j.Slf4j;
5
6 import org.apache.commons.codec.binary.Base64;
7 import org.apache.commons.lang3.StringUtils;
8 import org.apache.http.HttpHeaders;
9 import org.apache.http.HttpResponse;
10 import org.apache.http.client.HttpClient;
11 import org.apache.http.client.methods.CloseableHttpResponse;
12 import org.apache.http.client.methods.HttpDelete;
13 import org.apache.http.client.methods.HttpGet;
14 import org.apache.http.client.methods.HttpPost;
15 import org.apache.http.client.methods.HttpUriRequest;
16 import org.apache.http.client.utils.URIBuilder;
17 import org.apache.http.entity.StringEntity;
18 import org.apache.http.impl.client.HttpClientBuilder;
19
20 import java.io.IOException;
21 import java.net.URI;
22 import java.net.URISyntaxException;
23 import java.nio.charset.StandardCharsets;
24 import java.util.HashMap;
25 import java.util.LinkedHashMap;
26 import java.util.Map;
27
28 /**
29  * This is {@link HttpUtils}.
30  *
31  * @author Misagh Moayyed
32  * @since 5.2.0
33  */
34 @Slf4j
35 @UtilityClass
36 public class HttpUtils {
37
38     private static final int MAX_CONNECTIONS = 200;
39     private static final int MAX_CONNECTIONS_PER_ROUTE = 20;
40
41     private static final HttpClient HTTP_CLIENT = HttpClientBuilder.create().setMaxConnTotal(MAX_CONNECTIONS)
42             .setMaxConnPerRoute(MAX_CONNECTIONS_PER_ROUTE).build();
43
44     /**
45      * Execute http response.
46      *
47      * @param url               the url
48      * @param method            the method
49      * @param basicAuthUsername the basic auth username
50      * @param basicAuthPassword the basic auth password
51      * @return the http response
52      */
53     public static HttpResponse execute(final String url, final String method,
54                                        final String basicAuthUsername,
55                                        final String basicAuthPassword) {
56         return execute(url, method, basicAuthUsername, basicAuthPassword, new HashMap<>(), new HashMap<>());
57     }
58
59     /**
60      * Execute http response.
61      *
62      * @param url               the url
63      * @param method            the method
64      * @param basicAuthUsername the basic auth username
65      * @param basicAuthPassword the basic auth password
66      * @param headers           the headers
67      * @return the http response
68      */
69     public static HttpResponse execute(final String url, final String method,
70                                        final String basicAuthUsername, final String basicAuthPassword,
71                                        final Map<String, Object> headers) {
72         return execute(url, method, basicAuthUsername, basicAuthPassword, new HashMap<>(), headers);
73     }
74
75     /**
76      * Execute http response.
77      *
78      * @param url    the url
79      * @param method the method
80      * @return the http response
81      */
82     public static HttpResponse execute(final String url, final String method) {
83         return execute(url, method, null, null, new HashMap<>(), new HashMap<>());
84     }
85     
86     /**
87      * Execute http response.
88      *
89      * @param url    the url
90      * @param method the method
91      * @return the http response
92      */
93     public static HttpResponse execute(final String url, final String method, final Map<String, Object> parameters, final Map<String, Object> headers) {
94         return execute(url, method, null, null, parameters, headers);
95     }
96
97     /**
98      * Execute http response.
99      *
100      * @param url               the url
101      * @param method            the method
102      * @param basicAuthUsername the basic auth username
103      * @param basicAuthPassword the basic auth password
104      * @param parameters        the parameters
105      * @param headers           the headers
106      * @return the http response
107      */
108     public static HttpResponse execute(final String url, final String method,
109                                        final String basicAuthUsername,
110                                        final String basicAuthPassword,
111                                        final Map<String, Object> parameters,
112                                        final Map<String, Object> headers) {
113         return execute(url, method, basicAuthUsername, basicAuthPassword, parameters, headers, null);
114     }
115
116     /**
117      * Execute http request and produce a response.
118      *
119      * @param url               the url
120      * @param method            the method
121      * @param basicAuthUsername the basic auth username
122      * @param basicAuthPassword the basic auth password
123      * @param parameters        the parameters
124      * @param headers           the headers
125      * @param entity            the entity
126      * @return the http response
127      */
128     public static HttpResponse execute(final String url, final String method,
129                                        final String basicAuthUsername,
130                                        final String basicAuthPassword,
131                                        final Map<String, Object> parameters,
132                                        final Map<String, Object> headers,
133                                        final String entity) {
134         try {
135             final URI uri = buildHttpUri(url, parameters);
136             final HttpUriRequest request;
137             switch (method.toLowerCase()) {
138                 case "post":
139                 case "put":
140                     request = new HttpPost(uri);
141                     if (StringUtils.isNotBlank(entity)) {
142                         final StringEntity stringEntity = new StringEntity(entity);
143                         ((HttpPost) request).setEntity(stringEntity);
144                     }
145                     break;
146                 case "delete":
147                     request = new HttpDelete(uri);
148                     break;
149                 case "get":
150                 default:
151                     request = new HttpGet(uri);
152                     break;
153             }
154             headers.forEach((k, v) -> request.addHeader(k, v.toString()));
155             prepareHttpRequest(request, basicAuthUsername, basicAuthPassword);
156             return HTTP_CLIENT.execute(request);
157         } catch (final Exception e) {
158             log.error(e.getMessage(), e);
159         }
160         return null;
161     }
162
163     /**
164      * Close the response.
165      *
166      * @param response the response to close
167      */
168     public static void close(final HttpResponse response) {
169         if (response != null) {
170             final CloseableHttpResponse closeableHttpResponse = (CloseableHttpResponse) response;
171             try {
172                 closeableHttpResponse.close();
173             } catch (final IOException e) {
174                 log.error(e.getMessage(), e);
175             }
176         }
177     }
178
179     /**
180      * Execute get http response.
181      *
182      * @param url               the url
183      * @param basicAuthUsername the basic auth username
184      * @param basicAuthPassword the basic auth password
185      * @param parameters        the parameters
186      * @return the http response
187      */
188     public static HttpResponse executeGet(final String url,
189                                           final String basicAuthUsername,
190                                           final String basicAuthPassword,
191                                           final Map<String, Object> parameters) {
192         try {
193             return executeGet(url, basicAuthUsername, basicAuthPassword, parameters, new HashMap<>());
194         } catch (final Exception e) {
195             log.error(e.getMessage(), e);
196         }
197         return null;
198     }
199
200     /**
201      * Execute get http response.
202      *
203      * @param url               the url
204      * @param basicAuthUsername the basic auth username
205      * @param basicAuthPassword the basic auth password
206      * @param parameters        the parameters
207      * @param headers           the headers
208      * @return the http response
209      */
210     public static HttpResponse executeGet(final String url,
211                                           final String basicAuthUsername,
212                                           final String basicAuthPassword,
213                                           final Map<String, Object> parameters,
214                                           final Map<String, Object> headers) {
215         try {
216             return execute(url, "GET", basicAuthUsername, basicAuthPassword, parameters, headers);
217         } catch (final Exception e) {
218             log.error(e.getMessage(), e);
219         }
220         return null;
221     }
222
223     /**
224      * Execute get http response.
225      *
226      * @param url        the url
227      * @param parameters the parameters
228      * @return the http response
229      */
230     public static HttpResponse executeGet(final String url,
231                                           final Map<String, Object> parameters) {
232         try {
233             return executeGet(url, null, null, parameters);
234         } catch (final Exception e) {
235             log.error(e.getMessage(), e);
236         }
237         return null;
238     }
239
240     /**
241      * Execute get http response.
242      *
243      * @param url the url
244      * @return the http response
245      */
246     public static HttpResponse executeGet(final String url) {
247         try {
248             return executeGet(url, null, null, new LinkedHashMap<>());
249         } catch (final Exception e) {
250             log.error(e.getMessage(), e);
251         }
252         return null;
253     }
254
255     /**
256      * Execute get http response.
257      *
258      * @param url               the url
259      * @param basicAuthUsername the basic auth username
260      * @param basicAuthPassword the basic auth password
261      * @return the http response
262      */
263     public static HttpResponse executeGet(final String url,
264                                           final String basicAuthUsername,
265                                           final String basicAuthPassword) {
266         try {
267             return executeGet(url, basicAuthUsername, basicAuthPassword, new HashMap<>());
268         } catch (final Exception e) {
269             log.error(e.getMessage(), e);
270         }
271         return null;
272     }
273
274     /**
275      * Execute post http response.
276      *
277      * @param url               the url
278      * @param basicAuthUsername the basic auth username
279      * @param basicAuthPassword the basic auth password
280      * @param jsonEntity        the json entity
281      * @return the http response
282      */
283     public static HttpResponse executePost(final String url,
284                                            final String basicAuthUsername,
285                                            final String basicAuthPassword,
286                                            final String jsonEntity) {
287         return executePost(url, basicAuthUsername, basicAuthPassword, jsonEntity, new HashMap<>());
288     }
289
290     /**
291      * Execute post http response.
292      *
293      * @param url        the url
294      * @param parameters the parameters
295      * @return the http response
296      */
297     public static HttpResponse executePost(final String url,
298                                            final Map<String, Object> parameters) {
299         return executePost(url, null, null, null, parameters);
300     }
301     
302     /**
303      * Execute post http response.
304      *
305      * @param url        the url
306      * @param jsonEntity the json entity
307      * @param parameters the parameters
308      * @return the http response
309      */
310     public static HttpResponse executePost(final String url,
311                                            final String jsonEntity,
312                                            final Map<String, Object> parameters) {
313         return executePost(url, null, null, jsonEntity, parameters);
314     }
315
316     /**
317      * Execute post http response.
318      *
319      * @param url               the url
320      * @param basicAuthUsername the basic auth username
321      * @param basicAuthPassword the basic auth password
322      * @param jsonEntity        the json entity
323      * @param parameters        the parameters
324      * @return the http response
325      */
326     public static HttpResponse executePost(final String url,
327                                            final String basicAuthUsername,
328                                            final String basicAuthPassword,
329                                            final String jsonEntity,
330                                            final Map<String, Object> parameters) {
331         try {
332             return execute(url, "POST", basicAuthUsername, basicAuthPassword, parameters, new HashMap<>(), jsonEntity);
333         } catch (final Exception e) {
334             log.error(e.getMessage(), e);
335         }
336         return null;
337     }
338
339     /**
340      * Prepare http request. Tries to set the authorization header
341      * in cases where the URL endpoint does not actually produce the header
342      * on its own.
343      *
344      * @param request           the request
345      * @param basicAuthUsername the basic auth username
346      * @param basicAuthPassword the basic auth password
347      */
348     private static void prepareHttpRequest(final HttpUriRequest request, final String basicAuthUsername,
349                                            final String basicAuthPassword) {
350         if (StringUtils.isNotBlank(basicAuthUsername) && StringUtils.isNotBlank(basicAuthPassword)) {
351             final String auth = encodeBase64(basicAuthUsername + ":" + basicAuthPassword);
352             request.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + auth);
353         }
354     }
355
356     private static URI buildHttpUri(final String url, final Map<String, Object> parameters) throws URISyntaxException {
357         final URIBuilder uriBuilder = new URIBuilder(url);
358         parameters.forEach((k, v) -> uriBuilder.addParameter(k, v.toString()));
359         return uriBuilder.build();
360     }
361
362     /**
363      * Create headers org . springframework . http . http headers.
364      *
365      * @param basicAuthUser     the basic auth user
366      * @param basicAuthPassword the basic auth password
367      * @return the org . springframework . http . http headers
368      */
369 //    public static org.springframework.http.HttpHeaders createBasicAuthHeaders(final String basicAuthUser, final String basicAuthPassword) {
370 //        final org.springframework.http.HttpHeaders acceptHeaders = new org.springframework.http.HttpHeaders();
371 //        acceptHeaders.setAccept(CollectionUtils.wrap(MediaType.APPLICATION_JSON));
372 //        if (StringUtils.isNotBlank(basicAuthUser) && StringUtils.isNotBlank(basicAuthPassword)) {
373 //            final String authorization = basicAuthUser + ':' + basicAuthPassword;
374 //            final String basic = encodeBase64(authorization.getBytes(Charset.forName("US-ASCII")));
375 //            acceptHeaders.set("Authorization", "Basic " + basic);
376 //        }
377 //        return acceptHeaders;
378 //    }
379     
380     
381     private static String encodeBase64(final String data) {
382       return Base64.encodeBase64String(data.getBytes(StandardCharsets.UTF_8));
383     }
384 }