Fix some Sonar issue in common directory
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / svnfm / vnfmadapter / common / servicetoken / VNFRestfulUtil.java
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     public static final String METHODTYPE = "methodType";
65
66     public static final String AUTHMODE = "authMode";
67
68     private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
69
70     private VNFRestfulUtil() {
71
72     }
73
74     /**
75      * within our module, we support a default method to invoke
76      *
77      * @param methodNames String
78      * @param path
79      *            rest service url
80      * @param methodName
81      *            [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
82      *            asyncGet]
83      * @param bodyParam
84      *            rest body msg
85      * @return
86      */
87     @SuppressWarnings("unchecked")
88     public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
89         RestfulParametes restParametes = new RestfulParametes();
90         Map<String, String> headerMap = new HashMap<>(2);
91         headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
92         restParametes.setHeaderMap(headerMap);
93
94         if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
95             if(null != bodyParam) {
96                 Map<String, String> vnfParamMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
97                 if(path.contains("?")) {
98                     String[] vnFutlList = path.split("\\?");
99                     String[] vnFparams = vnFutlList[1].split("&");
100                     int paramsSize = vnFparams.length;
101
102                     for(int i = 0; i < paramsSize; i++) {
103                         vnfParamMap.put(vnFparams[i].split("=")[0], vnFparams[i].split("=")[1]);
104                     }
105                 }
106
107                 String vnFparamKey = null;
108                 Iterator<String> nameItr = bodyParam.keys();
109                 while(nameItr.hasNext()) {
110                     vnFparamKey = nameItr.next();
111                     vnfParamMap.put(vnFparamKey, bodyParam.get(vnFparamKey).toString());
112
113                 }
114                 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamMap);
115                 restParametes.setParamMap(vnfParamMap);
116             }
117         } else {
118             restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
119         }
120         return getRestRes(methodNames, path, restParametes);
121     }
122
123     /**
124      * encapsulate the java reflect exception
125      *
126      * @param methodName
127      *            Restful's method
128      * @param objects
129      *            method param array
130      * @return
131      */
132     private static boolean isAnyNull(Object... objects) {
133         for(int i = 0; i < objects.length; i++) {
134             if(objects[i] == null) {
135                 return true;
136             }
137         }
138         return false;
139
140     }
141
142     private static Class<?>[] formArray(Object[] objects) {
143         Class<?>[] vnfClasses = new Class[objects.length];
144         for(int i = 0; i < objects.length; i++) {
145             vnfClasses[i] = objects[i].getClass();
146         }
147         return vnfClasses;
148
149     }
150
151     /**
152      * Helps to invoke methods on Restful.
153      * <br>
154      *
155      * @param methodName
156      * @param objects
157      * @return
158      * @since VFC 1.0
159      */
160     public static RestfulResponse getRestRes(String methodName, Object... objects) {
161         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
162         try {
163             if(isAnyNull(objects, rest)) {
164                 return null;
165             }
166
167             Class<?>[] vnfClasses = formArray(objects);
168
169             if(methodName.startsWith("async")) {
170                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
171             }
172
173             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
174             MethodType mt = MethodType.methodType(rtType, vnfClasses);
175             Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
176                     .invokeWithArguments(objects);
177             if(reuslt != null) {
178                 return (RestfulResponse)reuslt;
179             }
180             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
181             return null;
182         } catch(ReflectiveOperationException e) {
183             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
184         } catch(ServiceException e) {
185
186             LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
187             LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
188             LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
189             RestfulResponse response = new RestfulResponse();
190             response.setStatus(e.getHttpCode());
191             response.setResponseJson(e.getCause().getMessage());
192             return response;
193
194         } catch(Throwable e) { // NOSONAR
195             try {
196                 throw (VnfmException)new VnfmException().initCause(e.getCause());
197             } catch(VnfmException e1) {
198                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
199             }
200
201         }
202         return null;
203     }
204
205     /**
206      * Send request to manager.
207      * 
208      * @param path
209      * @param methodName
210      * @param paraJson
211      * @return
212      */
213     public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
214         JSONObject retJson = new JSONObject();
215         retJson.put(Constant.RETCODE, Constant.REST_FAIL);
216         String abPath = null;
217         String vnfmId = null;
218         if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
219             JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
220             vnfmId = vnfmObj.getString("id");
221         } else {
222             abPath = path;
223         }
224         LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
225
226         RestfulResponse restfulResponse = VNFRestfulUtil.getRestResByDefault(path, methodName, paraJson);
227         if(restfulResponse == null || abPath == null) {
228             LOG.error("function=sendReqToApp, msg=data from app is null");
229             retJson.put("data", "get null result");
230         } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
231             JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
232             if(!abPath.contains("vnfdmgr/v1")) {
233                 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
234             }
235             if(object.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
236                 retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
237                 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
238                 return retJson;
239             } else {
240                 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
241                 if(object.containsKey("msg")) {
242                     retJson.put("data", object.getString("msg"));
243                     return retJson;
244                 } else {
245                     return object;
246                 }
247             }
248         } else {
249             LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
250             LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
251             retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
252         }
253         return retJson;
254     }
255
256     /**
257      * append suffix to result with vnfmId
258      *
259      * @param vnfmId
260      * @param dataJson
261      * @return
262      */
263     private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
264         Object result = new Object();
265         if(vnfmId == null) {
266             return dataJson;
267         }
268
269         if(dataJson instanceof JSONObject) {
270             JSONObject jsonObject = (JSONObject)dataJson;
271             jsonObject.put("vnfmId", vnfmId);
272             result = jsonObject;
273         } else if(dataJson instanceof JSONArray) {
274             JSONArray dataArray = (JSONArray)dataJson;
275             JSONArray resultArray = new JSONArray();
276
277             for(Object obj : dataArray) {
278                 JSONObject jsonObject = JSONObject.fromObject(obj);
279                 jsonObject.put("vnfmId", vnfmId);
280                 resultArray.add(jsonObject);
281             }
282             result = resultArray;
283         }
284         return result;
285     }
286
287     /**
288      * Make HTTP method calls<br>
289      *
290      * @param paramsMap Map<String, String>
291      * @param params String
292      * @param domainTokens String
293      * @param isNfvoApp Boolean
294      * @return
295      * @since VFC 1.0
296      */
297     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
298             boolean isNfvoApp) {
299         String utilUrl = paramsMap.get("url");
300         String utilMethodType = paramsMap.get(METHODTYPE);
301         String utilPath = paramsMap.get("path");
302         String authMode = paramsMap.get(AUTHMODE);
303
304         RestfulResponse rsp = null;
305         Restful rest = null;
306         String sslOptionFile = "";
307         try {
308             String restClientFile = "restclient.json";
309
310             if(isNfvoApp) {
311                 sslOptionFile = "ssl.nfvo.properties";
312             } else {
313                 sslOptionFile = "ssl.vcmm.properties";
314             }
315
316             LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
317
318             rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
319
320             RestfulOptions opt = new RestfulOptions();
321             String[] strs = utilPath.split("(http(s)?://)|:");
322
323             opt.setHost(strs[1]);
324             opt.setPort(Integer.parseInt(strs[2]));
325
326             RestfulParametes restfulParametes = new RestfulParametes();
327             Map<String, String> headerMap = new HashMap<>(3);
328             headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
329             headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
330             restfulParametes.setHeaderMap(headerMap);
331             restfulParametes.setRawData(params);
332
333             if(rest != null) {
334                 if(TYPE_GET.equalsIgnoreCase(utilMethodType)) {
335                     rsp = rest.get(utilUrl, restfulParametes, opt);
336                 } else if(TYPE_POST.equalsIgnoreCase(utilMethodType)) {
337                     rsp = rest.post(utilUrl, restfulParametes, opt);
338                 } else if(TYPE_PUT.equalsIgnoreCase(utilMethodType)) {
339                     rsp = rest.put(utilUrl, restfulParametes, opt);
340                 } else if(TYPE_DEL.equalsIgnoreCase(utilMethodType)) {
341                     rsp = rest.delete(utilUrl, restfulParametes, opt);
342                 }
343             }
344         } catch(ServiceException e) {
345             LOG.error("function=restfulResponse, get restful response catch exception {}", e);
346         }
347         return rsp;
348     }
349
350     /**
351      * Make HTTP method calls
352      * <br>
353      *
354      * @param paramsMap
355      * @param params
356      * @return
357      * @since VFC 1.0
358      */
359     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
360         if(null == paramsMap) {
361             return null;
362         }
363         String url = paramsMap.get("url");
364         String methodType = paramsMap.get(METHODTYPE);
365
366         RestfulResponse rsp = null;
367         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
368         try {
369
370             RestfulParametes restfulParametes = new RestfulParametes();
371             Map<String, String> headerMap = new HashMap<>(3);
372             headerMap.put(CONTENT_TYPE, APPLICATION);
373             restfulParametes.setHeaderMap(headerMap);
374             restfulParametes.setRawData(params);
375
376             if(rest != null) {
377                 if(TYPE_GET.equalsIgnoreCase(methodType)) {
378                     rsp = rest.get(url, restfulParametes);
379                 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
380                     rsp = rest.post(url, restfulParametes);
381                 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
382                     rsp = rest.put(url, restfulParametes);
383                 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
384                     rsp = rest.delete(url, restfulParametes);
385                 }
386             }
387         } catch(ServiceException e) {
388             LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
389         }
390         return rsp;
391     }
392
393     /**
394      * Helps to make the parameter map.
395      * <br>
396      *
397      * @param url
398      * @param methodType
399      * @param path
400      * @param authMode
401      * @return
402      * @since VFC 1.0
403      */
404     public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
405         Map<String, String> utilParamsMap = new HashMap<>(6);
406         utilParamsMap.put("url", url);
407         utilParamsMap.put(METHODTYPE, methodType);
408         utilParamsMap.put("path", path);
409         utilParamsMap.put(AUTHMODE, authMode);
410         return utilParamsMap;
411     }
412
413     /**
414      * Helps to make the parameter map.<br>
415      *
416      * @param url
417      * @param methodType
418      * @param path
419      * @return
420      * @since VFC 1.0
421      */
422     public static Map<String, String> generateParamsMap(String url, String methodType, String path) {
423         Map<String, String> paramsMap = new HashMap<>(6);
424         paramsMap.put("url", url);
425         paramsMap.put(METHODTYPE, methodType);
426         paramsMap.put("path", path);
427         paramsMap.put(AUTHMODE, "Certificate");
428         return paramsMap;
429     }
430
431     /**
432      * Cookup the response
433      * <br>
434      *
435      * @param vnfmInfo
436      * @param vnfmId
437      * @return
438      * @since VFC 1.0
439      */
440     public static JSONObject getResultToVnfm(JSONObject vnfmInfo, String vnfmId) {
441         JSONObject retJson = new JSONObject();
442         retJson.put(Constant.RETCODE, Constant.REST_FAIL);
443         if(vnfmInfo == null) {
444             LOG.error("function=getResultToVnfm, msg=data from vnfm is null");
445             retJson.put("data", "get null result");
446             return retJson;
447         }
448
449         if(vnfmInfo.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
450             retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
451             retJson.put("data", withVnfmIdSuffix(vnfmId, vnfmInfo.get("data")));
452             return retJson;
453         } else {
454             retJson.put(Constant.RETCODE, Constant.REST_FAIL);
455             if(vnfmInfo.containsKey("msg")) {
456                 retJson.put("data", vnfmInfo.getString("msg"));
457                 return retJson;
458             } else {
459                 return vnfmInfo;
460             }
461         }
462     }
463 }