2661d695541b59a6b485a68ce0c41b2f3865e7bd
[vfc/nfvo/wfengine.git] / common-util / src / main / java / org / openo / baseservice / util / RestUtils.java
1 /*
2  * Copyright 2016 Huawei Technologies Co., Ltd.
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.openo.baseservice.util;
17
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import java.io.BufferedReader;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.io.InputStreamReader;
25
26 import javax.servlet.http.HttpServletRequest;
27
28 /**
29  * Utility functions for ROA.<br/>
30  * <p>
31  * </p>
32  * 
33  * @author
34  * @version   31-May-2016
35  */
36 public final class RestUtils {
37
38     private static final Logger LOGGER = LoggerFactory.getLogger(RestUtils.class);
39
40     private RestUtils() {
41
42     }
43
44     /**
45      * To get body from http request<br/>
46      * 
47      * @param request : request object.
48      * @return Request body as string.
49      * @since  
50      */
51     public static String getRequestBody(final HttpServletRequest request) {
52         String body = null;
53         final StringBuilder stringBuilder = new StringBuilder();
54         BufferedReader bufferedReader = null;
55
56         try {
57             final InputStream inputStream = request.getInputStream();
58             if(inputStream != null) {
59                 bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
60                 final char[] charBuffer = new char[128];
61                 int bytesRead = -1;
62                 while((bytesRead = bufferedReader.read(charBuffer)) > 0) {
63                     stringBuilder.append(charBuffer, 0, bytesRead);
64                 }
65             }
66         } catch(final IOException ex) {
67             LOGGER.error("read inputStream buffer catch exception:", ex);
68         } finally {
69             if(bufferedReader != null) {
70                 try {
71                     bufferedReader.close();
72                 } catch(final IOException ex) {
73                     LOGGER.error("close buffer catch exception:", ex);
74                 }
75             }
76         }
77
78         body = stringBuilder.toString();
79         return body;
80     }
81
82 }