a8f34ceaed57184f7676c366cccf1f79eb49832a
[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 {}, context is {} ", rsp.getStatus(),
224                 rsp.getResponseContent());
225         return rsp;
226     }
227
228     /**
229      * encapsulate the java reflect exception.<br>
230      *
231      * @param methodName, Restful's method.
232      * @param objects, method param array.
233      * @return
234      * @since VFC 1.0
235      */
236     public static RestfulResponse getRestRes(String methodName, Object... objects) {
237         try {
238             if(objects == null || REST_CLIENT_HTTP == null) {
239                 return null;
240             }
241
242             Class<?>[] classes = new Class[objects.length];
243             for(int i = 0; i < objects.length; i++) {
244                 classes[i] = objects[i].getClass();
245             }
246             if(methodName.startsWith("async")) {
247                 classes[classes.length - 1] = RestfulAsyncCallback.class;
248             }
249
250             Class<?> rtType = methodName.startsWith("async") ? void.class : RestfulResponse.class;
251             MethodType mt = MethodType.methodType(rtType, classes);
252             Object result = MethodHandles.lookup().findVirtual(REST_CLIENT_HTTP.getClass(), methodName, mt)
253                     .bindTo(REST_CLIENT_HTTP).invokeWithArguments(objects);
254             if(result != null) {
255                 return (RestfulResponse)result;
256             }
257             LOGGER.warn("function=getRestRes, msg: invoke Restful async {} method which return type is Void.",
258                     methodName);
259             return null;
260         } catch(ReflectiveOperationException e) {
261             LOGGER.error("function=getRestRes, msg=error occurs, e={}.", e);
262         } catch(Throwable e) {// NOSONAR
263             LOGGER.error("function=getRestRes, msg=Throwable, e={}.", e);
264             try {
265                 throw (ServiceException)new ServiceException().initCause(e.getCause());
266             } catch(ServiceException se) {
267                 LOGGER.error("function=getRestRes, msg=ServiceException occurs, e={}.", se);
268             }
269         }
270         return null;
271     }
272
273     /**
274      * Get response.<br>
275      *
276      * @param restParametes
277      * @param url
278      * @return
279      * @throws ServiceException
280      * @since VFC 1.0
281      */
282     public static JSONArray getResponseRes(RestfulParametes restParametes, String url) throws ServiceException {
283         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
284         if(null == result || result.isEmpty()) {
285             LOGGER.error("result from  url:" + url + " result:" + result);
286             throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
287         }
288
289         JSONArray rsArray = null;
290         try {
291             JSONObject rsJson = JSONObject.fromObject(result);
292             rsArray = rsJson.getJSONArray(ParamConstant.PARAM_DATA);
293         } catch(JSONException e) {
294             LOGGER.error("getResources error:" + e);
295             throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
296         }
297         return rsArray;
298     }
299
300     /**
301      * Get response.<br>
302      *
303      * @param restParametes
304      * @param url
305      * @param iResName
306      * @return
307      * @throws ServiceException
308      * @since VFC 1.0
309      */
310     public static JSONArray getResponseRes(RestfulParametes restParametes, String url, String iResName)
311             throws ServiceException {
312         String result = getResponseContent(url, restParametes, RestfulUtil.TYPE_GET);
313         if(null == result || result.isEmpty()) {
314             LOGGER.error("result from  url:" + url + " result:" + result);
315             throw new ServiceException(ResourceUtil.getMessage(NO_RESULT_EXCEPTION));
316         }
317
318         JSONArray rsArray = null;
319         try {
320             JSONObject rsJson = JSONObject.fromObject(result);
321             rsArray = rsJson.getJSONArray(iResName);
322             String vimId = rsJson.getString(ParamConstant.PARAM_VIMID);
323             String vimName = rsJson.getString(ParamConstant.PARAM_VIMNAME);
324             for(int i = 0; i < rsArray.size(); i++) {
325                 JSONObject jsonObj = rsArray.getJSONObject(i);
326                 jsonObj.put(ParamConstant.PARAM_VIMID, vimId);
327                 jsonObj.put(ParamConstant.PARAM_VIMNAME, vimName);
328             }
329         } catch(JSONException e) {
330             LOGGER.error("getResources error:" + e);
331             throw new ServiceException(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 }