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.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.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.jujuvnfmadapter.common.AsyncCallback;
33 import org.openo.nfvo.jujuvnfmadapter.common.VnfmException;
34 import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import net.sf.json.JSONArray;
39 import net.sf.json.JSONObject;
43 * VNF Restful utility class.<br>
48 * @version NFVO 0.5 Sep 12, 2016
50 public final class VNFRestfulUtil {
52 public static final String TYPE_GET = "get";
54 public static final String TYPE_ADD = "add";
56 public static final String TYPE_POST = "post";
58 public static final String TYPE_PUT = "put";
60 public static final String TYPE_DEL = "delete";
62 public static final int ERROR_STATUS_CODE = -1;
64 private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
66 private VNFRestfulUtil() {
72 * within our module, we support a default method to invoke.<br>
74 * @param path, rest service url
75 * @param methodNames, [post, delete, put, get, asyncPost, asyncDelete, asyncPut,asyncGet]
76 * @param bodyParam, rest body msg
80 @SuppressWarnings("unchecked")
81 public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
82 RestfulParametes restParametes = new RestfulParametes();
83 Map<String, String> headerMap = new HashMap<>(2);
84 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
85 restParametes.setHeaderMap(headerMap);
87 if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
88 if(null != bodyParam) {
89 Map<String, String> vnfparamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
90 if(path.contains("?")) {
91 String[] vnfUtlList = path.split("\\?");
92 String[] vnfParams = vnfUtlList[1].split("&");
93 int paramsSize = vnfParams.length;
95 for(int i = 0; i < paramsSize; i++) {
96 vnfparamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
101 Iterator<String> nameItr = bodyParam.keys();
102 while(nameItr.hasNext()) {
103 vnfParamKey = nameItr.next();
104 vnfparamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString());
107 LOG.warn("method is GET or DEL,and paramsMap = " + vnfparamsMap);
108 restParametes.setParamMap(vnfparamsMap);
111 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
113 return getRestRes(methodNames, path, restParametes);
117 * send restful notification to other module
122 * [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
127 public static void sentEvtByRest(String path, String methodName, JSONObject bodyParam) {
128 RestfulParametes restParametes = new RestfulParametes();
129 Map<String, String> headerMap = new HashMap<>(2);
130 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
131 restParametes.setHeaderMap(headerMap);
132 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
133 getRestRes(methodName, path, restParametes, new AsyncCallback());
137 * encapsulate the java reflect exception
145 private static boolean isAnyNull(Object... objects) {
146 for(int i = 0; i < objects.length; i++) {
147 if(objects[i] == null) {
155 private static Class<?>[] formArray(Object[] objects) {
156 Class<?>[] vnfClasses = new Class[objects.length];
157 for(int i = 0; i < objects.length; i++) {
158 vnfClasses[i] = objects[i].getClass();
166 * Get restful resource.<br>
173 public static RestfulResponse getRestRes(String methodName, Object... objects) {
174 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
176 if(isAnyNull(objects, rest)) {
180 Class<?>[] vnfClasses = formArray(objects);
182 if(methodName.startsWith("async")) {
183 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
186 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
187 MethodType mt = MethodType.methodType(rtType, vnfClasses);
188 Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
189 .invokeWithArguments(objects);
191 return (RestfulResponse)reuslt;
193 LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
195 } catch(ReflectiveOperationException e) {
196 LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
197 } catch(ServiceException e) {
199 LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
200 LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
201 LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
202 RestfulResponse response = new RestfulResponse();
203 response.setStatus(e.getHttpCode());
204 response.setResponseJson(e.getCause().getMessage());
207 } catch(Throwable e) {//NOSONAR
209 throw (VnfmException)new VnfmException().initCause(e.getCause());
210 } catch(VnfmException e1) {
211 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
220 * Send request to application.<br>
228 public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
229 JSONObject retJson = new JSONObject();
230 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
231 String abPath = null;
232 String vnfmId = null;
233 if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
234 JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
235 vnfmId = vnfmObj.getString("id");
239 LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
241 RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson);
242 if(restfulResponse == null || abPath == null) {
243 LOG.error("function=sendReqToApp, msg=data from app is null");
244 retJson.put("data", "get null result");
245 } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
246 JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
247 if(!abPath.contains("vnfdmgr/v1")) {
248 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
250 if(object.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) {
251 retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS);
252 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
255 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
256 if(object.containsKey("msg")) {
257 retJson.put("data", object.getString("msg"));
264 LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
265 LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
266 retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
272 * append suffix to result with vnfmId
278 private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
279 Object result = new Object();
284 if(dataJson instanceof JSONObject) {
285 JSONObject jsonObject = (JSONObject)dataJson;
286 jsonObject.put("vnfmId", vnfmId);
288 } else if(dataJson instanceof JSONArray) {
289 JSONArray dataArray = (JSONArray)dataJson;
290 JSONArray resultArray = new JSONArray();
292 for(Object obj : dataArray) {
293 JSONObject jsonObject = JSONObject.fromObject(obj);
294 jsonObject.put("vnfmId", vnfmId);
295 resultArray.add(jsonObject);
297 result = resultArray;
304 * Get remote response.<br>
308 * @param domainTokens
313 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
315 String utilUrl = paramsMap.get("url");
316 String utilMethodType = paramsMap.get(Constant.METHOD_TYPE);
317 String utilPath = paramsMap.get("path");
318 String authMode = paramsMap.get(Constant.AUTH_MODE);
320 RestfulResponse rsp = null;
322 String sslOptionFile = "";
324 String restClientFile = "restclient.json";
327 sslOptionFile = "ssl.nfvo.properties";
329 sslOptionFile = "ssl.vcmm.properties";
332 LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
334 rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
336 RestfulOptions opt = new RestfulOptions();
337 String[] strs = utilPath.split("(http(s)?://)|:");
339 opt.setHost(strs[1]);
340 opt.setPort(Integer.parseInt(strs[2]));
342 RestfulParametes restfulParametes = new RestfulParametes();
343 Map<String, String> headerMap = new HashMap<>(3);
344 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
345 headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
346 restfulParametes.setHeaderMap(headerMap);
347 restfulParametes.setRawData(params);
350 if(TYPE_GET.equalsIgnoreCase(utilMethodType)) {
351 rsp = rest.get(utilUrl, restfulParametes, opt);
352 } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) {
353 rsp = rest.post(utilUrl, restfulParametes, opt);
354 } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) {
355 rsp = rest.put(utilUrl, restfulParametes, opt);
356 } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) {
357 rsp = rest.delete(utilUrl, restfulParametes, opt);
360 } catch(ServiceException e) {
361 LOG.error("function=restfulResponse, get restful response catch exception {}", e);
368 * Generate parameters map.<br>
377 public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
378 Map<String, String> utilParamsMap = new HashMap<>(6);
379 utilParamsMap.put("url", url);
380 utilParamsMap.put("methodType", methodType);
381 utilParamsMap.put("path", path);
382 utilParamsMap.put("authMode", authMode);
383 return utilParamsMap;
388 * Generate parameters map.<br>
396 public static Map<String, String> generateParamsMap(String url, String methodType, String path) {
397 Map<String, String> paramsMap = new HashMap<>(6);
398 paramsMap.put("url", url);
399 paramsMap.put("methodType", methodType);
400 paramsMap.put("path", path);
401 paramsMap.put("authMode", "Certificate");
407 * Get result to vnfm.<br>
414 public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) {
415 JSONObject retJson = new JSONObject();
416 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
417 if(vnfmInfo == null) {
418 LOG.error("function=getResultToVnfm, msg=data from vnfm is null");
419 retJson.put("data", "get null result");
423 if(vnfmInfo.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) {
424 retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS);
425 retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
428 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
429 if(vnfmInfo.containsKey("msg")) {
430 retJson.put("data", vnfmInfo.getString("msg"));