2 * ============LICENSE_START=======================================================
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * 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
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 * ============LICENSE_END=========================================================
18 package com.woorea.openstack.connector;
20 import org.apache.http.Header;
21 import org.apache.http.HttpResponse;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.woorea.openstack.base.client.OpenStackResponse;
28 import java.io.ByteArrayInputStream;
29 import java.io.ByteArrayOutputStream;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.util.HashMap;
35 public class HttpClientResponse implements OpenStackResponse {
37 private static Logger logger = LoggerFactory.getLogger(HttpClientConnector.class);
39 private HttpResponse response = null;
40 private String entityBody = null;
42 public HttpClientResponse(HttpResponse response)
44 this.response = response;
46 // Read the body so InputStream can be closed
47 if (response.getEntity() == null) {
49 logger.debug ("No Response Body");
53 ByteArrayOutputStream responseBody = new ByteArrayOutputStream();
55 response.getEntity().writeTo(responseBody);
56 } catch (IOException e) {
57 throw new HttpClientException ("Error Reading Response Body", e);
59 entityBody = responseBody.toString();
60 logger.debug (entityBody);
65 public <T> T getEntity (Class<T> returnType) {
66 // Get appropriate mapper, based on existence of a root element
67 ObjectMapper mapper = HttpClientConnector.getObjectMapper (returnType);
71 resp = mapper.readValue(entityBody, returnType);
72 } catch (Exception e) {
73 throw new HttpClientException ("Caught exception in getEntity", e);
79 public <T> T getErrorEntity(Class<T> returnType) {
80 return getEntity(returnType);
84 public InputStream getInputStream() {
85 return new ByteArrayInputStream (entityBody.getBytes());
89 public String header(String name) {
90 return response.getFirstHeader(name).getValue();
94 public Map<String, String> headers() {
95 Map<String, String> headers = new HashMap<>();
97 Header[] responseHeaders = response.getAllHeaders();
98 for (Header h : responseHeaders) {
99 headers.put(h.getName(), h.getValue());