Fix gvnfm juju compile problem
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / gvnfm / jujuvnfmadapter / 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.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.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.gvnfm.jujuvnfmadapter.common.AsyncCallback;
26 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.common.VnfmException;
27 import org.onap.vfc.nfvo.vnfm.gvnfm.jujuvnfmadapter.service.constant.Constant;
28 import org.openo.baseservice.remoteservice.exception.ServiceException;
29 import org.openo.baseservice.roa.util.restclient.Restful;
30 import org.openo.baseservice.roa.util.restclient.RestfulAsyncCallback;
31 import org.openo.baseservice.roa.util.restclient.RestfulFactory;
32 import org.openo.baseservice.roa.util.restclient.RestfulOptions;
33 import org.openo.baseservice.roa.util.restclient.RestfulParametes;
34 import org.openo.baseservice.roa.util.restclient.RestfulResponse;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37
38 import net.sf.json.JSONArray;
39 import net.sf.json.JSONObject;
40
41 /**
42  * 
43  * VNF Restful utility class.<br>
44  * <p>
45  * </p>
46  * 
47  * @author
48  * @version     NFVO 0.5  Sep 12, 2016
49  */
50 public final class VNFRestfulUtil {
51
52     public static final String TYPE_GET = "get";
53
54     public static final String TYPE_ADD = "add";
55
56     public static final String TYPE_POST = "post";
57
58     public static final String TYPE_PUT = "put";
59
60     public static final String TYPE_DEL = "delete";
61
62     public static final int ERROR_STATUS_CODE = -1;
63
64     private static final Logger LOG = LoggerFactory.getLogger(VNFRestfulUtil.class);
65
66     private VNFRestfulUtil() {
67
68     }
69
70     /**
71      * 
72      * within our module, we support a default method to invoke.<br>
73      * 
74      * @param path, rest service url
75      * @param methodNames, [post, delete, put, get, asyncPost, asyncDelete, asyncPut,asyncGet]
76      * @param bodyParam, rest body msg
77      * @return
78      * @since  NFVO 0.5
79      */
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);
86
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;
94
95                     for(int i = 0; i < paramsSize; i++) {
96                         vnfparamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
97                     }
98                 }
99
100                 String vnfParamKey;
101                 Iterator<String> nameItr = bodyParam.keys();
102                 while(nameItr.hasNext()) {
103                     vnfParamKey = nameItr.next();
104                     vnfparamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString());
105
106                 }
107                 LOG.warn("method is GET or DEL,and paramsMap = " + vnfparamsMap);
108                 restParametes.setParamMap(vnfparamsMap);
109             }
110         } else {
111             restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
112         }
113         return getRestRes(methodNames, path, restParametes);
114     }
115
116     /**
117      * send restful notification to other module
118      * 
119      * @param path
120      *            service url
121      * @param methodName
122      *            [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
123      *            asyncGet]
124      * @param bodyParam
125      *            rest body msg
126      */
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());
134     }
135
136     /**
137      * encapsulate the java reflect exception
138      * 
139      * @param methodName
140      *            Restful's method
141      * @param objects
142      *            method param array
143      * @return
144      */
145     private static boolean isAnyNull(Object... objects) {
146         for(int i = 0; i < objects.length; i++) {
147             if(objects[i] == null) {
148                 return true;
149             }
150         }
151         return false;
152
153     }
154
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();
159         }
160         return vnfClasses;
161
162     }
163
164     /**
165      * 
166      * Get restful resource.<br>
167      * 
168      * @param methodName
169      * @param objects
170      * @return
171      * @since  NFVO 0.5
172      */
173     public static RestfulResponse getRestRes(String methodName, Object... objects) {
174         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
175         try {
176             if(isAnyNull(objects, rest)) {
177                 return null;
178             }
179
180             Class<?>[] vnfClasses = formArray(objects);
181
182             if(methodName.startsWith("async")) {
183                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
184             }
185
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);
190             if(reuslt != null) {
191                 return (RestfulResponse)reuslt;
192             }
193             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
194             return null;
195         } catch(ReflectiveOperationException e) {
196             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
197         } catch(ServiceException e) {
198
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());
205             return response;
206
207         } catch(Throwable e) {//NOSONAR
208             try {
209                 throw (VnfmException)new VnfmException().initCause(e.getCause());
210             } catch(VnfmException e1) {
211                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
212             }
213
214         }
215         return null;
216     }
217
218     /**
219      * 
220      * Send request to application.<br>
221      * 
222      * @param path
223      * @param methodName
224      * @param paraJson
225      * @return
226      * @since  NFVO 0.5
227      */
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");
236         } else {
237             abPath = path;
238         }
239         LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
240
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());
249             }
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")));
253                 return retJson;
254             } else {
255                 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
256                 if(object.containsKey("msg")) {
257                     retJson.put("data", object.getString("msg"));
258                     return retJson;
259                 } else {
260                     return object;
261                 }
262             }
263         } else {
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());
267         }
268         return retJson;
269     }
270
271     /**
272      * append suffix to result with vnfmId
273      * 
274      * @param vnfmId
275      * @param dataJson
276      * @return
277      */
278     private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
279         Object result = new Object();
280         if(vnfmId == null) {
281             return dataJson;
282         }
283
284         if(dataJson instanceof JSONObject) {
285             JSONObject jsonObject = (JSONObject)dataJson;
286             jsonObject.put("vnfmId", vnfmId);
287             result = jsonObject;
288         } else if(dataJson instanceof JSONArray) {
289             JSONArray dataArray = (JSONArray)dataJson;
290             JSONArray resultArray = new JSONArray();
291
292             for(Object obj : dataArray) {
293                 JSONObject jsonObject = JSONObject.fromObject(obj);
294                 jsonObject.put("vnfmId", vnfmId);
295                 resultArray.add(jsonObject);
296             }
297             result = resultArray;
298         }
299         return result;
300     }
301
302     /**
303      * 
304      * Get remote response.<br>
305      * 
306      * @param paramsMap
307      * @param params
308      * @param domainTokens
309      * @param isNfvoApp
310      * @return
311      * @since  NFVO 0.5
312      */
313     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
314             boolean isNfvoApp) {
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);
319
320         RestfulResponse rsp = null;
321         Restful rest = null;
322         String sslOptionFile = "";
323         try {
324             String restClientFile = "restclient.json";
325
326             if(isNfvoApp) {
327                 sslOptionFile = "ssl.nfvo.properties";
328             } else {
329                 sslOptionFile = "ssl.vcmm.properties";
330             }
331
332             LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
333
334             rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
335
336             RestfulOptions opt = new RestfulOptions();
337             String[] strs = utilPath.split("(http(s)?://)|:");
338
339             opt.setHost(strs[1]);
340             opt.setPort(Integer.parseInt(strs[2]));
341
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);
348
349             if(rest != null) {
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);
358                 }
359             }
360         } catch(ServiceException e) {
361             LOG.error("function=restfulResponse, get restful response catch exception {}", e);
362         }
363         return rsp;
364     }
365
366     /**
367      * 
368      * Generate parameters map.<br>
369      * 
370      * @param url
371      * @param methodType
372      * @param path
373      * @param authMode
374      * @return
375      * @since  NFVO 0.5
376      */
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;
384     }
385
386     /**
387      * 
388      * Generate parameters map.<br>
389      * 
390      * @param url
391      * @param methodType
392      * @param path
393      * @return
394      * @since  NFVO 0.5
395      */
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");
402         return paramsMap;
403     }
404
405     /**
406      * 
407      * Get result to vnfm.<br>
408      * 
409      * @param vnfmInfo
410      * @param vnfmId
411      * @return
412      * @since  NFVO 0.5
413      */
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");
420             return retJson;
421         }
422
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")));
426             return retJson;
427         } else {
428             retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
429             if(vnfmInfo.containsKey("msg")) {
430                 retJson.put("data", vnfmInfo.getString("msg"));
431                 return retJson;
432             } else {
433                 return vnfmInfo;
434             }
435         }
436     }
437 }