Change: add OPEN-O seed code for VF-C
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / openo / nfvo / vnfmadapter / common / servicetoken / VNFRestfulUtil.java
1 /*
2  * Copyright 2016 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.openo.nfvo.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.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;
36
37 import net.sf.json.JSONArray;
38 import net.sf.json.JSONObject;
39
40 /**
41  * Utility class.</br>
42  *
43  * @author
44  * @version     NFVO 0.5  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     /**
121      * encapsulate the java reflect exception
122      *
123      * @param methodName
124      *            Restful's method
125      * @param objects
126      *            method param array
127      * @return
128      */
129     private static boolean isAnyNull(Object... objects) {
130         for(int i = 0; i < objects.length; i++) {
131             if(objects[i] == null) {
132                 return true;
133             }
134         }
135         return false;
136
137     }
138
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();
143         }
144         return vnfClasses;
145
146     }
147
148     /**
149      * Helps to invoke methods on Restful.
150      * <br>
151      *
152      * @param methodName
153      * @param objects
154      * @return
155      * @since  NFVO 0.5
156      */
157     public static RestfulResponse getRestRes(String methodName, Object... objects) {
158         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
159         try {
160             if(isAnyNull(objects, rest)) {
161                 return null;
162             }
163
164             Class<?>[] vnfClasses = formArray(objects);
165
166             if(methodName.startsWith("async")) {
167                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
168             }
169
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);
174             if(reuslt != null) {
175                 return (RestfulResponse)reuslt;
176             }
177             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
178             return null;
179         } catch(ReflectiveOperationException e) {
180             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
181         } catch(ServiceException e) {
182
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());
189             return response;
190
191         } catch(Throwable e) { //NOSONAR
192             try {
193                 throw (VnfmException)new VnfmException().initCause(e.getCause());
194             } catch(VnfmException e1) {
195                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
196             }
197
198         }
199         return null;
200     }
201
202     /**
203      * Send request to manager.
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("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("retCode") == Constant.REST_SUCCESS) {
232                 retJson.put("retCode", Constant.REST_SUCCESS);
233                 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
234                 return retJson;
235             } else {
236                 retJson.put("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  NFVO 0.5
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  NFVO 0.5
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     /**
391      * Helps to make the parameter map.
392      * <br>
393      *
394      * @param url
395      * @param methodType
396      * @param path
397      * @param authMode
398      * @return
399      * @since  NFVO 0.5
400      */
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;
408     }
409
410     /**
411      * Helps to make the parameter map.<br>
412      *
413      * @param url
414      * @param methodType
415      * @param path
416      * @return
417      * @since  NFVO 0.5
418      */
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");
425         return paramsMap;
426     }
427
428     /**
429      * Cookup the response
430      * <br>
431      *
432      * @param vnfmInfo
433      * @param vnfmId
434      * @return
435      * @since  NFVO 0.5
436      */
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");
443             return retJson;
444         }
445
446         if(vnfmInfo.getInt("retCode") == Constant.REST_SUCCESS) {
447             retJson.put("retCode", Constant.REST_SUCCESS);
448             retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
449             return retJson;
450         } else {
451             retJson.put("retCode", Constant.REST_FAIL);
452             if(vnfmInfo.containsKey("msg")) {
453                 retJson.put("data", vnfmInfo.getString("msg"));
454                 return retJson;
455             } else {
456                 return vnfmInfo;
457             }
458         }
459     }
460 }