2 * Copyright 2016 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.onap.vfc.nfvo.resmanagement.common.util.request;
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.util.Enumeration;
22 import java.util.HashMap;
25 import javax.servlet.http.HttpServletRequest;
27 import org.apache.commons.io.IOUtils;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
31 import net.sf.json.JSONException;
32 import net.sf.json.JSONObject;
37 * Utility used for request
41 * @version NFVO 0.5 2016-3-17
43 public final class RequestUtil {
45 private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);
54 private RequestUtil() {
58 * Get context string from http context
62 * @return the needed string in http context
64 public static String getStringRequestBody(HttpServletRequest context) {
66 InputStream input = context.getInputStream();
67 return IOUtils.toString(input);
68 } catch(IOException e) {
69 LOGGER.error("function=getStringRequestBody, get httpservletrequest body exception: {}", e);
75 * Get json parameter from http context
81 public static JSONObject getJsonRequestBody(HttpServletRequest context) {
83 String bodyStr = getStringRequestBody(context);
84 return JSONObject.fromObject(bodyStr);
85 } catch(JSONException e) {
86 LOGGER.error("function=getJsonRequestBody, maybe request param is not a jsonobject exception: {}", e);
92 * Get the body of all request in json format<br/>
96 * @return JSONObject The body of all request in json format
99 public static JSONObject getAllJsonRequestBody(HttpServletRequest context) {
100 JSONObject requestBody = getJsonRequestBody(context);
101 if(null == requestBody) {
102 LOGGER.error("get httpservletrequest body exception");
103 requestBody = new JSONObject();
105 LOGGER.warn("function=getAllJsonRequestBody; msg=get request data is:[{}]", requestBody.toString());
106 requestBody.put("header", getContextHeader(context));
111 * Get the context header<br/>
115 * @return Map context header
118 @SuppressWarnings("unchecked")
119 private static Map<String, String> getContextHeader(HttpServletRequest context) {
120 Map<String, String> header = new HashMap<String, String>();
121 Enumeration<String> headerNames = context.getHeaderNames();
122 while(headerNames.hasMoreElements()) {
123 String headerName = headerNames.nextElement();
124 String value = context.getHeader(headerName);
125 header.put(headerName, value);