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.vnfm.svnfm.vnfmadapter.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.svnfm.vnfmadapter.common.VnfmException;
26 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.Restful;
27 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.RestfulAsyncCallback;
28 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.RestfulFactory;
29 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.RestfulOptions;
30 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.RestfulParametes;
31 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.RestfulResponse;
32 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.restclient.ServiceException;
33 import org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.service.constant.Constant;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
37 import net.sf.json.JSONArray;
38 import net.sf.json.JSONObject;
44 * @version VFC 1.0 Sep 10, 2016
46 public final class VNFRestfulUtil {
48 public static final String TYPE_GET = "get";
50 public static final String TYPE_ADD = "add";
52 public static final String TYPE_POST = "post";
54 public static final String TYPE_PUT = "put";
56 public static final String TYPE_DEL = "delete";
58 public static final int ERROR_STATUS_CODE = -1;
60 public static final String CONTENT_TYPE = "Content-type";
62 public static final String APPLICATION = "application/json";
64 public static final String METHODTYPE = "methodType";
66 public static final String AUTHMODE = "authMode";
68 private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
70 private VNFRestfulUtil() {
75 * within our module, we support a default method to invoke
77 * @param methodNames String
81 * [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
87 @SuppressWarnings("unchecked")
88 public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
89 RestfulParametes restParametes = new RestfulParametes();
90 Map<String, String> headerMap = new HashMap<>(2);
91 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
92 restParametes.setHeaderMap(headerMap);
94 if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
95 if(null != bodyParam) {
96 Map<String, String> vnfParamMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
97 if(path.contains("?")) {
98 String[] vnFutlList = path.split("\\?");
99 String[] vnFparams = vnFutlList[1].split("&");
100 int paramsSize = vnFparams.length;
102 for(int i = 0; i < paramsSize; i++) {
103 vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]);
107 String vnFparamKey = null;
108 Iterator<String> nameItr = bodyParam.keys();
109 while(nameItr.hasNext()) {
110 vnFparamKey = nameItr.next();
111 vnfParamMap.put(vnFparamKey, bodyParam.get(vnFparamKey).toString());
114 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap);
115 restParametes.setParamMap(vnfParamMap);
118 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
120 return getRestRes(methodNames, path, restParametes);
124 * encapsulate the java reflect exception
132 private static boolean isAnyNull(Object... objects) {
133 for(int i = 0; i < objects.length; i++) {
134 if(objects[i] == null) {
142 private static Class<?>[] formArray(Object[] objects) {
143 Class<?>[] vnfClasses = new Class[objects.length];
144 for(int i = 0; i < objects.length; i++) {
145 vnfClasses[i] = objects[i].getClass();
152 * Helps to invoke methods on Restful.
160 public static RestfulResponse getRestRes(String methodName, Object... objects) {
161 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
163 if(isAnyNull(objects, rest)) {
167 Class<?>[] vnfClasses = formArray(objects);
169 if(methodName.startsWith("async")) {
170 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
173 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
174 MethodType mt = MethodType.methodType(rtType, vnfClasses);
175 Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
176 .invokeWithArguments(objects);
178 return (RestfulResponse)reuslt;
180 LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
182 } catch(ReflectiveOperationException e) {
183 LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
184 } catch(ServiceException e) {
186 LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
187 LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
188 LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
189 RestfulResponse response = new RestfulResponse();
190 response.setStatus(e.getHttpCode());
191 response.setResponseJson(e.getCause().getMessage());
194 } catch(Throwable e) { // NOSONAR
196 throw (VnfmException)new VnfmException().initCause(e.getCause());
197 } catch(VnfmException e1) {
198 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
206 * Send request to manager.
213 public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
214 JSONObject retJson = new JSONObject();
215 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
216 String abPath = null;
217 String vnfmId = null;
218 if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
219 JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
220 vnfmId = vnfmObj.getString("id");
224 LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
226 RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson);
227 if(restfulResponse == null || abPath == null) {
228 LOG.error("function=sendReqToApp, msg=data from app is null");
229 retJson.put("data", "get null result");
230 } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
231 JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
232 if(!abPath.contains("vnfdmgr/v1")) {
233 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
235 if(object.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
236 retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
237 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
240 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
241 if(object.containsKey("msg")) {
242 retJson.put("data", object.getString("msg"));
249 LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
250 LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
251 retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
257 * append suffix to result with vnfmId
263 private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
264 Object result = new Object();
269 if(dataJson instanceof JSONObject) {
270 JSONObject jsonObject = (JSONObject)dataJson;
271 jsonObject.put("vnfmId", vnfmId);
273 } else if(dataJson instanceof JSONArray) {
274 JSONArray dataArray = (JSONArray)dataJson;
275 JSONArray resultArray = new JSONArray();
277 for(Object obj : dataArray) {
278 JSONObject jsonObject = JSONObject.fromObject(obj);
279 jsonObject.put("vnfmId", vnfmId);
280 resultArray.add(jsonObject);
282 result = resultArray;
288 * Make HTTP method calls<br>
290 * @param paramsMap Map<String, String>
291 * @param params String
292 * @param domainTokens String
293 * @param isNfvoApp Boolean
297 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
299 String utilUrl = paramsMap.get("url");
300 String utilMethodType = paramsMap.get(METHODTYPE);
301 String utilPath = paramsMap.get("path");
302 String authMode = paramsMap.get(AUTHMODE);
304 RestfulResponse rsp = null;
306 String sslOptionFile = "";
308 String restClientFile = "restclient.json";
311 sslOptionFile = "ssl.nfvo.properties";
313 sslOptionFile = "ssl.vcmm.properties";
316 LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
318 rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
320 RestfulOptions opt = new RestfulOptions();
321 String[] strs = utilPath.split("(http(s)?://)|:");
323 opt.setHost(strs[1]);
324 opt.setPort(Integer.parseInt(strs[2]));
326 RestfulParametes restfulParametes = new RestfulParametes();
327 Map<String, String> headerMap = new HashMap<>(3);
328 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
329 headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
330 restfulParametes.setHeaderMap(headerMap);
331 restfulParametes.setRawData(params);
334 if(TYPE_GET.equalsIgnoreCase(utilMethodType)) {
335 rsp = rest.get(utilUrl, restfulParametes, opt);
336 } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) {
337 rsp = rest.post(utilUrl, restfulParametes, opt);
338 } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) {
339 rsp = rest.put(utilUrl, restfulParametes, opt);
340 } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) {
341 rsp = rest.delete(utilUrl, restfulParametes, opt);
344 } catch(ServiceException e) {
345 LOG.error("function=restfulResponse, get restful response catch exception {}", e);
351 * Make HTTP method calls
359 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
360 if(null == paramsMap) {
363 String url = paramsMap.get("url");
364 String methodType = paramsMap.get(METHODTYPE);
366 RestfulResponse rsp = null;
367 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
370 RestfulParametes restfulParametes = new RestfulParametes();
371 Map<String, String> headerMap = new HashMap<>(3);
372 headerMap.put(CONTENT_TYPE, APPLICATION);
373 restfulParametes.setHeaderMap(headerMap);
374 restfulParametes.setRawData(params);
377 if(TYPE_GET.equalsIgnoreCase(methodType)) {
378 rsp = rest.get(url, restfulParametes);
379 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
380 rsp = rest.post(url, restfulParametes);
381 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
382 rsp = rest.put(url, restfulParametes);
383 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
384 rsp = rest.delete(url, restfulParametes);
387 } catch(ServiceException e) {
388 LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
394 * Helps to make the parameter map.
404 public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
405 Map<String, String> utilParamsMap = new HashMap<>(6);
406 utilParamsMap.put("url", url);
407 utilParamsMap.put(METHODTYPE, methodType);
408 utilParamsMap.put("path", path);
409 utilParamsMap.put(AUTHMODE, authMode);
410 return utilParamsMap;
414 * Helps to make the parameter map.<br>
422 public static Map<String, String> generateParamsMap(String url, String methodType, String path) {
423 Map<String, String> paramsMap = new HashMap<>(6);
424 paramsMap.put("url", url);
425 paramsMap.put(METHODTYPE, methodType);
426 paramsMap.put("path", path);
427 paramsMap.put(AUTHMODE, "Certificate");
432 * Cookup the response
440 public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) {
441 JSONObject retJson = new JSONObject();
442 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
443 if(vnfmInfo == null) {
444 LOG.error("function=getResultToVnfm, msg=data from vnfm is null");
445 retJson.put("data", "get null result");
449 if(vnfmInfo.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
450 retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
451 retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
454 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
455 if(vnfmInfo.containsKey("msg")) {
456 retJson.put("data", vnfmInfo.getString("msg"));