blob: 1aa1c002fbdb9d62a4f7f7b58cd2ba24808b9aa1 (
plain) (
blame)
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
|
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.clustercontroller.utils.communication.http;
import com.yahoo.vespa.clustercontroller.utils.communication.async.AsyncOperation;
import com.yahoo.vespa.clustercontroller.utils.communication.async.RedirectedAsyncOperation;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
/**
* Wrapped for the HTTP client, converting requests to/from JSON.
*/
public class JsonAsyncHttpClient implements AsyncHttpClient<JsonHttpResult> {
private AsyncHttpClient<HttpResult> client;
private boolean verifyRequestContentAsJson = true;
private boolean addJsonContentType = true;
public JsonAsyncHttpClient(AsyncHttpClient<HttpResult> client) {
this.client = client;
}
public JsonAsyncHttpClient verifyRequestContentAsJson(boolean doIt) {
verifyRequestContentAsJson = doIt;
return this;
}
public JsonAsyncHttpClient addJsonContentType(boolean doIt) {
addJsonContentType = doIt;
return this;
}
public AsyncOperation<JsonHttpResult> execute(HttpRequest r) {
if (verifyRequestContentAsJson) {
if (r.getPostContent() != null && !(r.getPostContent() instanceof JSONObject)) {
try{
r = r.clone().setPostContent(new JSONObject(r.getPostContent().toString()));
} catch (JSONException e) {
throw new IllegalArgumentException(e);
}
}
}
if (addJsonContentType && r.getPostContent() != null) {
r = r.clone().addHttpHeader("Content-Type", "application/json");
}
final AsyncOperation<HttpResult> op = client.execute(r);
return new RedirectedAsyncOperation<HttpResult, JsonHttpResult>(op) {
@Override
public JsonHttpResult getResult() {
return (op.getResult() == null ? null : new JsonHttpResult(op.getResult()));
}
};
}
@Override
public void close() {
client.close();
}
}
|