1 package com.atlassian.plugins.rest.module.jersey;
2
3 import com.atlassian.sal.api.net.Response;
4 import com.atlassian.sal.api.net.ResponseException;
5
6 import javax.ws.rs.core.HttpHeaders;
7 import javax.ws.rs.core.MediaType;
8 import java.io.IOException;
9 import java.io.InputStream;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.List;
13 import java.util.Map;
14
15 public class JerseyResponse implements Response
16 {
17 private final Response delegateResponse;
18 private final JerseyEntityHandler jerseyEntityHandler;
19
20 public JerseyResponse(Response delegateResponse, JerseyEntityHandler jerseyEntityHandler)
21 {
22 this.delegateResponse = delegateResponse;
23 this.jerseyEntityHandler = jerseyEntityHandler;
24 }
25
26 public <T> T getEntity(final Class<T> entityClass) throws ResponseException
27 {
28 Map<String, String> headers = getHeaders();
29 Map<String, List<String>> headerListMap = new HashMap<String, List<String>>();
30 for (final Map.Entry<String, String> entry : headers.entrySet())
31 {
32 headerListMap.put(entry.getKey(), Collections.singletonList(entry.getValue()));
33 }
34 String contentType = HeaderHelper.getSingleHeaderValue(headerListMap, HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_XML);
35 InputStream entityStream = getResponseBodyAsStream();
36 try
37 {
38 return jerseyEntityHandler.unmarshall(entityClass, MediaType.valueOf(contentType), entityStream, headerListMap);
39 }
40 catch (IOException e)
41 {
42 throw new EntityConversionException(e);
43 }
44 }
45
46 public int getStatusCode()
47 {
48 return delegateResponse.getStatusCode();
49 }
50
51 public String getResponseBodyAsString()
52 throws ResponseException
53 {
54 return delegateResponse.getResponseBodyAsString();
55 }
56
57 public InputStream getResponseBodyAsStream()
58 throws ResponseException
59 {
60 return delegateResponse.getResponseBodyAsStream();
61 }
62
63 public String getStatusText()
64 {
65 return delegateResponse.getStatusText();
66 }
67
68 public boolean isSuccessful()
69 {
70 return delegateResponse.isSuccessful();
71 }
72
73 public String getHeader(final String s)
74 {
75 return delegateResponse.getHeader(s);
76 }
77
78 public Map<String, String> getHeaders()
79 {
80 return delegateResponse.getHeaders();
81 }
82 }