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;
41 * VNFM Restful Utility.
45 * @version NFVO 0.5 Sep 10, 2016
47 public final class VnfmRestfulUtil {
49 public static final String TYPE_GET = "get";
51 public static final String TYPE_ADD = "add";
53 public static final String TYPE_POST = "post";
55 public static final String TYPE_PUT = "put";
57 public static final String TYPE_DEL = "delete";
59 public static final int ERROR_STATUS_CODE = -1;
61 private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class);
63 private VnfmRestfulUtil() {
68 * within our module, we support a default method to invoke
73 * [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
79 @SuppressWarnings("unchecked")
80 public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
81 RestfulParametes restParametes = new RestfulParametes();
82 Map<String, String> headerMap = new HashMap<>(2);
83 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
84 restParametes.setHeaderMap(headerMap);
86 if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
87 if(null != bodyParam) {
88 Map<String, String> vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
89 if(path.contains("?")) {
90 String[] vnfUtlList = path.split("\\?");
91 String[] vnfParams = vnfUtlList[1].split("&");
92 int paramsSize = vnfParams.length;
94 for(int i = 0; i < paramsSize; i++) {
95 vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
99 String vnfParamKey = null;
100 Iterator<String> nameItr = bodyParam.keys();
101 while(nameItr.hasNext()) {
102 vnfParamKey = nameItr.next();
103 vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString());
106 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap);
107 restParametes.setParamMap(vnfParamsMap);
110 restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
112 return getRestRes(methodNames, path, restParametes);
116 * encapsulate the java reflect exception
124 private static boolean isAnyNull(Object... objects) {
125 for(int i = 0; i < objects.length; i++) {
126 if(objects[i] == null) {
134 private static Class<?>[] formArray(Object[] objects) {
135 Class<?>[] vnfClasses = new Class[objects.length];
136 for(int i = 0; i < objects.length; i++) {
137 vnfClasses[i] = objects[i].getClass();
144 * Helps to invoke http methods Restful
147 * @param methodName String
148 * @param objects String
152 public static RestfulResponse getRestRes(String methodName, Object... objects) {
153 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
155 if(isAnyNull(objects, rest)) {
159 Class<?>[] vnfClasses = formArray(objects);
161 if(methodName.startsWith("async")) {
162 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
165 Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
166 MethodType mt = MethodType.methodType(rtType, vnfClasses);
167 Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
168 .invokeWithArguments(objects);
170 return (RestfulResponse)reuslt;
172 LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
174 } catch(ReflectiveOperationException e) {
175 LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
176 } catch(ServiceException e) {
178 LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
179 LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
180 LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
181 RestfulResponse response = new RestfulResponse();
182 response.setStatus(e.getHttpCode());
183 response.setResponseJson(e.getCause().getMessage());
186 } catch(Throwable e) { //NOSONAR
188 throw (VnfmException)new VnfmException().initCause(e.getCause());
189 } catch(VnfmException e1) {
190 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
198 * Helps to send Request to vnfm.
202 * @param methodName String
203 * @param paraJson JSONObject
207 public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
208 JSONObject retJson = new JSONObject();
209 retJson.put("retCode", Constant.REST_FAIL);
210 String abPath = null;
211 String vnfmId = null;
212 if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
213 JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
214 vnfmId = vnfmObj.getString("id");
218 LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
220 RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson);
221 if(restfulResponse == null || abPath == null) {
222 LOG.error("function=sendReqToApp, msg=data from app is null");
223 retJson.put("data", "get null result");
224 } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
225 JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
226 if(!abPath.contains("vnfdmgr/v1")) {
227 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
229 if(object.getInt("retCode") == Constant.REST_SUCCESS) {
230 retJson.put("retCode", Constant.REST_SUCCESS);
231 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
234 retJson.put("retCode", Constant.REST_FAIL);
235 if(object.containsKey("msg")) {
236 retJson.put("data", object.getString("msg"));
243 LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
244 LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
245 retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
251 * append suffix to result with vnfmId
257 private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
258 Object result = new Object();
263 if(dataJson instanceof JSONObject) {
264 JSONObject jsonObject = (JSONObject)dataJson;
265 jsonObject.put("vnfmId", vnfmId);
267 } else if(dataJson instanceof JSONArray) {
268 JSONArray dataArray = (JSONArray)dataJson;
269 JSONArray resultArray = new JSONArray();
271 for(Object obj : dataArray) {
272 JSONObject jsonObject = JSONObject.fromObject(obj);
273 jsonObject.put("vnfmId", vnfmId);
274 resultArray.add(jsonObject);
276 result = resultArray;
282 * Make request and get HTTP response
285 * @param paramsMap Map<String, String>
286 * @param params String
287 * @param domainTokens String
288 * @param isNfvoApp boolean
292 public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
294 String utilUrl = paramsMap.get("url");
295 String utilMethodType = paramsMap.get("methodType");
296 String utilPath = paramsMap.get("path");
297 String authMode = paramsMap.get("authMode");
299 RestfulResponse rsp = null;
301 String sslOptionFile = "";
303 String restClientFile = "restclient.json";
306 sslOptionFile = "ssl.nfvo.properties";
308 sslOptionFile = "ssl.vcmm.properties";
311 LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
313 rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
315 RestfulOptions opt = new RestfulOptions();
316 String[] strs = utilPath.split("(http(s)?://)|:");
318 opt.setHost(strs[1]);
319 opt.setPort(Integer.parseInt(strs[2]));
321 RestfulParametes restfulParametes = new RestfulParametes();
322 Map<String, String> headerMap = new HashMap<>(3);
323 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
324 headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
325 restfulParametes.setHeaderMap(headerMap);
326 restfulParametes.setRawData(params);
329 if(TYPE_GET.equalsIgnoreCase(utilMethodType)) {
330 rsp = rest.get(utilUrl, restfulParametes, opt);
331 } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) {
332 rsp = rest.post(utilUrl, restfulParametes, opt);
333 } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) {
334 rsp = rest.put(utilUrl, restfulParametes, opt);
335 } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) {
336 rsp = rest.delete(utilUrl, restfulParametes, opt);
339 } catch(ServiceException e) {
340 LOG.error("function=restfulResponse, get restful response catch exception {}", e);
346 * Make request and get HTTP response
350 * @param methodType String
351 * @param params String
355 public static RestfulResponse getRemoteResponse(String url, String methodType, String params) {
356 RestfulResponse rsp = null;
357 Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
360 RestfulParametes restfulParametes = new RestfulParametes();
361 Map<String, String> headerMap = new HashMap<>(3);
362 headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
363 restfulParametes.setHeaderMap(headerMap);
365 restfulParametes.setRawData(params);
369 if(TYPE_GET.equalsIgnoreCase(methodType)) {
370 rsp = rest.get(url, restfulParametes);
371 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
372 rsp = rest.post(url, restfulParametes);
373 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
374 rsp = rest.put(url, restfulParametes);
375 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
376 rsp = rest.delete(url, restfulParametes);
379 } catch(ServiceException e) {
380 LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
386 * Make Params map<br>
389 * @param methodType String
391 * @param authMode String
395 public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
396 Map<String, String> utilParamsMap = new HashMap<>(6);
397 utilParamsMap.put("url", url);
398 utilParamsMap.put("methodType", methodType);
399 utilParamsMap.put("path", path);
400 utilParamsMap.put("authMode", authMode);
401 return utilParamsMap;