summaryrefslogtreecommitdiffstats
path: root/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/request/RequestUtil.java
blob: 3bda627f6144f6fd3fb0184116a0136371a9d2ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
/*
 * Copyright 2016 Huawei Technologies Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.vfc.nfvo.multivimproxy.common.util.request;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulClientConst;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulParametes;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * <br/>
 * <p>
 * Utility used for request
 * </p>
 *
 * @author
 * @version VFC 1.0 2016-3-17
 */
public final class RequestUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(RequestUtil.class);

    /**
     * Constructor<br/>
     * <p>
     * </p>
     *
     * @since VFC 1.0
     */
    private RequestUtil() {
    }

    /**
     * Get context string from http context
     *
     * @param context
     *         http context
     * @return the needed string in http context
     */
    public static String getStringRequestBody(HttpServletRequest context) {
        try {
            InputStream input = context.getInputStream();
            return IOUtils.toString(input);
        } catch(IOException e) {
            LOGGER.error("function=getStringRequestBody, get httpservletrequest body exception: {}", e);
            return null;
        }
    }

    /**
     * Get json parameter from http context
     *
     * @param context
     *         http context
     * @return JSONObject
     */
    public static JSONObject getJsonRequestBody(HttpServletRequest context) {
        try {
            String bodyStr = getStringRequestBody(context);
            return JSONObject.fromObject(bodyStr);
        } catch(JSONException e) {
            LOGGER.error("function=getJsonRequestBody, maybe request param is not a jsonobject exception: {}", e);
            return null;
        }
    }

    /**
     * Get the body of all request in json format<br/>
     *
     * @param context
     *         The http context
     * @return JSONObject The body of all request in json format
     * @since VFC 1.0
     */
    public static JSONObject getAllJsonRequestBody(HttpServletRequest context) {
        JSONObject requestBody = getJsonRequestBody(context);
        if(null == requestBody) {
            LOGGER.error("get httpservletrequest body exception");
            requestBody = new JSONObject();
        }
        LOGGER.warn("function=getAllJsonRequestBody; msg=get request data is:[{}]", requestBody.toString());
        requestBody.put("header", getContextHeader(context));
        return requestBody;
    }

    /**
     * Get the context header<br/>
     *
     * @param context
     *         The http context
     * @return Map context header
     * @since VFC 1.0
     */
    @SuppressWarnings("unchecked")
    private static Map<String, String> getContextHeader(HttpServletRequest context) {
        Map<String, String> header = new HashMap<>();
        Enumeration<String> headerNames = context.getHeaderNames();
        while(headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            String value = context.getHeader(headerName);
            header.put(headerName, value);
        }
        return header;
    }

    public static String encodeParams(final RestfulParametes restParametes) throws ServiceException {
        final Map<String, String> parm = restParametes.getParamMap();
        String value = null;
        boolean bHasParma = false;
        final StringBuilder builder = new StringBuilder();
        try {
            for(final String key : parm.keySet()) {
                value = parm.get(key);
                if(value == null) {
                    value = "";
                }
                String str;
                if(bHasParma) {
                    str = String.format("&%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
                } else {
                    bHasParma = true;
                    str = String.format("%s=%s", URLEncoder.encode(key, RestfulClientConst.ENCODING),
                            URLEncoder.encode(value, RestfulClientConst.ENCODING));
                }
                builder.append(str);
            }
        } catch(final UnsupportedEncodingException ex) {
            LOGGER.error("unsupported encoding: ", ex);
            throw new ServiceException("Broken VM does not support UTF-8");
        }
        return builder.toString();
    }

    public static Map<String, String> getAAIHeaderMap() {
        HashMap<String, String> headerMap = new HashMap<>();
        headerMap.put("X-TransactionId", "9999");
        headerMap.put("X-FromAppId", "jimmy");
        headerMap.put("Real-Time", "true");
        headerMap.put("Authorization", "Basic QUFJOkFBSQ==");
        headerMap.put("Accept", "application/json");
        headerMap.put("Content-Type", "application/json");
        return headerMap;
    }
}