Update gvnfm-driver .gitreview file
[vfc/nfvo/driver/vnfm/gvnfm.git] / juju / juju-vnfmadapter / Juju-vnfmadapterService / service / src / main / java / org / openo / nfvo / jujuvnfmadapter / common / servicetoken / VnfmRestfulUtil.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.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.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.jujuvnfmadapter.common.EntityUtils;
33 import org.openo.nfvo.jujuvnfmadapter.common.VnfmException;
34 import org.openo.nfvo.jujuvnfmadapter.service.constant.Constant;
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  * <br>
43  * <p>
44  * </p>
45  * 
46  * @author
47  */
48 public final class VnfmRestfulUtil {
49
50     public static final String TYPE_GET = "get";
51
52     public static final String TYPE_ADD = "add";
53
54     public static final String TYPE_POST = "post";
55
56     public static final String TYPE_PUT = "put";
57
58     public static final String TYPE_DEL = "delete";
59
60     public static final int ERROR_STATUS_CODE = -1;
61
62     private static final Logger LOG = LoggerFactory.getLogger(VnfmRestfulUtil.class);
63
64     /**
65      * Constructor<br/>
66      * <p>
67      * </p>
68      * 
69      */
70     private VnfmRestfulUtil() {
71         // Default Constructor
72     }
73
74     /**
75      * within our module, we support a default method to invoke
76      * 
77      * @param path
78      *            rest service url
79      * @param methodNames
80      *            [post, delete, put, get, asyncPost, asyncDelete, asyncPut,
81      *            asyncGet]
82      * @param bodyParam
83      *            rest body msg
84      * @return
85      */
86     @SuppressWarnings("unchecked")
87     public static RestfulResponse getRestResByDefault(String path, String methodNames, JSONObject bodyParam) {
88         RestfulParametes restParametes = new RestfulParametes();
89         Map<String, String> headerMap = new HashMap<>(2);
90         headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
91         restParametes.setHeaderMap(headerMap);
92
93         if(Constant.GET.equals(methodNames) || Constant.DELETE.equals(methodNames)) {
94             if(null != bodyParam) {
95                 Map<String, String> vnfParamsMap = new HashMap<>(Constant.DEFAULT_COLLECTION_SIZE);
96                 if(path.contains("?")) {
97                     String[] vnfUtlList = path.split("\\?");
98                     String[] vnfParams = vnfUtlList[1].split("&");
99                     int paramsSize = vnfParams.length;
100
101                     for(int i = 0; i < paramsSize; i++) {
102                         vnfParamsMap.put(vnfParams[i].split("=")[0], vnfParams[i].split("=")[1]);
103                     }
104                 }
105
106                 String vnfParamKey = null;
107                 Iterator<String> nameItr = bodyParam.keys();
108                 while(nameItr.hasNext()) {
109                     vnfParamKey = nameItr.next();
110                     vnfParamsMap.put(vnfParamKey, bodyParam.get(vnfParamKey).toString());
111
112                 }
113                 LOG.warn("method is GET or DEL,and paramsMap = " + vnfParamsMap);
114                 restParametes.setParamMap(vnfParamsMap);
115             }
116         } else {
117             restParametes.setRawData(bodyParam == null ? null : bodyParam.toString());
118         }
119         return getRestRes(methodNames, path, restParametes);
120     }
121
122     /**
123      * encapsulate the java reflect exception
124      *
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      * <br>
150      * 
151      * @param methodName
152      * @param objects
153      * @return
154      */
155     public static RestfulResponse getRestRes(String methodName, Object... objects) {
156         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
157         try {
158             if(isAnyNull(objects, rest)) {
159                 return null;
160             }
161
162             Class<?>[] vnfClasses = formArray(objects);
163
164             if(methodName.startsWith("async")) {
165                 vnfClasses[vnfClasses.length - 1] = RestfulAsyncCallback.class;
166             }
167
168             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
169             MethodType mt = MethodType.methodType(rtType, vnfClasses);
170             Object reuslt = MethodHandles.lookup().findVirtual(rest.getClass(), methodName, mt).bindTo(rest)
171                     .invokeWithArguments(objects);
172             if(reuslt != null) {
173                 return (RestfulResponse)reuslt;
174             }
175             LOG.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.", methodName);
176             return null;
177         } catch(ReflectiveOperationException e) {
178             LOG.error("function=getRestRes, msg=error occurs, e={}.", e);
179         } catch(ServiceException e) {
180
181             LOG.error("function=getRestRes, msg=ServiceException occurs, status={}", e.getHttpCode());
182             LOG.error("function=getRestRes, msg=ServiceException occurs, reason={}.", e.getCause().getMessage());
183             LOG.error("function=getRestRes, msg=ServiceException occurs, e={}.", e);
184             RestfulResponse response = new RestfulResponse();
185             response.setStatus(e.getHttpCode());
186             response.setResponseJson(e.getCause().getMessage());
187             return response;
188
189         } catch(Throwable e) {//NOSONAR
190             try {
191                 throw (VnfmException)new VnfmException().initCause(e.getCause());
192             } catch(VnfmException e1) {
193                 LOG.error("function=getRestRes, msg=VnfmException occurs, e={},e1={}.", e1, e);
194             }
195
196         }
197         return null;
198     }
199
200     /**
201      * <br>
202      * 
203      * @param path
204      * @param methodName
205      * @param paraJson
206      * @return
207      */
208     public static JSONObject sendReqToApp(String path, String methodName, JSONObject paraJson) {
209         JSONObject retJson = new JSONObject();
210         retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
211         String abPath = null;
212         String vnfmId = null;
213         if(paraJson != null && paraJson.containsKey("vnfmInfo")) {
214             JSONObject vnfmObj = paraJson.getJSONObject("vnfmInfo");
215             vnfmId = vnfmObj.getString("id");
216         } else {
217             abPath = path;
218         }
219         LOG.warn("function=sendReqToApp, msg=url to send to app is: " + abPath);
220
221         RestfulResponse restfulResponse = VnfmRestfulUtil.getRestResByDefault(path, methodName, paraJson);
222         if(restfulResponse == null || abPath == null) {
223             LOG.error("function=sendReqToApp, msg=data from app is null");
224             retJson.put("data", "get null result");
225         } else if(restfulResponse.getStatus() == Constant.HTTP_OK) {
226             JSONObject object = JSONObject.fromObject(restfulResponse.getResponseContent());
227             if(!abPath.contains("vnfdmgr/v1")) {
228                 LOG.warn("function=sendReqToApp, msg=result from app is: " + object.toString());
229             }
230             if(object.getInt(Constant.RETURN_CODE) == Constant.REST_SUCCESS) {
231                 retJson.put(Constant.RETURN_CODE, Constant.REST_SUCCESS);
232                 retJson.put("data", withVnfmIdSuffix(vnfmId, object.get("data")));
233                 return retJson;
234             } else {
235                 retJson.put(Constant.RETURN_CODE, Constant.REST_FAIL);
236                 if(object.containsKey("msg")) {
237                     retJson.put("data", object.getString("msg"));
238                     return retJson;
239                 } else {
240                     return object;
241                 }
242             }
243         } else {
244             LOG.error("function=sendReqToApp, msg=status from app is: " + restfulResponse.getStatus());
245             LOG.error("function=sendReqToApp, msg=result from app is: " + restfulResponse.getResponseContent());
246             retJson.put("data", "send to app get error status: " + restfulResponse.getStatus());
247         }
248         return retJson;
249     }
250
251     /**
252      * append suffix to result with vnfmId
253      * 
254      * @param vnfmId
255      * @param dataJson
256      * @return
257      */
258     private static Object withVnfmIdSuffix(String vnfmId, Object dataJson) {
259         Object result = new Object();
260         if(vnfmId == null) {
261             return dataJson;
262         }
263
264         if(dataJson instanceof JSONObject) {
265             JSONObject jsonObject = (JSONObject)dataJson;
266             jsonObject.put("vnfmId", vnfmId);
267             result = jsonObject;
268         } else if(dataJson instanceof JSONArray) {
269             JSONArray dataArray = (JSONArray)dataJson;
270             JSONArray resultArray = new JSONArray();
271
272             for(Object obj : dataArray) {
273                 JSONObject jsonObject = JSONObject.fromObject(obj);
274                 jsonObject.put("vnfmId", vnfmId);
275                 resultArray.add(jsonObject);
276             }
277             result = resultArray;
278         }
279         return result;
280     }
281     /**
282     *
283     * Method to get Remote Response.<br/>
284     *
285     * @param paramsMap
286     * @param params
287     * @param domainTokens
288     * @param isHttps
289     * @return
290     * @since  NFVO 0.5
291     */
292    public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params, String domainTokens) {
293        String path = paramsMap.get("path");
294        String methodType = paramsMap.get(Constant.METHOD_TYPE);
295        String url = paramsMap.get("url");
296
297        RestfulResponse rsp = null;
298        Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
299        try {
300
301            RestfulOptions opt = new RestfulOptions();
302            String[] strs = url.split("(http(s)?://)|:|/");
303
304            opt.setHost(strs[1]);
305            if(strs.length > 0){
306                opt.setPort(Integer.parseInt(strs[2]));
307            }else{
308                opt.setPort(80);
309            }
310
311            for(int i=strs.length-1;i>=0;i--){
312                 if(i > 2){
313                     path = "/"+strs[i]+path;  
314                 }
315             }
316            LOG.info("restfull options:"+EntityUtils.toString(opt, RestfulOptions.class));
317            RestfulParametes restfulParametes = new RestfulParametes();
318            Map<String, String> headerMap = new HashMap<>(3);
319            headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
320            headerMap.put(Constant.HEADER_AUTH_TOKEN, domainTokens);
321            restfulParametes.setHeaderMap(headerMap);
322            restfulParametes.setRawData(params);
323
324            if(rest != null) {
325                if(TYPE_GET.equalsIgnoreCase(methodType)) {
326                    rsp = rest.get(path, restfulParametes, opt);
327                } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
328                    rsp = rest.post(path, restfulParametes, opt);
329                } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
330                    rsp = rest.put(path, restfulParametes, opt);
331                } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
332                    rsp = rest.delete(path, restfulParametes, opt);
333                }
334            }
335        } catch(ServiceException e) {
336            LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
337        }
338        LOG.info("request :{},response:{}",params,EntityUtils.toString(rsp, RestfulResponse.class));
339        return rsp;
340    }
341    
342
343    /**
344     * read DEFAULT config
345     * <br/>
346     * 
347     * @param url
348     * @param methodType
349     * @param params
350     * @return
351     * @since  NFVO 0.5
352     */
353     public static RestfulResponse getRemoteResponse(String url, String methodType, String params) {
354         RestfulResponse rsp = null;
355         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
356         try {
357
358             RestfulParametes restfulParametes = new RestfulParametes();
359             Map<String, String> headerMap = new HashMap<>(3);
360             headerMap.put(Constant.CONTENT_TYPE, Constant.APPLICATION);
361             restfulParametes.setHeaderMap(headerMap);
362             if(params != null) {
363                 restfulParametes.setRawData(params);
364             }
365
366             if(rest != null) {
367                 if(TYPE_GET.equalsIgnoreCase(methodType)) {
368                     rsp = rest.get(url, restfulParametes);
369                 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
370                     rsp = rest.post(url, restfulParametes);
371                 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
372                     rsp = rest.put(url, restfulParametes);
373                 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
374                     rsp = rest.delete(url, restfulParametes);
375                 }
376             }
377         } catch(ServiceException e) {
378             LOG.error("function=getRemoteResponse, get restful response catch exception {}", e);
379         }
380         return rsp;
381     }
382
383     /**
384      * <br>
385      * 
386      * @param url
387      * @param methodType
388      * @param path
389      * @param authMode
390      * @return Map<String, String>
391      */
392     public static Map<String, String> generateParamsMap(String url, String methodType, String path, String authMode) {
393         Map<String, String> utilParamsMap = new HashMap<>(6);
394         utilParamsMap.put("url", url);
395         utilParamsMap.put(Constant.METHOD_TYPE, methodType);
396         utilParamsMap.put("path", path);
397         utilParamsMap.put("authMode", authMode);
398         return utilParamsMap;
399     }
400
401 }