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