blob: e26ea4fc3a2691e22e4efee0fe9ec5da12db5182 (
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
|
// Copyright 2016 Yahoo Inc. 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.util.JSONObjectWrapper;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
public class JsonHttpResult extends HttpResult {
private JSONObject json;
private boolean failedParsing = false;
public JsonHttpResult() {
addHeader("Content-Type", "application/json");
}
public JsonHttpResult(HttpResult other) {
super(other);
if (other.getContent() == null) {
setParsedJson(new JSONObject());
return;
}
try{
if (other.getContent() instanceof JSONObject) {
setParsedJson((JSONObject) other.getContent());
} else {
setParsedJson(new JSONObject(other.getContent().toString()));
}
} catch (JSONException e) {
failedParsing = true;
setParsedJson(createErrorJson(e.getMessage(), other));
}
}
private JSONObject createErrorJson(String error, HttpResult other) {
return new JSONObjectWrapper()
.put("error", "Invalid JSON in output: " + error)
.put("output", other.getContent().toString());
}
public JsonHttpResult setJson(JSONObject o) {
setContent(o);
json = o;
return this;
}
private void setParsedJson(JSONObject o) {
json = o;
}
public JSONObject getJson() {
return json;
}
@Override
public void printContent(StringBuilder sb) {
if (failedParsing) {
super.printContent(sb);
return;
}
if (json != null) {
sb.append("JSON: ");
try{
sb.append(json.toString(2));
} catch (JSONException e) {
sb.append(json.toString());
}
} else {
super.printContent(sb);
}
}
}
|