feat:Add file transfer function
[usecase-ui/server.git] / server / src / main / java / org / onap / usecaseui / server / util / HttpUtil.java
1 /*
2  * Copyright (C) 2018 CMCC, Inc. and others. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.usecaseui.server.util;
17
18 import java.io.BufferedReader;
19 import java.io.IOException;
20 import java.io.UnsupportedEncodingException;
21 import java.util.ArrayList;
22 import java.util.List;
23 import java.util.Map;
24 import java.util.Set;
25
26 import org.apache.http.HttpStatus;
27 import org.apache.http.NameValuePair;
28 import org.apache.http.client.ClientProtocolException;
29 import org.apache.http.client.entity.UrlEncodedFormEntity;
30 import org.apache.http.client.methods.*;
31 import org.apache.http.entity.ContentType;
32 import org.apache.http.entity.StringEntity;
33 import org.apache.http.impl.client.CloseableHttpClient;
34 import org.apache.http.impl.client.HttpClients;
35 import org.apache.http.message.BasicNameValuePair;
36 import org.apache.http.util.EntityUtils;
37 import org.onap.usecaseui.server.bean.HttpResponseResult;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
40
41 import javax.servlet.http.HttpServletRequest;
42
43 import static org.onap.usecaseui.server.constant.CommonConstant.BLANK;
44 import static org.onap.usecaseui.server.constant.CommonConstant.ENCODING_UTF8;
45
46 public class HttpUtil {
47     private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);
48     private static final String LOG_FORMATTER = "[ {} ] {} ";
49     private static final String CLIENT_PRTOCOL_EXCEPTION = "Client protocol exception";
50     private static final String IO_EXCEPTION = "IO Exception occured";
51     private static final String EXCEPTION = "Exception occured";
52     private static final String HTTP_CLIENT_CLOSING_EXCEPTION = "Exception occured while closing httpClient";
53
54     /**
55      * common POST method for REST API calling by using map request body
56      *
57      * @param url
58      * @param headerMap
59      * @param requestBodyMap
60      * @return HttpResponseResult
61      */
62     public static HttpResponseResult sendPostRequestByMap(
63             String url,
64             Map<String, String> headerMap,
65             Map<String, String> requestBodyMap) {
66         logger.info(LOG_FORMATTER  ,url , "  API POST calling is starting......");
67         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
68         CloseableHttpClient httpClient = HttpClients.createDefault();
69
70         try {
71             // set request url and header for API calling
72             HttpPost httpPost = new HttpPost(url);
73             setHeader(httpPost, headerMap);
74
75             // set request body for API calling
76             httpPost.setEntity(setBodyByMap(requestBodyMap));
77
78             // execute API calling and set response
79             CloseableHttpResponse response = httpClient.execute(httpPost);
80             setResponse(response, responseResult);
81         } catch (ClientProtocolException cpe) {
82             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
83         } catch (IOException ioe) {
84             logger.error(IO_EXCEPTION,ioe);
85         } catch (Exception e) {
86             logger.error("EXCEPTION",e);
87         } finally {
88             try {
89                 httpClient.close();
90             } catch (Exception e) {
91                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
92             }
93         }
94
95         logger.info(LOG_FORMATTER  ,url , "  API POST calling has finished!");
96         return responseResult;
97     }
98
99     /**
100      * common POST method for REST API calling by using json request body
101      *
102      * @param url
103      * @param headerMap
104      * @param requestBodyJson
105      * @return HttpResponseResult
106      */
107     public static HttpResponseResult sendPostRequestByJson(
108             String url,
109             Map<String, String> headerMap,
110             String requestBodyJson) {
111         logger.info(LOG_FORMATTER  ,url , "  API POST calling is starting......");
112         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
113         CloseableHttpClient httpClient = HttpClients.createDefault();
114
115         try {
116             // set request url and header for API calling
117             HttpPost httpPost = new HttpPost(url);
118             setHeader(httpPost, headerMap);
119
120             // set request body for API calling
121             httpPost.setEntity(setBodyByJson(requestBodyJson));
122
123             // execute API calling and return response
124             CloseableHttpResponse response = httpClient.execute(httpPost);
125             setResponse(response, responseResult);
126         } catch (ClientProtocolException cpe) {
127             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
128         } catch (IOException ioe) {
129             logger.error(IO_EXCEPTION,ioe);
130         } catch (Exception e) {
131             logger.error(EXCEPTION,e);
132         } finally {
133             try {
134                 httpClient.close();
135             } catch (Exception e) {
136                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
137             }
138         }
139
140         logger.info(LOG_FORMATTER  ,url , " API POST calling has finished!");
141         return responseResult;
142     }
143
144     /**
145      * common GET method for REST API calling
146      *
147      * @param url
148      * @param headerMap
149      * @return HttpResponseResult
150      */
151     public static HttpResponseResult sendGetRequest(
152             String url,
153             Map<String, String> headerMap) {
154         logger.info(LOG_FORMATTER  ,url , "API GET calling is starting......");
155         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
156         CloseableHttpClient httpClient = HttpClients.createDefault();
157
158         try {
159             // set request url and header for API calling
160             HttpGet httpGet = new HttpGet(url);
161             setHeader(httpGet, headerMap);
162
163             // execute API calling and return response
164             CloseableHttpResponse response = httpClient.execute(httpGet);
165             setResponse(response, responseResult);
166         } catch (ClientProtocolException cpe) {
167             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
168         } catch (IOException ioe) {
169             logger.error(IO_EXCEPTION,ioe);
170         } catch (Exception e) {
171             logger.error(EXCEPTION,e);
172         } finally {
173             try {
174                 httpClient.close();
175             } catch (Exception e) {
176                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
177             }
178         }
179
180         logger.info(LOG_FORMATTER  ,url , "API GET calling has finished!");
181         return responseResult;
182     }
183
184     /**
185      * common PUT method for REST API calling by using map request body
186      *
187      * @param url            AAAAA
188      * @param headerMap      AAAAA
189      * @param requestBodyMap AAAAA
190      * @return HttpResponseResult
191      */
192     public static HttpResponseResult sendPutRequestByMap(
193             String url,
194             Map<String, String> headerMap,
195             Map<String, String> requestBodyMap) {
196         logger.info(LOG_FORMATTER ,url , "API PUT calling is starting......");
197         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
198         CloseableHttpClient httpClient = HttpClients.createDefault();
199
200         try {
201             // set request url and header for API calling
202             HttpPut httpPut = new HttpPut(url);
203             setHeader(httpPut, headerMap);
204
205             // set request body for API calling
206             httpPut.setEntity(setBodyByMap(requestBodyMap));
207
208             // execute API calling and set response
209             CloseableHttpResponse response = httpClient.execute(httpPut);
210             setResponse(response, responseResult);
211         } catch (ClientProtocolException cpe) {
212             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
213         } catch (IOException ioe) {
214             logger.error(IO_EXCEPTION,ioe);
215         } catch (Exception e) {
216             logger.error(EXCEPTION,e);
217         } finally {
218             try {
219                 httpClient.close();
220             } catch (Exception e) {
221                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
222             }
223         }
224
225         logger.info(LOG_FORMATTER ,url , " API PUT calling has finished!");
226         return responseResult;
227     }
228
229     /**
230      * common PUT method for REST API calling by using json request body
231      *
232      * @param url
233      * @param headerMap
234      * @param requestBodyJson
235      * @return HttpResponseResult
236      */
237     public static HttpResponseResult sendPutRequestByJson(
238             String url,
239             Map<String, String> headerMap,
240             String requestBodyJson) {
241         logger.info(LOG_FORMATTER, url , "API PUT calling is starting......");
242         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
243         CloseableHttpClient httpClient = HttpClients.createDefault();
244
245         try {
246             // set request url and header for API calling
247             HttpPut httpPut = new HttpPut(url);
248             setHeader(httpPut, headerMap);
249
250             // set request body for API calling
251             httpPut.setEntity(setBodyByJson(requestBodyJson));
252
253             // execute API calling and return response
254             CloseableHttpResponse response = httpClient.execute(httpPut);
255             setResponse(response, responseResult);
256         } catch (ClientProtocolException cpe) {
257             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
258         } catch (IOException ioe) {
259             logger.error(IO_EXCEPTION,ioe);
260         } catch (Exception e) {
261             logger.error(EXCEPTION,e);
262         } finally {
263             try {
264                 httpClient.close();
265             } catch (Exception e) {
266                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
267             }
268         }
269
270         logger.info(LOG_FORMATTER,url , " API PUT calling has finished!");
271         return responseResult;
272     }
273
274     /**
275      * common DELETE method for REST API calling
276      *
277      * @param url
278      * @param headerMap
279      * @return HttpResponseResult
280      */
281     public HttpResponseResult sendDeleteRequest(
282             String url,
283             Map<String, String> headerMap) {
284         logger.info(LOG_FORMATTER,url , " API DELETE calling is starting......");
285         HttpResponseResult responseResult = new HttpResponseResult(HttpStatus.SC_NOT_FOUND, BLANK);
286         CloseableHttpClient httpClient = HttpClients.createDefault();
287
288         try {
289             // set request url and header for API calling
290             HttpDelete httpDelete = new HttpDelete(url);
291             setHeader(httpDelete, headerMap);
292
293             // execute API calling and return response
294             CloseableHttpResponse response = httpClient.execute(httpDelete);
295             setResponse(response, responseResult);
296         } catch (ClientProtocolException cpe) {
297             logger.error(CLIENT_PRTOCOL_EXCEPTION,cpe);
298         } catch (IOException ioe) {
299             logger.error(IO_EXCEPTION,ioe);
300         } catch (Exception e) {
301             logger.error(EXCEPTION,e);
302         } finally {
303             try {
304                 httpClient.close();
305             } catch (Exception e) {
306                 logger.error(HTTP_CLIENT_CLOSING_EXCEPTION,e);
307             }
308         }
309
310         logger.info(LOG_FORMATTER,url , " API DELETE calling has finished!");
311         return responseResult;
312     }
313
314     /**
315      * get string content from request body
316      *
317      * @param request
318      * @return String
319      */
320     public static String ReadAsChars(HttpServletRequest request) {
321         BufferedReader br = null;
322         StringBuilder sb = new StringBuilder(BLANK);
323
324         try {
325             br = request.getReader();
326             String tempString;
327             while ((tempString = br.readLine()) != null) {
328                 sb.append(tempString);
329             }
330             br.close();
331         } catch (IOException ioe) {
332             logger.error("IO exception occured",ioe);
333         } finally {
334             if (null != br) {
335                 try {
336                     br.close();
337                 } catch (IOException ioe) {
338                     logger.error("IO exception occured",ioe);
339                 }
340             }
341         }
342
343         return sb.toString();
344     }
345
346     private static void setHeader(HttpRequestBase request, Map<String, String> headerMap) {
347         if (headerMap != null) {
348             Set<String> keySet = headerMap.keySet();
349             for (String key : keySet) {
350                 request.addHeader(key, headerMap.get(key));
351             }
352         }
353     }
354
355     private static UrlEncodedFormEntity setBodyByMap(Map<String, String> requestBodyMap) throws UnsupportedEncodingException {
356         List<NameValuePair> nvp = new ArrayList<>();
357         if (requestBodyMap != null) {
358             for (Map.Entry<String, String> entry : requestBodyMap.entrySet()) {
359                 nvp.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
360             }
361         }
362         return new UrlEncodedFormEntity(nvp, ENCODING_UTF8);
363     }
364
365     private static StringEntity setBodyByJson(String requestBodyJson) {
366         StringEntity se = new StringEntity(requestBodyJson, ContentType.APPLICATION_JSON);
367         se.setContentEncoding(ENCODING_UTF8);
368         return se;
369     }
370
371     private static void setResponse(CloseableHttpResponse response, HttpResponseResult responseResult) throws IOException {
372         if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
373             responseResult.setResultContent(EntityUtils.toString(response.getEntity(), ENCODING_UTF8));
374         }
375         responseResult.setResultCode(response.getStatusLine().getStatusCode());
376         response.close();
377     }
378 }