2 * Copyright 2017 [ZTE] and others.
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5 * in compliance with the License. You may obtain a copy of the License at
7 * http://www.apache.org/licenses/LICENSE-2.0
9 * Unless required by applicable law or agreed to in writing, software distributed under the License
10 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11 * or implied. See the License for the specific language governing permissions and limitations under
14 package org.onap.workflow.activitiext.restservicetask;
16 import org.apache.commons.httpclient.HttpClient;
17 import org.apache.commons.httpclient.HttpMethod;
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
21 import com.alibaba.fastjson.JSON;
24 * This static-class eases HTTP-method execution by self-managed fault-handling
25 * and automated Response-information processing
27 public class LowLevelRestApi {
29 private static final Logger logger = LoggerFactory.getLogger(LowLevelRestApi.class);
31 // Local HttpClient used for every communication (Singleton implementation)
32 private static HttpClient httpClient = new HttpClient();
35 * Executes a passed HttpMethod (Method type is either PUT, POST, GET or
36 * DELETE) and returns a HttpResponseMessage
40 * @return HttpResponseMessage which contains all information about the
43 public static HttpResponseMessage executeHttpMethod(HttpMethod method) throws Exception {
45 HttpResponseMessage responseMessage = null;
50 LowLevelRestApi.httpClient.executeMethod(method);
51 responseMessage = LowLevelRestApi.extractResponseInformation(method);
53 logger.info("statusCode: {}", method.getStatusCode());
54 logger.info("responseBody: {}", method.getResponseBodyAsString());
55 } catch (Exception e) {
56 logger.error("visit interface failed!", e);
60 // Release Connection anyway
61 method.releaseConnection();
64 // Extract response information and return
65 return responseMessage;
69 * Extracts the response information from an executed HttpMethod
73 * @return Packaged response information
75 private static HttpResponseMessage extractResponseInformation(HttpMethod method) {
76 // Create and return HttpResponseMethod
77 HttpResponseMessage responseMessage = new HttpResponseMessage();
78 responseMessage.setStatusCode(method.getStatusCode());
80 JSON json = (JSON) JSON.parse(method.getResponseBodyAsString());
81 responseMessage.setResponseBody(json);
83 } catch (Exception e) {
84 logger.info("response is not a json!");
86 return responseMessage;