2 * Copyright 2016-2017 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;
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.util.HashMap;
24 import javax.servlet.http.HttpServletResponse;
26 import org.apache.commons.lang.StringUtils;
27 import org.apache.logging.log4j.LogManager;
28 import org.apache.logging.log4j.Logger;
29 import org.onap.vfc.nfvo.resmanagement.common.ResourceUtil;
30 import org.onap.vfc.nfvo.resmanagement.common.constant.Constant;
31 import org.onap.vfc.nfvo.resmanagement.common.constant.ParamConstant;
32 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.Restful;
33 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulAsyncCallback;
34 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulFactory;
35 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulOptions;
36 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulParametes;
37 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulResponse;
38 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.ServiceException;
40 import net.sf.json.JSONArray;
41 import net.sf.json.JSONException;
42 import net.sf.json.JSONObject;
45 * Restful Utility Class.<br>
50 * @version VFC 1.0 Sep 10, 2016
52 public class RestfulUtil {
54 public static final String TYPE_GET = "get";
56 public static final String TYPE_PUT = "put";
58 public static final String TYPE_POST = "post";
60 public static final String TYPE_DEL = "delete";
62 public static final String CONTENT_TYPE = "Content-type";
64 public static final String APPLICATION = "application/json";
66 public static final String NO_RESULT_EXCEPTION =
67 "org.openo.nfvo.resmanage.service.group.resoperate.add.res.no.result";
69 private static final Logger LOGGER = LogManager.getLogger(RestfulUtil.class);
71 private static final Restful REST_CLIENT_HTTP = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
73 private static final Restful REST_CLIENT_HTTPS = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTPS);
75 private RestfulUtil() {
79 * Get response object.<br>
86 public static JSONObject getResponseObj(String url, String type) {
87 return getResponseObj(url, new RestfulParametes(), type);
91 * Get response object.<br>
99 public static JSONObject getResponseObj(String url, RestfulParametes parametes, String type) {
101 String content = RestfulUtil.getResponseContent(url, parametes, null, type);
102 LOGGER.error("function=getResponseObj, content : {}", content);
103 if(StringUtils.isEmpty(content)) {
106 return JSONObject.fromObject(content);
107 } catch(JSONException e) {
108 LOGGER.error("function=getResponseObj, exception : {}", e);
114 * Get response content.<br>
117 * @param restParametes
122 public static String getResponseContent(String url, RestfulParametes restParametes, String type) {
123 return getResponseContent(url, restParametes, null, type);
127 * Get response map.<br>
130 * @param restParametes
136 public static Map<String, Object> getResponseMap(String url, RestfulParametes restParametes, RestfulOptions opt,
138 RestfulResponse response = restfulResponse(url, restParametes, opt, type);
139 return getResponseMap(response);
143 * Get response content map.<br>
150 public static Map<String, Object> getResponseContentMap(String url, String type) {
151 RestfulResponse response = restfulResponse(url, new RestfulParametes(), null, type);
152 return getResponseMap(response);
155 private static Map<String, Object> getResponseMap(RestfulResponse response) {
156 Map<String, Object> resMap = new HashMap<>(10);
157 if(null != response) {
158 resMap.put(Constant.RESPONSE_CONTENT, response.getResponseContent());
159 resMap.put(Constant.STATUS_CODE, response.getStatus());
165 * Get response content.<br>
168 * @param restParametes
174 public static String getResponseContent(String url, RestfulParametes restParametes, RestfulOptions opt,
176 String responseContent = null;
177 RestfulResponse rsp = restfulResponse(url, restParametes, opt, type);
179 int httpStatus = rsp.getStatus();
180 LOGGER.warn("function=getResponseContent, get response httpStatusCode : {} ", httpStatus);
181 if(httpStatus < HttpServletResponse.SC_BAD_REQUEST && httpStatus > 0) {
182 responseContent = rsp.getResponseContent();
183 LOGGER.warn("function=getResponseContent, get response data success!responseContent={}",
187 return responseContent;
191 * Get restful response.<br>
194 * @param restParametes
199 public static RestfulResponse getRestfulResponse(String url, RestfulParametes restParametes, String type) {
200 return restfulResponse(url, restParametes, null, type);
203 private static RestfulResponse restfulResponse(String url, RestfulParametes restParametes, RestfulOptions opt,
205 RestfulResponse rsp = new RestfulResponse();
207 Restful restClient = url.startsWith("https") ? REST_CLIENT_HTTPS : REST_CLIENT_HTTP;
209 if(restClient != null) {
210 if(TYPE_GET.equals(type)) {
211 rsp = restClient.get(url, restParametes, opt);
212 } else if(TYPE_POST.equals(type)) {
213 rsp = restClient.post(url, restParametes, opt);
214 } else if(TYPE_PUT.equals(type)) {
215 rsp = restClient.put(url, restParametes, opt);
216 } else if(TYPE_DEL.equals(type)) {
217 rsp = restClient.delete(url, restParametes, opt);
220 } catch(ServiceException e) {
221 LOGGER.error("function=restfulResponse, get restful response catch exception {} ", e);
223 LOGGER.warn("function=restfulResponse, response status is {}, context is {} ", rsp.getStatus(),
224 rsp.getResponseContent());
229 * encapsulate the java reflect exception.<br>
231 * @param methodName, Restful's method.
232 * @param objects, method param array.
236 public static RestfulResponse getRestRes(String methodName, Object... objects) {
238 if(objects == null || REST_CLIENT_HTTP == null) {
242 Class<?>[] classes = new Class[objects.length];
243 for(int i = 0; i < objects.length; i++) {
244 classes[i] = objects[i].getClass();
246 if(methodName.startsWith("async")) {
247 classes[classes.length - 1] = RestfulAsyncCallback.class;
250 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
251 MethodType mt = MethodType.methodType(rtType, classes);
252 Object result = MethodHandles.lookup().findVirtual(REST_CLIENT_HTTP.getClass(), methodName, mt)
253 .bindTo(REST_CLIENT_HTTP).invokeWithArguments(objects);
255 return (RestfulResponse)result;
257 LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
260 } catch(ReflectiveOperationException e) {
261 LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
262 } catch(Throwable e) {// NOSONAR
263 LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
265 throw (ServiceException)new ServiceException().initCause(e.getCause());
266 } catch(ServiceException se) {
267 LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
276 * @param restParametes
279 * @throws ServiceException
282 public static JSONArray getResponseRes(RestfulParametes restParametes, String url) throws ServiceException {
283 String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
284 if(null == result || result.isEmpty()) {
285 LOGGER.error("result from url:" + url + " result:" + result);
286 throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
289 JSONArray rsArray = null;
291 JSONObject rsJson = JSONObject.fromObject(result);
292 rsArray = rsJson.getJSONArray(ParamConstant.PARAM_DATA);
293 } catch(JSONException e) {
294 LOGGER.error("getResources error:" + e);
295 throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
303 * @param restParametes
307 * @throws ServiceException
310 public static JSONArray getResponseRes(RestfulParametes restParametes, String url, String iResName)
311 throws ServiceException {
312 String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
313 if(null == result || result.isEmpty()) {
314 LOGGER.error("result from url:" + url + " result:" + result);
315 throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
318 JSONArray rsArray = null;
320 JSONObject rsJson = JSONObject.fromObject(result);
321 rsArray = rsJson.getJSONArray(iResName);
322 String vimId = rsJson.getString(ParamConstant.PARAM_VIMID);
323 String vimName = rsJson.getString(ParamConstant.PARAM_VIMNAME);
324 for(int i = 0; i < rsArray.size(); i++) {
325 JSONObject jsonObj = rsArray.getJSONObject(i);
326 jsonObj.put(ParamConstant.PARAM_VIMID, vimId);
327 jsonObj.put(ParamConstant.PARAM_VIMNAME, vimName);
329 } catch(JSONException e) {
330 LOGGER.error("getResources error:" + e);
331 throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
344 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
345 String url = paramsMap.get("url");
346 String methodType = paramsMap.get("methodType");
348 RestfulResponse rsp = null;
349 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
352 RestfulParametes restfulParametes = new RestfulParametes();
353 Map<String, String> headerMap = new HashMap<>(3);
354 headerMap.put(CONTENT_TYPE, APPLICATION);
355 restfulParametes.setHeaderMap(headerMap);
356 restfulParametes.setRawData(params);
359 if(TYPE_GET.equalsIgnoreCase(methodType)) {
360 rsp = rest.get(url, restfulParametes);
361 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
362 rsp = rest.post(url, restfulParametes);
363 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
364 rsp = rest.put(url, restfulParametes);
365 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
366 rsp = rest.delete(url, restfulParametes);
369 } catch(ServiceException e) {
370 LOGGER.error("function=getRemoteResponse, get restful response catch exception {}", e);