blob: b9cb58752e3b47896d9a92d401f01dc3eb0df846 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
|
/*
* Copyright 2013 Jesse Morgan
*/
package com.p4square.fmfacade.json;
import java.util.Map;
import java.io.IOException;
import org.restlet.data.Status;
import org.restlet.data.Reference;
import org.restlet.representation.Representation;
import org.restlet.Response;
import org.restlet.ext.jackson.JacksonRepresentation;
/**
* JsonResponse wraps a Restlet Response object and parses the entity, if any,
* as a JSON map.
*
* @author Jesse Morgan <jesse@jesterpm.net>
*/
public class JsonResponse {
private final Response mResponse;
private final Representation mRepresentation;
private Map<String, Object> mMap;
JsonResponse(Response response) {
mResponse = response;
mRepresentation = response.getEntity();
mMap = null;
if (!response.getStatus().isSuccess()) {
if (mRepresentation != null) {
mRepresentation.release();
}
}
}
/**
* @return the Status info from the response.
*/
public Status getStatus() {
return mResponse.getStatus();
}
/**
* @return the Reference for a redirect.
*/
public Reference getRedirectLocation() {
return mResponse.getLocationRef();
}
/**
* Return the parsed json map from the response.
*/
public Map<String, Object> getMap() throws ClientException {
if (mMap == null) {
Representation representation = mRepresentation;
// Parse response
if (representation == null) {
return null;
}
JacksonRepresentation<Map> mapRepresentation;
if (representation instanceof JacksonRepresentation) {
mapRepresentation = (JacksonRepresentation<Map>) representation;
} else {
mapRepresentation = new JacksonRepresentation<Map>(
representation, Map.class);
}
try {
mMap = (Map<String, Object>) mapRepresentation.getObject();
} catch (IOException e) {
throw new ClientException("Failed to parse response: " + e.getMessage(), e);
}
}
return mMap;
}
}
|