summaryrefslogtreecommitdiffstats
path: root/service/src/main/java/org/onap/vfc/nfvo/multivimproxy/common/util/RestfulUtil.java
blob: 49e46e7503cc3663cf9e18c460e63874d70bb608 (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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*
 * Copyright 2016-2017 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;

import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.onap.vfc.nfvo.multivimproxy.common.constant.Constant;
import org.onap.vfc.nfvo.multivimproxy.common.constant.ParamConstant;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.Restful;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulAsyncCallback;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulFactory;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulOptions;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulParametes;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.RestfulResponse;
import org.onap.vfc.nfvo.multivimproxy.common.util.restclient.ServiceException;

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

/**
 * Restful Utility Class.<br>
 * <p>
 * </p>
 *
 * @author
 * @version VFC 1.0 Sep 10, 2016
 */
public class RestfulUtil {

    public static final String TYPE_GET = "get";

    public static final String TYPE_PUT = "put";

    public static final String TYPE_POST = "post";

    public static final String TYPE_DEL = "delete";

    public static final String CONTENT_TYPE = "Content-type";

    public static final String APPLICATION = "application/json";

    public static final String NO_RESULT_EXCEPTION =
            "org.openo.nfvo.resmanage.service.group.resoperate.add.res.no.result";

    private static final Logger LOGGER = LogManager.getLogger(RestfulUtil.class);

    private static final Restful REST_CLIENT_HTTP = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);

    private static final Restful REST_CLIENT_HTTPS = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTPS);

    private RestfulUtil() {
    }

    /**
     * Get response object.<br>
     *
     * @param url
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static JSONObject getResponseObj(String url, String type) {
        return getResponseObj(url, new RestfulParametes(), type);
    }

    /**
     * Get response object.<br>
     *
     * @param url
     * @param parametes
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static JSONObject getResponseObj(String url, RestfulParametes parametes, String type) {
        try {
            String content = RestfulUtil.getResponseContent(url, parametes, null, type);
            LOGGER.error("function=getResponseObj, content : {}", content);
            if(StringUtils.isEmpty(content)) {
                return null;
            }
            return JSONObject.fromObject(content);
        } catch(JSONException e) {
            LOGGER.error("function=getResponseObj, exception : {}", e);
            return null;
        }
    }

    /**
     * Get response content.<br>
     *
     * @param url
     * @param restParametes
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static String getResponseContent(String url, RestfulParametes restParametes, String type) {
        return getResponseContent(url, restParametes, null, type);
    }

    /**
     * Get response map.<br>
     *
     * @param url
     * @param restParametes
     * @param opt
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static Map<String, Object> getResponseMap(String url, RestfulParametes restParametes, RestfulOptions opt,
            String type) {
        RestfulResponse response = restfulResponse(url, restParametes, opt, type);
        return getResponseMap(response);
    }

    /**
     * Get response content map.<br>
     *
     * @param url
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static Map<String, Object> getResponseContentMap(String url, String type) {
        RestfulResponse response = restfulResponse(url, new RestfulParametes(), null, type);
        return getResponseMap(response);
    }

    private static Map<String, Object> getResponseMap(RestfulResponse response) {
        Map<String, Object> resMap = new HashMap<>(10);
        if(null != response) {
            resMap.put(Constant.RESPONSE_CONTENT, response.getResponseContent());
            resMap.put(Constant.STATUS_CODE, response.getStatus());
        }
        return resMap;
    }

    /**
     * Get response content.<br>
     *
     * @param url
     * @param restParametes
     * @param opt
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static String getResponseContent(String url, RestfulParametes restParametes, RestfulOptions opt,
            String type) {
        String responseContent = null;
        RestfulResponse rsp = restfulResponse(url, restParametes, opt, type);
        if(rsp != null) {
            int httpStatus = rsp.getStatus();
            LOGGER.warn("function=getResponseContent, get response httpStatusCode : {} ", httpStatus);
            if(httpStatus < HttpServletResponse.SC_BAD_REQUEST && httpStatus > 0) {
                responseContent = rsp.getResponseContent();
                LOGGER.warn("function=getResponseContent, get response data success!responseContent={}",
                        responseContent);
            }
        }
        return responseContent;
    }
    
    public static RestfulResponse getResponse(String url, RestfulParametes restParametes, RestfulOptions opt,
            String type) {
        String responseContent = null;
        RestfulResponse rsp = restfulResponse(url, restParametes, opt, type);
        if(rsp != null) {
            int httpStatus = rsp.getStatus();
            LOGGER.warn("function=getResponseContent, get response httpStatusCode : {} ", httpStatus);
            if(httpStatus < HttpServletResponse.SC_BAD_REQUEST && httpStatus > 0) {
                responseContent = rsp.getResponseContent();
                LOGGER.warn("function=getResponseContent, get response data success!responseContent={}",
                        responseContent);
            }
        }
        return rsp;
    }

    /**
     * Get restful response.<br>
     *
     * @param url
     * @param restParametes
     * @param type
     * @return
     * @since VFC 1.0
     */
    public static RestfulResponse getRestfulResponse(String url, RestfulParametes restParametes, String type) {
        return restfulResponse(url, restParametes, null, type);
    }

    private static RestfulResponse restfulResponse(String url, RestfulParametes restParametes, RestfulOptions opt,
            String type) {
        RestfulResponse rsp = new RestfulResponse();
        try {
            Restful restClient = url.startsWith("https") ? REST_CLIENT_HTTPS : REST_CLIENT_HTTP;

            if(restClient != null) {
                if(TYPE_GET.equals(type)) {
                    rsp = restClient.get(url, restParametes, opt);
                } else if(TYPE_POST.equals(type)) {
                    rsp = restClient.post(url, restParametes, opt);
                } else if(TYPE_PUT.equals(type)) {
                    rsp = restClient.put(url, restParametes, opt);
                } else if(TYPE_DEL.equals(type)) {
                    rsp = restClient.delete(url, restParametes, opt);
                }
            }
        } catch(ServiceException e) {
            LOGGER.error("function=restfulResponse, get restful response catch exception {} ", e);
        }
        LOGGER.warn("function=restfulResponse, response status is {}, context is {} ", rsp.getStatus(),
                rsp.getResponseContent());
        return rsp;
    }

    /**
     * encapsulate the java reflect exception.<br>
     *
     * @param methodName, Restful's method.
     * @param objects, method param array.
     * @return
     * @since VFC 1.0
     */
    public static RestfulResponse getRestRes(String methodName, Object... objects) {
        try {
            if(objects == null || REST_CLIENT_HTTP == null) {
                return null;
            }

            Class<?>[] classes = new Class[objects.length];
            for(int i = 0; i < objects.length; i++) {
                classes[i] = objects[i].getClass();
            }
            if(methodName.startsWith("async")) {
                classes[classes.length - 1] = RestfulAsyncCallback.class;
            }

            Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
            MethodType mt = MethodType.methodType(rtType, classes);
            Object result = MethodHandles.lookup().findVirtual(REST_CLIENT_HTTP.getClass(), methodName, mt)
                    .bindTo(REST_CLIENT_HTTP).invokeWithArguments(objects);
            if(result != null) {
                return (RestfulResponse)result;
            }
            LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
                    methodName);
            return null;
        } catch(ReflectiveOperationException e) {
            LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
        } catch(Throwable e) {// NOSONAR
            LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
            try {
                throw (ServiceException)new ServiceException().initCause(e.getCause());
            } catch(ServiceException se) {
                LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
            }
        }
        return null;
    }

    /**
     * Get response.<br>
     *
     * @param restParametes
     * @param url
     * @return
     * @throws ServiceException
     * @since VFC 1.0
     */
    public static JSONArray getResponseRes(RestfulParametes restParametes, String url) throws ServiceException {
        String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
        if(null == result || result.isEmpty()) {
            LOGGER.error("result from  url:" + url + " result:" + result);
            throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
        }

        JSONArray rsArray = null;
        try {
            JSONObject rsJson = JSONObject.fromObject(result);
            rsArray = rsJson.getJSONArray(ParamConstant.PARAM_DATA);
        } catch(JSONException e) {
            LOGGER.error("getResources error:" + e);
            throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
        }
        return rsArray;
    }

    /**
     * Get response.<br>
     *
     * @param restParametes
     * @param url
     * @param iResName
     * @return
     * @throws ServiceException
     * @since VFC 1.0
     */
    public static JSONArray getResponseRes(RestfulParametes restParametes, String url, String iResName)
            throws ServiceException {
        String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
        if(null == result || result.isEmpty()) {
            LOGGER.error("result from  url:" + url + " result:" + result);
            throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
        }

        JSONArray rsArray = null;
        try {
            JSONObject rsJson = JSONObject.fromObject(result);
            rsArray = rsJson.getJSONArray(iResName);
            String vimId = rsJson.getString(ParamConstant.PARAM_VIMID);
            String vimName = rsJson.getString(ParamConstant.PARAM_VIMNAME);
            for(int i = 0; i < rsArray.size(); i++) {
                JSONObject jsonObj = rsArray.getJSONObject(i);
                jsonObj.put(ParamConstant.PARAM_VIMID, vimId);
                jsonObj.put(ParamConstant.PARAM_VIMNAME, vimName);
            }
        } catch(JSONException e) {
            LOGGER.error("getResources error:" + e);
            throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
        }
        return rsArray;
    }

    /**
     * <br>
     * 
     * @param paramsMap
     * @param params
     * @return
     * @since VFC 1.0
     */
    public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
        String url = paramsMap.get("url");
        String methodType = paramsMap.get("methodType");

        RestfulResponse rsp = null;
        Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
        try {

            RestfulParametes restfulParametes = new RestfulParametes();
            Map<String, String> headerMap = new HashMap<>(3);
            headerMap.put(CONTENT_TYPE, APPLICATION);
            restfulParametes.setHeaderMap(headerMap);
            restfulParametes.setRawData(params);

            if(rest != null) {
                if(TYPE_GET.equalsIgnoreCase(methodType)) {
                    rsp = rest.get(url, restfulParametes);
                } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
                    rsp = rest.post(url, restfulParametes);
                } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
                    rsp = rest.put(url, restfulParametes);
                } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
                    rsp = rest.delete(url, restfulParametes);
                }
            }
        } catch(ServiceException e) {
            LOGGER.error("function=getRemoteResponse, get restful response catch exception {}", e);
        }
        return rsp;
    }
}