d3be616a80fc6b08189f6412cb86cccd2df5b87d
[vfc/nfvo/driver/vnfm/svnfm.git] / huawei / vnfmadapter / VnfmadapterService / service / src / main / java / org / onap / vfc / nfvo / vnfm / svnfm / vnfmadapter / common / servicetoken / VnfmRestfulUtil.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  * VNFM Restful Utility.
42  * .</br>
43  *
44  * @author
45  * @version VFC 1.0 Sep 10, 2016
46  */
47 public final class VnfmRestfulUtil {
48
49     public static final String TYPE_GET = "get";
50
51     public static final String TYPE_ADD = "add";
52
53     public static final String TYPE_POST = "post";
54
55     public static final String TYPE_PUT = "put";
56
57     public static final String TYPE_DEL = "delete";
58
59     public static final int ERROR_STATUS_CODE = -1;
60
61     private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class);
62
63     private VnfmRestfulUtil() {
64
65     }
66
67     /**
68      * within our module, we support a default method to invoke
69      *
70      * @param path
71      *            rest service url
72      * @param methodNames
73      *            [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
74      *            asyncGet]
75      * @param bodyParam
76      *            rest body msg
77      * @return
78      */
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);
85
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;
93
94                     for(int i = 0; i < paramsSize; i++) {
95                         vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
96                     }
97                 }
98
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());
104
105                 }
106                 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap);
107                 restParametes.setParamMap(vnfParamsMap);
108             }
109         } else {
110             restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
111         }
112         return getRestRes(methodNames, path, restParametes);
113     }
114
115     /**
116      * encapsulate the java reflect exception
117      *
118      * @param methodName
119      *            Restful's method
120      * @param objects
121      *            method param array
122      * @return
123      */
124     private static boolean isAnyNull(Object... objects) {
125         for(int i = 0; i < objects.length; i++) {
126             if(objects[i] == null) {
127                 return true;
128             }
129         }
130         return false;
131
132     }
133
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();
138         }
139         return vnfClasses;
140
141     }
142
143     /**
144      * Helps to invoke http methods Restful
145      * <br>
146      *
147      * @param methodName String
148      * @param objects String
149      * @return
150      * @since VFC 1.0
151      */
152     public static RestfulResponse getRestRes(String methodName, Object... objects) {
153         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
154         try {
155             if(isAnyNull(objects, rest)) {
156                 return null;
157             }
158
159             Class<?>[] vnfClasses = formArray(objects);
160
161             if(methodName.startsWith("async")) {
162                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
163             }
164
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);
169             if(reuslt != null) {
170                 return (RestfulResponse)reuslt;
171             }
172             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
173             return null;
174         } catch(ReflectiveOperationException e) {
175             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
176         } catch(ServiceException e) {
177
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());
184             return response;
185
186         } catch(Throwable e) { // NOSONAR
187             try {
188                 throw (VnfmException)new VnfmException().initCause(e.getCause());
189             } catch(VnfmException e1) {
190                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
191             }
192
193         }
194         return null;
195     }
196
197     /**
198      * Helps to send Request to vnfm.
199      * <br>
200      *
201      * @param path String
202      * @param methodName String
203      * @param paraJson JSONObject
204      * @return
205      * @since VFC 1.0
206      */
207     public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
208         JSONObject retJson = new JSONObject();
209         retJson.put(Constant.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");
215         } else {
216             abPath = path;
217         }
218         LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
219
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());
228             }
229             if(object.getInt(Constant.RETCODE) == Constant.REST_SUCCESS) {
230                 retJson.put(Constant.RETCODE, Constant.REST_SUCCESS);
231                 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
232                 return retJson;
233             } else {
234                 retJson.put(Constant.RETCODE, Constant.REST_FAIL);
235                 if(object.containsKey("msg")) {
236                     retJson.put("data", object.getString("msg"));
237                     return retJson;
238                 } else {
239                     return object;
240                 }
241             }
242         } else {
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());
246         }
247         return retJson;
248     }
249
250     /**
251      * append suffix to result with vnfmId
252      *
253      * @param vnfmId
254      * @param dataJson
255      * @return
256      */
257     private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
258         Object result = new Object();
259         if(vnfmId == null) {
260             return dataJson;
261         }
262
263         if(dataJson instanceof JSONObject) {
264             JSONObject jsonObject = (JSONObject)dataJson;
265             jsonObject.put("vnfmId", vnfmId);
266             result = jsonObject;
267         } else if(dataJson instanceof JSONArray) {
268             JSONArray dataArray = (JSONArray)dataJson;
269             JSONArray resultArray = new JSONArray();
270
271             for(Object obj : dataArray) {
272                 JSONObject jsonObject = JSONObject.fromObject(obj);
273                 jsonObject.put("vnfmId", vnfmId);
274                 resultArray.add(jsonObject);
275             }
276             result = resultArray;
277         }
278         return result;
279     }
280
281     /**
282      * Make request and get HTTP response
283      * <br>
284      *
285      * @param paramsMap Map<String, String>
286      * @param params String
287      * @param domainTokens String
288      * @param isNfvoApp boolean
289      * @return
290      * @since VFC 1.0
291      */
292     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens,
293             boolean isNfvoApp) {
294         String utilUrl = paramsMap.get("url");
295         String utilMethodType = paramsMap.get("methodType");
296         String utilPath = paramsMap.get("path");
297         String authMode = paramsMap.get("authMode");
298
299         RestfulResponse rsp = null;
300         Restful rest = null;
301         String sslOptionFile = "";
302         try {
303             String restClientFile = "restclient.json";
304
305             if(isNfvoApp) {
306                 sslOptionFile = "ssl.nfvo.properties";
307             } else {
308                 sslOptionFile = "ssl.vcmm.properties";
309             }
310
311             LOG.warn("function=getRemoteResponse,AuthenticationMode=" + authMode);
312
313             rest = HttpRestfulHelp.getRestInstance(sslOptionFile, restClientFile);
314
315             RestfulOptions opt = new RestfulOptions();
316             String[] strs = utilPath.split("(http(s)?://)|:");
317
318             opt.setHost(strs[1]);
319             opt.setPort(Integer.parseInt(strs[2]));
320
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);
327
328             if(rest != null) {
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);
337                 }
338             }
339         } catch(ServiceException e) {
340             LOG.error("function=restfulResponse, get restful response catch exception {}", e);
341         }
342         return rsp;
343     }
344
345     /**
346      * Make request and get HTTP response
347      * <br>
348      *
349      * @param url String
350      * @param methodType String
351      * @param params String
352      * @return
353      * @since VFC 1.0
354      */
355     public static RestfulResponse getRemoteResponse(String url, String methodType, String params) {
356         RestfulResponse rsp = null;
357         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
358         try {
359
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);
364             if(params != null) {
365                 restfulParametes.setRawData(params);
366             }
367
368             if(rest != null) {
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);
377                 }
378             }
379         } catch(ServiceException e) {
380             LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
381         }
382         return rsp;
383     }
384
385     /**
386      * Make Params map<br>
387      *
388      * @param url String
389      * @param methodType String
390      * @param path String
391      * @param authMode String
392      * @return
393      * @since VFC 1.0
394      */
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;
402     }
403
404 }