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.vnfm.gvnfm.jujuvnfmadapter.common.servicetoken;
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.util.HashMap;
22 import java.util.Iterator;
25 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common.EntityUtils;
26 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common.VnfmException;
27 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.constant.Constant;
28 import org.openo.baseservice.remoteservice.exception.ServiceException;
29 import org.openo.baseservice.roa.util.restclient.Restful;
30 import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback;
31 import org.openo.baseservice.roa.util.restclient.RestfulFactory;
32 import org.openo.baseservice.roa.util.restclient.RestfulOptions;
33 import org.openo.baseservice.roa.util.restclient.RestfulParametes;
34 import org.openo.baseservice.roa.util.restclient.RestfulResponse;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import net.sf.json.JSONArray;
39 import net.sf.json.JSONObject;
48 public final class VnfmRestfulUtil {
50 public static final String TYPE_GET = "get";
52 public static final String TYPE_ADD = "add";
54 public static final String TYPE_POST = "post";
56 public static final String TYPE_PUT = "put";
58 public static final String TYPE_DEL = "delete";
60 public static final int ERROR_STATUS_CODE = -1;
62 private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class);
70 private VnfmRestfulUtil() {
71 // Default Constructor
75 * within our module, we support a default method to invoke
80 * [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
86 @SuppressWarnings("unchecked")
87 public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
88 RestfulParametes restParametes = new RestfulParametes();
89 Map<String, String> headerMap = new HashMap<>(2);
90 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
91 restParametes.setHeaderMap(headerMap);
93 if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
94 if(null != bodyParam) {
95 Map<String, String> vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
96 if(path.contains("?")) {
97 String[] vnfUtlList = path.split("\\?");
98 String[] vnfParams = vnfUtlList[1].split("&");
99 int paramsSize = vnfParams.length;
101 for(int i = 0; i < paramsSize; i++) {
102 vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
106 String vnfParamKey = null;
107 Iterator<String> nameItr = bodyParam.keys();
108 while(nameItr.hasNext()) {
109 vnfParamKey = nameItr.next();
110 vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString());
113 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap);
114 restParametes.setParamMap(vnfParamsMap);
117 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
119 return getRestRes(methodNames, path, restParametes);
123 * encapsulate the java reflect exception
129 private static boolean isAnyNull(Object... objects) {
130 for(int i = 0; i < objects.length; i++) {
131 if(objects[i] == null) {
139 private static Class<?>[] formArray(Object[] objects) {
140 Class<?>[] vnfclasses = new Class[objects.length];
141 for(int i = 0; i < objects.length; i++) {
142 vnfclasses[i] = objects[i].getClass();
155 public static RestfulResponse getRestRes(String methodName, Object... objects) {
156 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
158 if(isAnyNull(objects, rest)) {
162 Class<?>[] vnfClasses = formArray(objects);
164 if(methodName.startsWith("async")) {
165 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
168 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
169 MethodType mt = MethodType.methodType(rtType, vnfClasses);
170 Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
171 .invokeWithArguments(objects);
173 return (RestfulResponse)reuslt;
175 LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
177 } catch(ReflectiveOperationException e) {
178 LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
179 } catch(ServiceException e) {
181 LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
182 LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
183 LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
184 RestfulResponse response = new RestfulResponse();
185 response.setStatus(e.getHttpCode());
186 response.setResponseJson(e.getCause().getMessage());
189 } catch(Throwable e) {//NOSONAR
191 throw (VnfmException)new VnfmException().initCause(e.getCause());
192 } catch(VnfmException e1) {
193 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
208 public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
209 JSONObject retJson = new JSONObject();
210 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
211 String abPath = null;
212 String vnfmId = null;
213 if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
214 JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
215 vnfmId = vnfmObj.getString("id");
219 LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
221 RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson);
222 if(restfulResponse == null || abPath == null) {
223 LOG.error("function=sendReqToApp, msg=data from app is null");
224 retJson.put("data", "get null result");
225 } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
226 JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
227 if(!abPath.contains("vnfdmgr/v1")) {
228 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
230 if(object.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) {
231 retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS);
232 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
235 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
236 if(object.containsKey("msg")) {
237 retJson.put("data", object.getString("msg"));
244 LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
245 LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
246 retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
252 * append suffix to result with vnfmId
258 private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
259 Object result = new Object();
264 if(dataJson instanceof JSONObject) {
265 JSONObject jsonObject = (JSONObject)dataJson;
266 jsonObject.put("vnfmId", vnfmId);
268 } else if(dataJson instanceof JSONArray) {
269 JSONArray dataArray = (JSONArray)dataJson;
270 JSONArray resultArray = new JSONArray();
272 for(Object obj : dataArray) {
273 JSONObject jsonObject = JSONObject.fromObject(obj);
274 jsonObject.put("vnfmId", vnfmId);
275 resultArray.add(jsonObject);
277 result = resultArray;
283 * Method to get Remote Response.<br/>
287 * @param domainTokens
292 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens) {
293 String path = paramsMap.get("path");
294 String methodType = paramsMap.get(Constant.METHOD_TYPE);
295 String url = paramsMap.get("url");
297 RestfulResponse rsp = null;
298 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
301 RestfulOptions opt = new RestfulOptions();
302 String[] strs = url.split("(http(s)?://)|:|/");
304 opt.setHost(strs[1]);
306 opt.setPort(Integer.parseInt(strs[2]));
311 for(int i=strs.length-1;i>=0;i--){
313 path = "/"+strs[i]+path;
316 LOG.info("restfull options:"+EntityUtils.toString(opt, RestfulOptions.class));
317 RestfulParametes restfulParametes = new RestfulParametes();
318 Map<String, String> headerMap = new HashMap<>(3);
319 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
320 headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
321 restfulParametes.setHeaderMap(headerMap);
322 restfulParametes.setRawData(params);
325 if(TYPE_GET.equalsIgnoreCase(methodType)) {
326 rsp = rest.get(path, restfulParametes, opt);
327 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
328 rsp = rest.post(path, restfulParametes, opt);
329 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
330 rsp = rest.put(path, restfulParametes, opt);
331 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
332 rsp = rest.delete(path, restfulParametes, opt);
335 } catch(ServiceException e) {
336 LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
338 LOG.info("request :{},response:{}",params,EntityUtils.toString(rsp, RestfulResponse.class));
344 * read DEFAULT config
353 public static RestfulResponse getRemoteResponse(String url, String methodType, String params) {
354 RestfulResponse rsp = null;
355 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
358 RestfulParametes restfulParametes = new RestfulParametes();
359 Map<String, String> headerMap = new HashMap<>(3);
360 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
361 restfulParametes.setHeaderMap(headerMap);
363 restfulParametes.setRawData(params);
367 if(TYPE_GET.equalsIgnoreCase(methodType)) {
368 rsp = rest.get(url, restfulParametes);
369 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
370 rsp = rest.post(url, restfulParametes);
371 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
372 rsp = rest.put(url, restfulParametes);
373 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
374 rsp = rest.delete(url, restfulParametes);
377 } catch(ServiceException e) {
378 LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
390 * @return Map<String, String>
392 public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
393 Map<String, String> utilParamsMap = new HashMap<>(6);
394 utilParamsMap.put("url", url);
395 utilParamsMap.put(Constant.METHOD_TYPE, methodType);
396 utilParamsMap.put("path", path);
397 utilParamsMap.put("authMode", authMode);
398 return utilParamsMap;