41ce7db931389e92c1cbedbf576e16d3c7fc9fe0
[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_HTTP = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
72
73     private static final Restful REST_CLIENT_HTTPS = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTPS);
74
75     private RestfulUtil() {
76     }
77
78     /**
79      * Get response object.<br>
80      *
81      * @param url
82      * @param type
83      * @return
84      * @since VFC 1.0
85      */
86     public static JSONObject getResponseObj(String url, String type) {
87         return getResponseObj(url, new RestfulParametes(), type);
88     }
89
90     /**
91      * Get response object.<br>
92      *
93      * @param url
94      * @param parametes
95      * @param type
96      * @return
97      * @since VFC 1.0
98      */
99     public static JSONObject getResponseObj(String url, RestfulParametes parametes, String type) {
100         try {
101             String content = RestfulUtil.getResponseContent(url, parametes, null, type);
102             LOGGER.error("function=getResponseObj, content : {}", content);
103             if(StringUtils.isEmpty(content)) {
104                 return null;
105             }
106             return JSONObject.fromObject(content);
107         } catch(JSONException e) {
108             LOGGER.error("function=getResponseObj, exception : {}", e);
109             return null;
110         }
111     }
112
113     /**
114      * Get response content.<br>
115      *
116      * @param url
117      * @param restParametes
118      * @param type
119      * @return
120      * @since VFC 1.0
121      */
122     public static String getResponseContent(String url, RestfulParametes restParametes, String type) {
123         return getResponseContent(url, restParametes, null, type);
124     }
125
126     /**
127      * Get response map.<br>
128      *
129      * @param url
130      * @param restParametes
131      * @param opt
132      * @param type
133      * @return
134      * @since VFC 1.0
135      */
136     public static Map<String, Object> getResponseMap(String url, RestfulParametes restParametes, RestfulOptions opt,
137             String type) {
138         RestfulResponse response = restfulResponse(url, restParametes, opt, type);
139         return getResponseMap(response);
140     }
141
142     /**
143      * Get response content map.<br>
144      *
145      * @param url
146      * @param type
147      * @return
148      * @since VFC 1.0
149      */
150     public static Map<String, Object> getResponseContentMap(String url, String type) {
151         RestfulResponse response = restfulResponse(url, new RestfulParametes(), null, type);
152         return getResponseMap(response);
153     }
154
155     private static Map<String, Object> getResponseMap(RestfulResponse response) {
156         Map<String, Object> resMap = new HashMap<>(10);
157         if(null != response) {
158             resMap.put(Constant.RESPONSE_CONTENT, response.getResponseContent());
159             resMap.put(Constant.STATUS_CODE, response.getStatus());
160         }
161         return resMap;
162     }
163
164     /**
165      * Get response content.<br>
166      *
167      * @param url
168      * @param restParametes
169      * @param opt
170      * @param type
171      * @return
172      * @since VFC 1.0
173      */
174     public static String getResponseContent(String url, RestfulParametes restParametes, RestfulOptions opt,
175             String type) {
176         String responseContent = null;
177         RestfulResponse rsp = restfulResponse(url, restParametes, opt, type);
178         if(rsp != null) {
179             int httpStatus = rsp.getStatus();
180             LOGGER.warn("function=getResponseContent, get response httpStatusCode : {} ", httpStatus);
181             if(httpStatus < HttpServletResponse.SC_BAD_REQUEST && httpStatus > 0) {
182                 responseContent = rsp.getResponseContent();
183                 LOGGER.warn("function=getResponseContent, get response data success!responseContent={}",
184                         responseContent);
185             }
186         }
187         return responseContent;
188     }
189
190     /**
191      * Get restful response.<br>
192      *
193      * @param url
194      * @param restParametes
195      * @param type
196      * @return
197      * @since VFC 1.0
198      */
199     public static RestfulResponse getRestfulResponse(String url, RestfulParametes restParametes, String type) {
200         return restfulResponse(url, restParametes, null, type);
201     }
202
203     private static RestfulResponse restfulResponse(String url, RestfulParametes restParametes, RestfulOptions opt,
204             String type) {
205         RestfulResponse rsp = new RestfulResponse();
206         try {
207             Restful restClient = url.startsWith("https") ? REST_CLIENT_HTTPS : REST_CLIENT_HTTP;
208
209             if(restClient != null) {
210                 if(TYPE_GET.equals(type)) {
211                     rsp = restClient.get(url, restParametes, opt);
212                 } else if(TYPE_POST.equals(type)) {
213                     rsp = restClient.post(url, restParametes, opt);
214                 } else if(TYPE_PUT.equals(type)) {
215                     rsp = restClient.put(url, restParametes, opt);
216                 } else if(TYPE_DEL.equals(type)) {
217                     rsp = restClient.delete(url, restParametes, opt);
218                 }
219             }
220         } catch(ServiceException e) {
221             LOGGER.error("function=restfulResponse, get restful response catch exception {} ", e);
222         }
223         LOGGER.warn("function=restfulResponse, response status is {} ", rsp.getStatus());
224         return rsp;
225     }
226
227     /**
228      * encapsulate the java reflect exception.<br>
229      *
230      * @param methodName, Restful's method.
231      * @param objects, method param array.
232      * @return
233      * @since VFC 1.0
234      */
235     public static RestfulResponse getRestRes(String methodName, Object... objects) {
236         try {
237             if(objects == null || REST_CLIENT_HTTP == null) {
238                 return null;
239             }
240
241             Class<?>[] classes = new Class[objects.length];
242             for(int i = 0; i < objects.length; i++) {
243                 classes[i] = objects[i].getClass();
244             }
245             if(methodName.startsWith("async")) {
246                 classes[classes.length - 1] = RestfulAsyncCallback.class;
247             }
248
249             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
250             MethodType mt = MethodType.methodType(rtType, classes);
251             Object result = MethodHandles.lookup().findVirtual(REST_CLIENT_HTTP.getClass(), methodName, mt)
252                     .bindTo(REST_CLIENT_HTTP).invokeWithArguments(objects);
253             if(result != null) {
254                 return (RestfulResponse)result;
255             }
256             LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
257                     methodName);
258             return null;
259         } catch(ReflectiveOperationException e) {
260             LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
261         } catch(Throwable e) {// NOSONAR
262             LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
263             try {
264                 throw (ServiceException)new ServiceException().initCause(e.getCause());
265             } catch(ServiceException se) {
266                 LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
267             }
268         }
269         return null;
270     }
271
272     /**
273      * Get response.<br>
274      *
275      * @param restParametes
276      * @param url
277      * @return
278      * @throws ServiceException
279      * @since VFC 1.0
280      */
281     public static JSONArray getResponseRes(RestfulParametes restParametes, String url) throws ServiceException {
282         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
283         if(null == result || result.isEmpty()) {
284             LOGGER.error("result from  url:" + url + " result:" + result);
285             throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
286         }
287
288         JSONArray rsArray = null;
289         try {
290             JSONObject rsJson = JSONObject.fromObject(result);
291             rsArray = rsJson.getJSONArray(ParamConstant.PARAM_DATA);
292         } catch(JSONException e) {
293             LOGGER.error("getResources error:" + e);
294             throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
295         }
296         return rsArray;
297     }
298
299     /**
300      * Get response.<br>
301      *
302      * @param restParametes
303      * @param url
304      * @param iResName
305      * @return
306      * @throws ServiceException
307      * @since VFC 1.0
308      */
309     public static JSONArray getResponseRes(RestfulParametes restParametes, String url, String iResName)
310             throws ServiceException {
311         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
312         if(null == result || result.isEmpty()) {
313             LOGGER.error("result from  url:" + url + " result:" + result);
314             throw new ServiceException(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(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
331         }
332         return rsArray;
333     }
334
335     /**
336      * <br>
337      * 
338      * @param paramsMap
339      * @param params
340      * @return
341      * @since VFC 1.0
342      */
343     public static RestfulResponse getRemoteResponse(Map<String, String> paramsMap, String params) {
344         String url = paramsMap.get("url");
345         String methodType = paramsMap.get("methodType");
346
347         RestfulResponse rsp = null;
348         Restful rest = RestfulFactory.getRestInstance(RestfulFactory.PROTO_HTTP);
349         try {
350
351             RestfulParametes restfulParametes = new RestfulParametes();
352             Map<String, String> headerMap = new HashMap<>(3);
353             headerMap.put(CONTENT_TYPE, APPLICATION);
354             restfulParametes.setHeaderMap(headerMap);
355             restfulParametes.setRawData(params);
356
357             if(rest != null) {
358                 if(TYPE_GET.equalsIgnoreCase(methodType)) {
359                     rsp = rest.get(url, restfulParametes);
360                 } else if(TYPE_POST.equalsIgnoreCase(methodType)) {
361                     rsp = rest.post(url, restfulParametes);
362                 } else if(TYPE_PUT.equalsIgnoreCase(methodType)) {
363                     rsp = rest.put(url, restfulParametes);
364                 } else if(TYPE_DEL.equalsIgnoreCase(methodType)) {
365                     rsp = rest.delete(url, restfulParametes);
366                 }
367             }
368         } catch(ServiceException e) {
369             LOGGER.error("function=getRemoteResponse, get restful response catch exception {}", e);
370         }
371         return rsp;
372     }
373 }