44f643f95d6024c4f288b92398c0f8ac457a7f2b
[vfc/nfvo/driver/vnfm/svnfm.git] /
1 /*
2  * Copyright 2016-2017 Huawei Technologies Co., Ltd.
3  *
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
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  */
16
17 package org.onap.vfc.nfvo.vnfm.svnfm.vnfmadapter.common.servicetoken;
18
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.Map;
24
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;
36
37 import net.sf.json.JSONArray;
38 import net.sf.json.JSONObject;
39
40 /**
41  * Utility class.</br>
42  *
43  * @author
44  * @version VFC 1.0 Sep 10, 2016
45  */
46 public final class VNFRestfulUtil {
47
48     public static final String TYPE_GET = "get";
49
50     public static final String TYPE_ADD = "add";
51
52     public static final String TYPE_POST = "post";
53
54     public static final String TYPE_PUT = "put";
55
56     public static final String TYPE_DEL = "delete";
57
58     public static final int ERROR_STATUS_CODE = -1;
59
60     public static final String CONTENT_TYPE = "Content-type";
61
62     public static final String APPLICATION = "application/json";
63
64     private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
65
66     private VNFRestfulUtil() {
67
68     }
69
70     /**
71      * within our module, we support a default method to invoke
72      *
73      * @param methodNames String
74      * @param path
75      *            rest service url
76      * @param methodName
77      *            [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
78      *            asyncGet]
79      * @param bodyParam
80      *            rest body msg
81      * @return
82      */
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);
89
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;
97
98                     for(int i = 0; i < paramsSize; i++) {
99                         vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]);
100                     }
101                 }
102
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());
108
109                 }
110                 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap);
111                 restParametes.setParamMap(vnfParamMap);
112             }
113         } else {
114             restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
115         }
116         return getRestRes(methodNames, path, restParametes);
117     }
118
119     /**
120      * encapsulate the java reflect exception
121      *
122      * @param methodName
123      *            Restful's method
124      * @param objects
125      *            method param array
126      * @return
127      */
128     private static boolean isAnyNull(Object... objects) {
129         for(int i = 0; i < objects.length; i++) {
130             if(objects[i] == null) {
131                 return true;
132             }
133         }
134         return false;
135
136     }
137
138     private static Class<?>[] formArray(Object[] objects) {
139         Class<?>[] vnfClasses = new Class[objects.length];
140         for(int i = 0; i < objects.length; i++) {
141             vnfClasses[i] = objects[i].getClass();
142         }
143         return vnfClasses;
144
145     }
146
147     /**
148      * Helps to invoke methods on Restful.
149      * <br>
150      *
151      * @param methodName
152      * @param objects
153      * @return
154      * @since VFC 1.0
155      */
156     public static RestfulResponse getRestRes(String methodName, Object... objects) {
157         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
158         try {
159             if(isAnyNull(objects, rest)) {
160                 return null;
161             }
162
163             Class<?>[] vnfClasses = formArray(objects);
164
165             if(methodName.startsWith("async")) {
166                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
167             }
168
169             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
170             MethodType mt = MethodType.methodType(rtType, vnfClasses);
171             Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
172                     .invokeWithArguments(objects);
173             if(reuslt != null) {
174                 return (RestfulResponse)reuslt;
175             }
176             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
177             return null;
178         } catch(ReflectiveOperationException e) {
179             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
180         } catch(ServiceException e) {
181
182             LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
183             LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
184             LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
185             RestfulResponse response = new RestfulResponse();
186             response.setStatus(e.getHttpCode());
187             response.setResponseJson(e.getCause().getMessage());
188             return response;
189
190         } catch(Throwable e) { // NOSONAR
191             try {
192                 throw (VnfmException)new VnfmException().initCause(e.getCause());
193             } catch(VnfmException e1) {
194                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
195             }
196
197         }
198         return null;
199     }
200
201     /**
202      * Send request to manager.
203      * 
204      * @param path
205      * @param methodName
206      * @param paraJson
207      * @return
208      */
209     public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
210         JSONObject retJson = new JSONObject();
211         retJson.put(Constant.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");
217         } else {
218             abPath = path;
219         }
220         LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
221
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());
230             }
231             if(object.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
232                 retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
233                 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
234                 return retJson;
235             } else {
236                 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
237                 if(object.containsKey("msg")) {
238                     retJson.put("data", object.getString("msg"));
239                     return retJson;
240                 } else {
241                     return object;
242                 }
243             }
244         } else {
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());
248         }
249         return retJson;
250     }
251
252     /**
253      * append suffix to result with vnfmId
254      *
255      * @param vnfmId
256      * @param dataJson
257      * @return
258      */
259     private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
260         Object result = new Object();
261         if(vnfmId == null) {
262             return dataJson;
263         }
264
265         if(dataJson instanceof JSONObject) {
266             JSONObject jsonObject = (JSONObject)dataJson;
267             jsonObject.put("vnfmId", vnfmId);
268             result = jsonObject;
269         } else if(dataJson instanceof JSONArray) {
270             JSONArray dataArray = (JSONArray)dataJson;
271             JSONArray resultArray = new JSONArray();
272
273             for(Object obj : dataArray) {
274                 JSONObject jsonObject = JSONObject.fromObject(obj);
275                 jsonObject.put("vnfmId", vnfmId);
276                 resultArray.add(jsonObject);
277             }
278             result = resultArray;
279         }
280         return result;
281     }
282
283     /**
284      * Make HTTP method calls<br>
285      *
286      * @param paramsMap Map<String, String>
287      * @param params String
288      * @param domainTokens String
289      * @param isNfvoApp Boolean
290      * @return
291      * @since VFC 1.0
292      */
293     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
294             boolean isNfvoApp) {
295         String utilUrl = paramsMap.get("url");
296         String utilMethodType = paramsMap.get("methodType");
297         String utilPath = paramsMap.get("path");
298         String authMode = paramsMap.get("authMode");
299
300         RestfulResponse rsp = null;
301         Restful rest = null;
302         String sslOptionFile = "";
303         try {
304             String restClientFile = "restclient.json";
305
306             if(isNfvoApp) {
307                 sslOptionFile = "ssl.nfvo.properties";
308             } else {
309                 sslOptionFile = "ssl.vcmm.properties";
310             }
311
312             LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
313
314             rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
315
316             RestfulOptions opt = new RestfulOptions();
317             String[] strs = utilPath.split("(http(s)?://)|:");
318
319             opt.setHost(strs[1]);
320             opt.setPort(Integer.parseInt(strs[2]));
321
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);
328
329             if(rest != null) {
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);
338                 }
339             }
340         } catch(ServiceException e) {
341             LOG.error("function=restfulResponse, get restful response catch exception {}", e);
342         }
343         return rsp;
344     }
345
346     /**
347      * Make HTTP method calls
348      * <br>
349      *
350      * @param paramsMap
351      * @param params
352      * @return
353      * @since VFC 1.0
354      */
355     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
356         if(null == paramsMap) {
357             return null;
358         }
359         String url = paramsMap.get("url");
360         String methodType = paramsMap.get("methodType");
361
362         RestfulResponse rsp = null;
363         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
364         try {
365
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);
371
372             if(rest != null) {
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);
381                 }
382             }
383         } catch(ServiceException e) {
384             LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
385         }
386         return rsp;
387     }
388
389     /**
390      * Helps to make the parameter map.
391      * <br>
392      *
393      * @param url
394      * @param methodType
395      * @param path
396      * @param authMode
397      * @return
398      * @since VFC 1.0
399      */
400     public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
401         Map<String, String> utilParamsMap = new HashMap<>(6);
402         utilParamsMap.put("url", url);
403         utilParamsMap.put("methodType", methodType);
404         utilParamsMap.put("path", path);
405         utilParamsMap.put("authMode", authMode);
406         return utilParamsMap;
407     }
408
409     /**
410      * Helps to make the parameter map.<br>
411      *
412      * @param url
413      * @param methodType
414      * @param path
415      * @return
416      * @since VFC 1.0
417      */
418     public static Map<String, String> generateParamsMap(String url, String methodType, String path) {
419         Map<String, String> paramsMap = new HashMap<>(6);
420         paramsMap.put("url", url);
421         paramsMap.put("methodType", methodType);
422         paramsMap.put("path", path);
423         paramsMap.put("authMode", "Certificate");
424         return paramsMap;
425     }
426
427     /**
428      * Cookup the response
429      * <br>
430      *
431      * @param vnfmInfo
432      * @param vnfmId
433      * @return
434      * @since VFC 1.0
435      */
436     public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) {
437         JSONObject retJson = new JSONObject();
438         retJson.put(Constant.RETCODE, Constant.REST_FAIL);
439         if(vnfmInfo == null) {
440             LOG.error("function=getResultToVnfm, msg=data from vnfm is null");
441             retJson.put("data", "get null result");
442             return retJson;
443         }
444
445         if(vnfmInfo.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
446             retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
447             retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
448             return retJson;
449         } else {
450             retJson.put(Constant.RETCODE, Constant.REST_FAIL);
451             if(vnfmInfo.containsKey("msg")) {
452                 retJson.put("data", vnfmInfo.getString("msg"));
453                 return retJson;
454             } else {
455                 return vnfmInfo;
456             }
457         }
458     }
459 }