894b61c0c72937f179d87cd330927ceb48003455
[vfc/nfvo/resmanagement.git] /
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
17 package org.onap.vfc.nfvo.resmanagement.common.util.request;
18
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.io.UnsupportedEncodingException;
22 import java.net.URLEncoder;
23 import java.util.Enumeration;
24 import java.util.HashMap;
25 import java.util.Map;
26
27 import javax.servlet.http.HttpServletRequest;
28
29 import org.apache.commons.io.IOUtils;
30 import org.apache.logging.log4j.LogManager;
31 import org.apache.logging.log4j.Logger;
32 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulClientConst;
33 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulParametes;
34 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.ServiceException;
35
36 import net.sf.json.JSONException;
37 import net.sf.json.JSONObject;
38
39 /**
40  * <br/>
41  * <p>
42  * Utility used for request
43  * </p>
44  *
45  * @author
46  * @version VFC 1.0 2016-3-17
47  */
48 public final class RequestUtil {
49
50     private static final Logger LOGGER = LogManager.getLogger(RequestUtil.class);
51
52     /**
53      * Constructor<br/>
54      * <p>
55      * </p>
56      *
57      * @since VFC 1.0
58      */
59     private RequestUtil() {
60     }
61
62     /**
63      * Get context string from http context
64      *
65      * @param context
66      *         http context
67      * @return the needed string in http context
68      */
69     public static String getStringRequestBody(HttpServletRequest context) {
70         try {
71             InputStream input = context.getInputStream();
72             return IOUtils.toString(input);
73         } catch(IOException e) {
74             LOGGER.error("function=getStringRequestBody, get httpservletrequest body exception: {}", e);
75             return null;
76         }
77     }
78
79     /**
80      * Get json parameter from http context
81      *
82      * @param context
83      *         http context
84      * @return JSONObject
85      */
86     public static JSONObject getJsonRequestBody(HttpServletRequest context) {
87         try {
88             String bodyStr = getStringRequestBody(context);
89             return JSONObject.fromObject(bodyStr);
90         } catch(JSONException e) {
91             LOGGER.error("function=getJsonRequestBody, maybe request param is not a jsonobject exception: {}", e);
92             return null;
93         }
94     }
95
96     /**
97      * Get the body of all request in json format<br/>
98      *
99      * @param context
100      *         The http context
101      * @return JSONObject The body of all request in json format
102      * @since VFC 1.0
103      */
104     public static JSONObject getAllJsonRequestBody(HttpServletRequest context) {
105         JSONObject requestBody = getJsonRequestBody(context);
106         if(null == requestBody) {
107             LOGGER.error("get httpservletrequest body exception");
108             requestBody = new JSONObject();
109         }
110         LOGGER.warn("function=getAllJsonRequestBody; msg=get request data is:[{}]", requestBody.toString());
111         requestBody.put("header", getContextHeader(context));
112         return requestBody;
113     }
114
115     /**
116      * Get the context header<br/>
117      *
118      * @param context
119      *         The http context
120      * @return Map context header
121      * @since VFC 1.0
122      */
123     @SuppressWarnings("unchecked")
124     private static Map<String, String> getContextHeader(HttpServletRequest context) {
125         Map<String, String> header = new HashMap<>();
126         Enumeration<String> headerNames = context.getHeaderNames();
127         while(headerNames.hasMoreElements()) {
128             String headerName = headerNames.nextElement();
129             String value = context.getHeader(headerName);
130             header.put(headerName, value);
131         }
132         return header;
133     }
134
135     public static String encodeParams(final RestfulParametes restParametes) throws ServiceException {
136         final Map<String, String> parm = restParametes.getParamMap();
137         String value = null;
138         boolean bHasParma = false;
139         final StringBuilder builder = new StringBuilder();
140         try {
141             for(final String key : parm.keySet()) {
142                 value = parm.get(key);
143                 if(value == null) {
144                     value = "";
145                 }
146                 String str;
147                 if(bHasParma) {
148                     str = String.format("&%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
149                             URLEncoder.encode(value, RestfulClientConst.ENCODING));
150                 } else {
151                     bHasParma = true;
152                     str = String.format("%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
153                             URLEncoder.encode(value, RestfulClientConst.ENCODING));
154                 }
155                 builder.append(str);
156             }
157         } catch(final UnsupportedEncodingException ex) {
158             LOGGER.error("unsupported encoding: ", ex);
159             throw new ServiceException("Broken VM does not support UTF-8");
160         }
161         return builder.toString();
162     }
163
164     public static Map<String, String> getAAIHeaderMap() {
165         HashMap<String, String> headerMap = new HashMap<>();
166         headerMap.put("X-TransactionId", "9999");
167         headerMap.put("X-FromAppId", "jimmy");
168         headerMap.put("Real-Time", "true");
169         headerMap.put("Authorization", "Basic QUFJOkFBSQ==");
170         headerMap.put("Accept", "application/json");
171         headerMap.put("Content-Type", "application/json");
172         return headerMap;
173     }
174 }