-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathResponse.java
More file actions
72 lines (61 loc) · 1.81 KB
/
Response.java
File metadata and controls
72 lines (61 loc) · 1.81 KB
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
package com.rallydev.rest.response;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
/**
* Represents a WSAPI response.
*/
public abstract class Response {
private static final String ERRORS = "Errors";
private static final String WARNINGS = "Warnings";
protected JsonObject result;
protected String raw;
/**
* Create a new response from the specified JSON encoded string.
*
* @param response the JSON encoded string
*/
public Response(String response) {
this.raw = response;
this.result = ((JsonObject) new JsonParser().parse(response)).getAsJsonObject(getRoot());
}
/**
* Returns whether the response was successful (no errors)
*
* @return whether the response was successful
*/
public boolean wasSuccessful() {
return getErrors().length == 0;
}
/**
* Get any errors returned in the response.
*
* @return the response errors
*/
public String[] getErrors() {
return result.has(ERRORS) ? parseArray(ERRORS) : new String[0];
}
/**
* Get any warnings returned in the response.
*
* @return the response warnings
*/
public String[] getWarnings() {
return result.has(WARNINGS) ? parseArray(WARNINGS) : new String[0];
}
/**
* Get the name of the root JSON result
*
* @return the root element name
*/
protected abstract String getRoot();
private String[] parseArray(String key) {
List<String> elements = new ArrayList<String>();
for (JsonElement j : result.getAsJsonArray(key)) {
elements.add(j.getAsString());
}
return elements.toArray(new String[elements.size()]);
}
}