added svcapi ui and camunda code
[it/otf.git] / otf-camunda / src / main / java / org / oran / otf / common / utility / http / RequestUtility.java
1 /*  Copyright (c) 2019 AT&T Intellectual Property.                             #\r
2 #                                                                              #\r
3 #   Licensed under the Apache License, Version 2.0 (the "License");            #\r
4 #   you may not use this file except in compliance with the License.           #\r
5 #   You may obtain a copy of the License at                                    #\r
6 #                                                                              #\r
7 #       http://www.apache.org/licenses/LICENSE-2.0                             #\r
8 #                                                                              #\r
9 #   Unless required by applicable law or agreed to in writing, software        #\r
10 #   distributed under the License is distributed on an "AS IS" BASIS,          #\r
11 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   #\r
12 #   See the License for the specific language governing permissions and        #\r
13 #   limitations under the License.                                             #\r
14 ##############################################################################*/\r
15 \r
16 \r
17 package org.oran.otf.common.utility.http;\r
18 \r
19 import com.google.common.base.Strings;\r
20 import java.io.UnsupportedEncodingException;\r
21 import java.util.HashMap;\r
22 import java.util.Map;\r
23 import java.util.Timer;\r
24 import java.util.TimerTask;\r
25 import java.util.concurrent.Future;\r
26 import org.apache.http.HttpHost;\r
27 import org.apache.http.HttpResponse;\r
28 import org.apache.http.client.config.RequestConfig;\r
29 import org.apache.http.client.methods.HttpGet;\r
30 import org.apache.http.client.methods.HttpPost;\r
31 import org.apache.http.client.methods.HttpRequestBase;\r
32 import org.apache.http.client.protocol.HttpClientContext;\r
33 import org.apache.http.entity.StringEntity;\r
34 import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;\r
35 import org.apache.http.impl.nio.client.HttpAsyncClients;\r
36 import org.apache.http.protocol.BasicHttpContext;\r
37 import org.slf4j.Logger;\r
38 import org.slf4j.LoggerFactory;\r
39 \r
40 public class RequestUtility {\r
41 \r
42   private static final Logger logger = LoggerFactory.getLogger(RequestUtility.class);\r
43 \r
44   public static void postAsync(String url, String body, Map<String, String> headers, Boolean proxy)\r
45       throws Exception {\r
46     HttpPost post = buildPost(url, body, headers);\r
47     executeAsync(post, proxy);\r
48   }\r
49 \r
50   public static HttpResponse postSync(\r
51       String url, String body, Map<String, String> headers, Boolean proxy) throws Exception {\r
52     HttpPost post = buildPost(url, body, headers);\r
53     return executeSync(post, proxy);\r
54   }\r
55 \r
56   public static HttpResponse postSync(\r
57       String url, String body, Map<String, String> headers, int timeoutInMillis, Boolean proxy)\r
58       throws Exception {\r
59     HttpPost post = buildPost(url, body, headers);\r
60     return executeSync(post, timeoutInMillis, proxy);\r
61   }\r
62 \r
63   public static HttpResponse getSync(String url, Map<String, String> headers, Boolean proxy)\r
64       throws Exception {\r
65     HttpGet get = buildGet(url, headers);\r
66     return executeSync(get, proxy);\r
67   }\r
68 \r
69   public static HttpResponse getSync(\r
70       String url, Map<String, String> headers, int timeoutInMillis, Boolean proxy)\r
71       throws Exception {\r
72     if (timeoutInMillis < 0) {\r
73       throw new IllegalArgumentException("The timeoutInMillis must be a value greater than 0.");\r
74     }\r
75 \r
76     HttpGet get = buildGet(url, headers);\r
77     return executeSync(get, timeoutInMillis, proxy);\r
78   }\r
79 \r
80   public static void getAsync(String url, Map<String, String> headers, Boolean proxy)\r
81       throws Exception {\r
82     HttpGet get = buildGet(url, headers);\r
83     executeAsync(get, proxy);\r
84   }\r
85 \r
86   private static HttpPost buildPost(String url, String body, Map<String, String> headers)\r
87       throws UnsupportedEncodingException {\r
88     if (Strings.isNullOrEmpty(url) || Strings.isNullOrEmpty(body)) {\r
89       return null;\r
90     } else if (headers == null) {\r
91       headers = new HashMap<>();\r
92     }\r
93 \r
94     HttpPost post = new HttpPost(url);\r
95     headers.forEach(post::setHeader);\r
96     post.setEntity(new StringEntity(body));\r
97     return post;\r
98   }\r
99 \r
100   private static HttpGet buildGet(String url, Map<String, String> headers) {\r
101     if (Strings.isNullOrEmpty(url)) {\r
102       return null;\r
103     } else if (headers == null) {\r
104       headers = new HashMap<>();\r
105     }\r
106 \r
107     HttpGet get = new HttpGet(url);\r
108     headers.forEach(get::setHeader);\r
109     return get;\r
110   }\r
111 \r
112   private static HttpResponse executeSync(HttpRequestBase request, Boolean proxy) throws Exception {\r
113     CloseableHttpAsyncClient httpClient = createHttpAsyncClient();\r
114     try {\r
115       httpClient.start();\r
116       Future<HttpResponse> future =\r
117           proxy\r
118               ? httpClient.execute(request, createHttpClientContext(), null)\r
119               : httpClient.execute(request, null);\r
120       return future.get();\r
121     } catch (Exception e) {\r
122       throw e;\r
123     } finally {\r
124       httpClient.close();\r
125     }\r
126   }\r
127 \r
128   private static HttpResponse executeSync(\r
129       HttpRequestBase request, int timeoutInMillis, Boolean proxy) throws Exception {\r
130     if (timeoutInMillis < 0) {\r
131       throw new IllegalArgumentException("The timeoutInMillis must be a value greater than 0.");\r
132     }\r
133 \r
134     // Create a timer task that will abort the task (the request) after the specified time. This\r
135     // task will run *timeoutInMillis* ms\r
136     TimerTask task =\r
137         new TimerTask() {\r
138           @Override\r
139           public void run() {\r
140             if (request != null) {\r
141               request.abort();\r
142             }\r
143           }\r
144         };\r
145 \r
146     CloseableHttpAsyncClient httpClient = createHttpAsyncClient();\r
147     try {\r
148       httpClient.start();\r
149       // Start the timer before making the request.\r
150       new Timer(true).schedule(task, timeoutInMillis);\r
151       Future<HttpResponse> future =\r
152           proxy\r
153               ? httpClient.execute(request, createHttpClientContext(), null)\r
154               : httpClient.execute(request, null);\r
155 \r
156       return future.get();\r
157     } catch (Exception e) {\r
158       throw e;\r
159     } finally {\r
160       httpClient.close();\r
161     }\r
162   }\r
163 \r
164   private static void executeAsync(HttpRequestBase request, Boolean proxy) throws Exception {\r
165     CloseableHttpAsyncClient httpClient = createHttpAsyncClient();\r
166     try {\r
167       httpClient.start();\r
168       Future<HttpResponse> future =\r
169           proxy\r
170               ? httpClient.execute(request, createHttpClientContext(), null)\r
171               : httpClient.execute(request, null);\r
172       logger.debug("Sent asynchronous request.");\r
173     } catch (Exception e) {\r
174       throw e;\r
175     } finally {\r
176       httpClient.close();\r
177     }\r
178   }\r
179 \r
180   private static RequestConfig configureProxy() {\r
181     HttpHost proxy;\r
182     proxy = new HttpHost("localhost", 8080, "http");\r
183     return RequestConfig.custom().setProxy(proxy).build();\r
184   }\r
185 \r
186   private static HttpClientContext createHttpClientContext() {\r
187     HttpClientContext localContext = HttpClientContext.adapt(new BasicHttpContext());\r
188     localContext.setRequestConfig(configureProxy());\r
189     return localContext;\r
190   }\r
191 \r
192   private static CloseableHttpAsyncClient createHttpAsyncClient() throws Exception {\r
193     return HttpAsyncClients.createDefault();\r
194   }\r
195 }\r