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.openo.nfvo.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.openo.baseservice.remoteservice.exception.ServiceException;
26 import org.openo.baseservice.roa.util.restclient.Restful;
27 import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback;
28 import org.openo.baseservice.roa.util.restclient.RestfulFactory;
29 import org.openo.baseservice.roa.util.restclient.RestfulOptions;
30 import org.openo.baseservice.roa.util.restclient.RestfulParametes;
31 import org.openo.baseservice.roa.util.restclient.RestfulResponse;
32 import org.openo.nfvo.vnfmadapter.common.VnfmException;
33 import org.openo.nfvo.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 NFVO 0.5 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 private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
66 private VNFRestfulUtil() {
71 * within our module, we support a default method to invoke
73 * @param methodNames String
77 * [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
83 @SuppressWarnings("unchecked")
84 public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
85 RestfulParametes restParametes = new RestfulParametes();
86 Map<String, String> headerMap = new HashMap<>(2);
87 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
88 restParametes.setHeaderMap(headerMap);
90 if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
91 if(null != bodyParam) {
92 Map<String, String> vnfParamMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
93 if(path.contains("?")) {
94 String[] vnFutlList = path.split("\\?");
95 String[] vnFparams = vnFutlList[1].split("&");
96 int paramsSize = vnFparams.length;
98 for(int i = 0; i < paramsSize; i++) {
99 vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]);
103 String vnFparamKey = null;
104 Iterator<String> nameItr = bodyParam.keys();
105 while(nameItr.hasNext()) {
106 vnFparamKey = nameItr.next();
107 vnfParamMap.put(vnFparamKey, bodyParam.get(vnFparamKey).toString());
110 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap);
111 restParametes.setParamMap(vnfParamMap);
114 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
116 return getRestRes(methodNames, path, restParametes);
121 * 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();
149 * Helps to invoke methods on Restful.
157 public static RestfulResponse getRestRes(String methodName, Object... objects) {
158 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
160 if(isAnyNull(objects, rest)) {
164 Class<?>[] vnfClasses = formArray(objects);
166 if(methodName.startsWith("async")) {
167 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
170 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
171 MethodType mt = MethodType.methodType(rtType, vnfClasses);
172 Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
173 .invokeWithArguments(objects);
175 return (RestfulResponse)reuslt;
177 LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
179 } catch(ReflectiveOperationException e) {
180 LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
181 } catch(ServiceException e) {
183 LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
184 LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
185 LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
186 RestfulResponse response = new RestfulResponse();
187 response.setStatus(e.getHttpCode());
188 response.setResponseJson(e.getCause().getMessage());
191 } catch(Throwable e) { //NOSONAR
193 throw (VnfmException)new VnfmException().initCause(e.getCause());
194 } catch(VnfmException e1) {
195 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
203 * Send request to manager.
209 public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
210 JSONObject retJson = new JSONObject();
211 retJson.put("retCode", Constant.REST_FAIL);
212 String abPath = null;
213 String vnfmId = null;
214 if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
215 JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
216 vnfmId = vnfmObj.getString("id");
220 LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
222 RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson);
223 if(restfulResponse == null || abPath == null) {
224 LOG.error("function=sendReqToApp, msg=data from app is null");
225 retJson.put("data", "get null result");
226 } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
227 JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
228 if(!abPath.contains("vnfdmgr/v1")) {
229 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
231 if(object.getInt("retCode") == Constant.REST_SUCCESS) {
232 retJson.put("retCode", Constant.REST_SUCCESS);
233 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
236 retJson.put("retCode", Constant.REST_FAIL);
237 if(object.containsKey("msg")) {
238 retJson.put("data", object.getString("msg"));
245 LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
246 LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
247 retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
253 * append suffix to result with vnfmId
259 private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
260 Object result = new Object();
265 if(dataJson instanceof JSONObject) {
266 JSONObject jsonObject = (JSONObject)dataJson;
267 jsonObject.put("vnfmId", vnfmId);
269 } else if(dataJson instanceof JSONArray) {
270 JSONArray dataArray = (JSONArray)dataJson;
271 JSONArray resultArray = new JSONArray();
273 for(Object obj : dataArray) {
274 JSONObject jsonObject = JSONObject.fromObject(obj);
275 jsonObject.put("vnfmId", vnfmId);
276 resultArray.add(jsonObject);
278 result = resultArray;
284 * Make HTTP method calls<br>
286 * @param paramsMap Map<String, String>
287 * @param params String
288 * @param domainTokens String
289 * @param isNfvoApp Boolean
293 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
295 String utilUrl = paramsMap.get("url");
296 String utilMethodType = paramsMap.get("methodType");
297 String utilPath = paramsMap.get("path");
298 String authMode = paramsMap.get("authMode");
300 RestfulResponse rsp = null;
302 String sslOptionFile = "";
304 String restClientFile = "restclient.json";
307 sslOptionFile = "ssl.nfvo.properties";
309 sslOptionFile = "ssl.vcmm.properties";
312 LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
314 rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
316 RestfulOptions opt = new RestfulOptions();
317 String[] strs = utilPath.split("(http(s)?://)|:");
319 opt.setHost(strs[1]);
320 opt.setPort(Integer.parseInt(strs[2]));
322 RestfulParametes restfulParametes = new RestfulParametes();
323 Map<String, String> headerMap = new HashMap<>(3);
324 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
325 headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
326 restfulParametes.setHeaderMap(headerMap);
327 restfulParametes.setRawData(params);
330 if(TYPE_GET.equalsIgnoreCase(utilMethodType)) {
331 rsp = rest.get(utilUrl, restfulParametes, opt);
332 } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) {
333 rsp = rest.post(utilUrl, restfulParametes, opt);
334 } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) {
335 rsp = rest.put(utilUrl, restfulParametes, opt);
336 } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) {
337 rsp = rest.delete(utilUrl, restfulParametes, opt);
340 } catch(ServiceException e) {
341 LOG.error("function=restfulResponse, get restful response catch exception {}", e);
347 * Make HTTP method calls
355 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
356 if(null == paramsMap){
359 String url = paramsMap.get("url");
360 String methodType = paramsMap.get("methodType");
362 RestfulResponse rsp = null;
363 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
366 RestfulParametes restfulParametes = new RestfulParametes();
367 Map<String, String> headerMap = new HashMap<>(3);
368 headerMap.put(CONTENT_TYPE, APPLICATION);
369 restfulParametes.setHeaderMap(headerMap);
370 restfulParametes.setRawData(params);
373 if (TYPE_GET.equalsIgnoreCase(methodType)) {
374 rsp = rest.get(url, restfulParametes);
375 } else if (TYPE_POST.equalsIgnoreCase(methodType)) {
376 rsp = rest.post(url, restfulParametes);
377 } else if (TYPE_PUT.equalsIgnoreCase(methodType)) {
378 rsp = rest.put(url, restfulParametes);
379 } else if (TYPE_DEL.equalsIgnoreCase(methodType)) {
380 rsp = rest.delete(url, restfulParametes);
383 } catch (ServiceException e) {
384 LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
391 * Helps to make the parameter map.
401 public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
402 Map<String, String> utilParamsMap = new HashMap<>(6);
403 utilParamsMap.put("url", url);
404 utilParamsMap.put("methodType", methodType);
405 utilParamsMap.put("path", path);
406 utilParamsMap.put("authMode", authMode);
407 return utilParamsMap;
411 * Helps to make the parameter map.<br>
419 public static Map<String, String> generateParamsMap(String url, String methodType, String path) {
420 Map<String, String> paramsMap = new HashMap<>(6);
421 paramsMap.put("url", url);
422 paramsMap.put("methodType", methodType);
423 paramsMap.put("path", path);
424 paramsMap.put("authMode", "Certificate");
429 * Cookup the response
437 public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) {
438 JSONObject retJson = new JSONObject();
439 retJson.put("retCode", Constant.REST_FAIL);
440 if(vnfmInfo == null) {
441 LOG.error("function=getResultToVnfm, msg=data from vnfm is null");
442 retJson.put("data", "get null result");
446 if(vnfmInfo.getInt("retCode") == Constant.REST_SUCCESS) {
447 retJson.put("retCode", Constant.REST_SUCCESS);
448 retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
451 retJson.put("retCode", Constant.REST_FAIL);
452 if(vnfmInfo.containsKey("msg")) {
453 retJson.put("data", vnfmInfo.getString("msg"));