blob: f3234f8def80832c3a9dcff61f799527db14ec06 (
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
|
package cgeo.geocaching.connector.oc;
import cgeo.geocaching.utils.Log;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
/**
* Handles the JSON error response from OKAPI
*/
public class OkapiError {
/**
* List of detected errors OKAPI might return
*/
public enum OkapiErrors {
NO_ERROR,
UNSPECIFIED,
INVALID_TIMESTAMP,
INVALID_TOKEN;
}
@NonNull private final OkapiErrors state;
@NonNull private final String message;
public OkapiError(@Nullable final ObjectNode data) {
// A null-response is by definition an error (some exception occurred somewhere in the flow)
if (data == null) {
state = OkapiErrors.UNSPECIFIED;
message = StringUtils.EMPTY;
return;
}
// Second possibility: we get an error object as return (@see http://opencaching.pl/okapi/introduction.html#errors)
if (data.has("error")) {
String localmessage = null;
OkapiErrors localstate = OkapiErrors.UNSPECIFIED;
try {
final ObjectNode error = (ObjectNode) data.get("error");
// Check reason_stack element to look for the specific oauth problems we want to report back
if (error.has("reason_stack")) {
final String reason = error.get("reason_stack").asText();
if (StringUtils.contains(reason, "invalid_oauth_request")) {
if (StringUtils.contains(reason, "invalid_timestamp")) {
localstate = OkapiErrors.INVALID_TIMESTAMP;
} else if (StringUtils.contains(reason, "invalid_token")) {
localstate = OkapiErrors.INVALID_TOKEN;
}
}
}
// Check if we can extract a message as well
if (error.has("developer_message")) {
localmessage = error.get("developer_message").asText();
assert localmessage != null; // by virtue of defaultString
}
} catch (ClassCastException | NullPointerException ex) {
Log.d("OkapiError: Failed to parse JSON", ex);
localstate = OkapiErrors.UNSPECIFIED;
}
state = localstate;
message = StringUtils.defaultString(localmessage);
return;
}
// Third possibility: some other response, everything is fine!
state = OkapiErrors.NO_ERROR;
message = StringUtils.EMPTY;
}
public boolean isError() {
return state != OkapiErrors.NO_ERROR;
}
@NonNull
public OkapiErrors getResult() {
return state;
}
@NonNull
public String getMessage() {
return message;
}
}
|