blob: 8eee6d310a1066d6863d30b5a604f55d14cc533d (
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
|
/*
* Copyright 2013 Jesse Morgan
*/
package com.p4square.grow.frontend;
import java.io.IOException;
import com.fasterxml.jackson.databind.JavaType;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.data.Method;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import com.p4square.grow.provider.JsonEncodedProvider;
/**
* Fetch a JSON object via a Request.
*
* @author Jesse Morgan <jesse@jesterpm.net>
*/
public class JsonRequestProvider<V> extends JsonEncodedProvider<String, V> {
private final Restlet mDispatcher;
public JsonRequestProvider(Restlet dispatcher, Class<V> clazz) {
super(clazz);
mDispatcher = dispatcher;
}
public JsonRequestProvider(Restlet dispatcher, JavaType type) {
super(type);
mDispatcher = dispatcher;
}
@Override
public V get(String url) throws IOException {
Request request = new Request(Method.GET, url);
Response response = mDispatcher.handle(request);
Representation representation = response.getEntity();
if (!response.getStatus().isSuccess()) {
if (representation != null) {
representation.release();
}
throw new IOException("Could not get object. " + response.getStatus());
}
return decode(representation.getText());
}
@Override
public void put(String url, V obj) throws IOException {
final Request request = new Request(Method.PUT, url);
request.setEntity(new StringRepresentation(encode(obj)));
final Response response = mDispatcher.handle(request);
if (!response.getStatus().isSuccess()) {
throw new IOException("Could not put object. " + response.getStatus());
}
}
}
|