d783ea8e2f190e18ae26ef71fbf65c82580f8eab
[vfc/nfvo/resmanagement.git] /
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.resmanagement.common.util;
18
19 import java.lang.invoke.MethodHandles;
20 import java.lang.invoke.MethodType;
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import javax.servlet.http.HttpServletResponse;
25
26 import org.apache.commons.lang.StringUtils;
27 import org.onap.vfc.nfvo.resmanagement.common.ResourceUtil;
28 import org.onap.vfc.nfvo.resmanagement.common.constant.Constant;
29 import org.onap.vfc.nfvo.resmanagement.common.constant.ParamConstant;
30 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.Restful;
31 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulAsyncCallback;
32 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulFactory;
33 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulOptions;
34 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulParametes;
35 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.RestfulResponse;
36 import org.onap.vfc.nfvo.resmanagement.common.util.restclient.ServiceException;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import net.sf.json.JSONArray;
41 import net.sf.json.JSONException;
42 import net.sf.json.JSONObject;
43
44 /**
45  * Restful Utility Class.<br>
46  * <p>
47  * </p>
48  *
49  * @author
50  * @version VFC 1.0 Sep 10, 2016
51  */
52 public class RestfulUtil {
53
54     public static final String TYPE_GET = "get";
55
56     public static final String TYPE_PUT = "put";
57
58     public static final String TYPE_POST = "post";
59
60     public static final String TYPE_DEL = "delete";
61
62     public static final String CONTENT_TYPE = "Content-type";
63
64     public static final String APPLICATION = "application/json";
65
66     public static final String NO_RESULT_EXCEPTION =
67             "org.openo.nfvo.resmanage.service.group.resoperate.add.res.no.result";
68
69     private static final Logger LOGGER = LoggerFactory.getLogger(RestfulUtil.class);
70
71     private static final Restful REST_CLIENT = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
72
73     private RestfulUtil() {
74     }
75
76     /**
77      * Get response object.<br>
78      *
79      * @param url
80      * @param type
81      * @return
82      * @since VFC 1.0
83      */
84     public static JSONObject getResponseObj(String url, String type) {
85         return getResponseObj(url, new RestfulParametes(), type);
86     }
87
88     /**
89      * Get response object.<br>
90      *
91      * @param url
92      * @param parametes
93      * @param type
94      * @return
95      * @since VFC 1.0
96      */
97     public static JSONObject getResponseObj(String url, RestfulParametes parametes, String type) {
98         try {
99             String content = RestfulUtil.getResponseContent(url, parametes, null, type);
100             LOGGER.error("function=getResponseObj, content : {}", content);
101             if(StringUtils.isEmpty(content)) {
102                 return null;
103             }
104             return JSONObject.fromObject(content);
105         } catch(JSONException e) {
106             LOGGER.error("function=getResponseObj, exception : {}", e);
107             return null;
108         }
109     }
110
111     /**
112      * Get response content.<br>
113      *
114      * @param url
115      * @param restParametes
116      * @param type
117      * @return
118      * @since VFC 1.0
119      */
120     public static String getResponseContent(String url, RestfulParametes restParametes, String type) {
121         return getResponseContent(url, restParametes, null, type);
122     }
123
124     /**
125      * Get response map.<br>
126      *
127      * @param url
128      * @param restParametes
129      * @param opt
130      * @param type
131      * @return
132      * @since VFC 1.0
133      */
134     public static Map<String, Object> getResponseMap(String url, RestfulParametes restParametes, RestfulOptions opt,
135             String type) {
136         RestfulResponse response = restfulResponse(url, restParametes, opt, type);
137         return getResponseMap(response);
138     }
139
140     /**
141      * Get response content map.<br>
142      *
143      * @param url
144      * @param type
145      * @return
146      * @since VFC 1.0
147      */
148     public static Map<String, Object> getResponseContentMap(String url, String type) {
149         RestfulResponse response = restfulResponse(url, new RestfulParametes(), null, type);
150         return getResponseMap(response);
151     }
152
153     private static Map<String, Object> getResponseMap(RestfulResponse response) {
154         Map<String, Object> resMap = new HashMap<>(10);
155         if(null != response) {
156             resMap.put(Constant.RESPONSE_CONTENT, response.getResponseContent());
157             resMap.put(Constant.STATUS_CODE, response.getStatus());
158         }
159         return resMap;
160     }
161
162     /**
163      * Get response content.<br>
164      *
165      * @param url
166      * @param restParametes
167      * @param opt
168      * @param type
169      * @return
170      * @since VFC 1.0
171      */
172     public static String getResponseContent(String url, RestfulParametes restParametes, RestfulOptions opt,
173             String type) {
174         String responseContent = null;
175         RestfulResponse rsp = restfulResponse(url, restParametes, opt, type);
176         if(rsp != null) {
177             int httpStatus = rsp.getStatus();
178             LOGGER.warn("function=getResponseContent, get response httpStatusCode : {} ", httpStatus);
179             if(httpStatus < HttpServletResponse.SC_BAD_REQUEST && httpStatus > 0) {
180                 responseContent = rsp.getResponseContent();
181                 LOGGER.warn("function=getResponseContent, get response data success!responseContent={}",
182                         responseContent);
183             }
184         }
185         return responseContent;
186     }
187
188     /**
189      * Get restful response.<br>
190      *
191      * @param url
192      * @param restParametes
193      * @param type
194      * @return
195      * @since VFC 1.0
196      */
197     public static RestfulResponse getRestfulResponse(String url, RestfulParametes restParametes, String type) {
198         return restfulResponse(url, restParametes, null, type);
199     }
200
201     private static RestfulResponse restfulResponse(String url, RestfulParametes restParametes, RestfulOptions opt,
202             String type) {
203         RestfulResponse rsp = new RestfulResponse();
204         try {
205
206             if(REST_CLIENT != null) {
207                 if(TYPE_GET.equals(type)) {
208                     rsp = REST_CLIENT.get(url, restParametes, opt);
209                 } else if(TYPE_POST.equals(type)) {
210                     rsp = REST_CLIENT.post(url, restParametes, opt);
211                 } else if(TYPE_PUT.equals(type)) {
212                     rsp = REST_CLIENT.put(url, restParametes, opt);
213                 } else if(TYPE_DEL.equals(type)) {
214                     rsp = REST_CLIENT.delete(url, restParametes, opt);
215                 }
216             }
217         } catch(ServiceException e) {
218             LOGGER.error("function=restfulResponse, get restful response catch exception {} ", e);
219         }
220         LOGGER.warn("function=restfulResponse, response status is {} ", rsp.getStatus());
221         return rsp;
222     }
223
224     /**
225      * encapsulate the java reflect exception.<br>
226      *
227      * @param methodName, Restful's method.
228      * @param objects, method param array.
229      * @return
230      * @since VFC 1.0
231      */
232     public static RestfulResponse getRestRes(String methodName, Object... objects) {
233         try {
234             if(objects == null || REST_CLIENT == null) {
235                 return null;
236             }
237
238             Class<?>[] classes = new Class[objects.length];
239             for(int i = 0; i < objects.length; i++) {
240                 classes[i] = objects[i].getClass();
241             }
242             if(methodName.startsWith("async")) {
243                 classes[classes.length - 1] = RestfulAsyncCallback.class;
244             }
245
246             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
247             MethodType mt = MethodType.methodType(rtType, classes);
248             Object result = MethodHandles.lookup().findVirtual(REST_CLIENT.getClass(), methodName, mt)
249                     .bindTo(REST_CLIENT).invokeWithArguments(objects);
250             if(result != null) {
251                 return (RestfulResponse)result;
252             }
253             LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
254                     methodName);
255             return null;
256         } catch(ReflectiveOperationException e) {
257             LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
258         } catch(Throwable e) {// NOSONAR
259             LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
260             try {
261                 throw (ServiceException)new ServiceException().initCause(e.getCause());
262             } catch(ServiceException se) {
263                 LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
264             }
265         }
266         return null;
267     }
268
269     /**
270      * Get response.<br>
271      *
272      * @param restParametes
273      * @param url
274      * @return
275      * @throws ServiceException
276      * @since VFC 1.0
277      */
278     public static JSONArray getResponseRes(RestfulParametes restParametes, String url) throws ServiceException {
279         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
280         if(null == result || result.isEmpty()) {
281             LOGGER.error("result from  url:" + url + " result:" + result);
282             throw new ServiceException(
283                     ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
284         }
285
286         JSONArray rsArray = null;
287         try {
288             JSONObject rsJson = JSONObject.fromObject(result);
289             rsArray = rsJson.getJSONArray(ParamConstant.PARAM_DATA);
290         } catch(JSONException e) {
291             LOGGER.error("getResources error:" + e);
292             throw new ServiceException(
293                     ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
294         }
295         return rsArray;
296     }
297
298     /**
299      * Get response.<br>
300      *
301      * @param restParametes
302      * @param url
303      * @param iResName
304      * @return
305      * @throws ServiceException
306      * @since VFC 1.0
307      */
308     public static JSONArray getResponseRes(RestfulParametes restParametes, String url, String iResName)
309             throws ServiceException {
310         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
311         if(null == result || result.isEmpty()) {
312             LOGGER.error("result from  url:" + url + " result:" + result);
313             throw new ServiceException(
314                     ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
315         }
316
317         JSONArray rsArray = null;
318         try {
319             JSONObject rsJson = JSONObject.fromObject(result);
320             rsArray = rsJson.getJSONArray(iResName);
321             String vimId = rsJson.getString(ParamConstant.PARAM_VIMID);
322             String vimName = rsJson.getString(ParamConstant.PARAM_VIMNAME);
323             for(int i = 0; i < rsArray.size(); i++) {
324                 JSONObject jsonObj = rsArray.getJSONObject(i);
325                 jsonObj.put(ParamConstant.PARAM_VIMID, vimId);
326                 jsonObj.put(ParamConstant.PARAM_VIMNAME, vimName);
327             }
328         } catch(JSONException e) {
329             LOGGER.error("getResources error:" + e);
330             throw new ServiceException(
331                     ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
332         }
333         return rsArray;
334     }
335
336     /**
337      * <br>
338      * 
339      * @param paramsMap
340      * @param params
341      * @return
342      * @since VFC 1.0
343      */
344     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
345         String url = paramsMap.get("url");
346         String methodType = paramsMap.get("methodType");
347
348         RestfulResponse rsp = null;
349         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
350         try {
351
352             RestfulParametes restfulParametes = new RestfulParametes();
353             Map<String, String> headerMap = new HashMap<>(3);
354             headerMap.put(CONTENT_TYPE, APPLICATION);
355             restfulParametes.setHeaderMap(headerMap);
356             restfulParametes.setRawData(params);
357
358             if(rest != null) {
359                 if(TYPE_GET.equalsIgnoreCase(methodType)) {
360                     rsp = rest.get(url, restfulParametes);
361                 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
362                     rsp = rest.post(url, restfulParametes);
363                 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
364                     rsp = rest.put(url, restfulParametes);
365                 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
366                     rsp = rest.delete(url, restfulParametes);
367                 }
368             }
369         } catch(ServiceException e) {
370             LOGGER.error("function=getRemoteResponse, get restful response catch exception {}", e);
371         }
372         return rsp;
373     }
374 }