This repository has been archived by the owner on Jun 20, 2023. It is now read-only.
/
JestResult.java
376 lines (325 loc) · 12.8 KB
/
JestResult.java
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
package io.searchbox.client;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.searchbox.annotations.JestId;
import io.searchbox.annotations.JestVersion;
import io.searchbox.cloning.CloneUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @author Dogukan Sonmez
*/
public class JestResult {
public static final String ES_METADATA_ID = "es_metadata_id";
public static final String ES_METADATA_VERSION = "es_metadata_version";
private static final Logger log = LoggerFactory.getLogger(JestResult.class);
protected static class MetaField {
public final String internalFieldName;
public final String esFieldName;
public final Class<? extends Annotation> annotationClass;
MetaField(String internalFieldName, String esFieldName, Class<? extends Annotation> annotationClass) {
this.internalFieldName = internalFieldName;
this.esFieldName = esFieldName;
this.annotationClass = annotationClass;
}
}
protected static final ImmutableList<MetaField> META_FIELDS = ImmutableList.of(
new MetaField(ES_METADATA_ID, "_id", JestId.class),
new MetaField(ES_METADATA_VERSION, "_version", JestVersion.class)
);
protected JsonObject jsonObject;
protected String jsonString;
protected String pathToResult;
protected int responseCode;
protected boolean isSucceeded;
protected String errorMessage;
protected Gson gson;
private JestResult() {
}
public JestResult(JestResult source) {
this.jsonObject = source.jsonObject;
this.jsonString = source.jsonString;
this.pathToResult = source.pathToResult;
this.responseCode = source.responseCode;
this.isSucceeded = source.isSucceeded;
this.errorMessage = source.errorMessage;
this.gson = source.gson;
}
public JestResult(Gson gson) {
this.gson = gson;
}
public String getPathToResult() {
return pathToResult;
}
public void setPathToResult(String pathToResult) {
this.pathToResult = pathToResult;
}
public Object getValue(String key) {
return getJsonMap().get(key);
}
public boolean isSucceeded() {
return isSucceeded;
}
public void setSucceeded(boolean succeeded) {
isSucceeded = succeeded;
}
public String getJsonString() {
return jsonString;
}
public void setJsonString(String jsonString) {
this.jsonString = jsonString;
}
public String getErrorMessage() {
return errorMessage;
}
public int getResponseCode() {
return responseCode;
}
public void setResponseCode(int responseCode) {
this.responseCode = responseCode;
}
/**
* manually set an error message, eg. for the cases where non-200 response code is received
*/
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public JsonObject getJsonObject() {
return jsonObject;
}
public void setJsonObject(JsonObject jsonObject) {
this.jsonObject = jsonObject;
if (jsonObject.get("error") != null) {
errorMessage = jsonObject.get("error").toString();
}
}
@Deprecated
@SuppressWarnings("rawtypes")
public Map getJsonMap() {
return gson.fromJson(jsonObject, Map.class);
}
public void setJsonMap(Map<String, Object> resultMap) {
String json = gson.toJson(resultMap, Map.class);
setJsonObject(new JsonParser().parse(json).getAsJsonObject());
}
/**
* @return null if operation did not succeed or the response is null or the "keys" field of the action is empty or
* the response does not contain the key to source.
* String representing the source JSON element(s) otherwise.
* Elements are joined with a comma if there are multiple sources (e.g.: search with multiple hits).
*/
public String getSourceAsString() {
List<String> sources = getSourceAsStringList();
return sources == null ? null : Joiner.on(',').join(sources);
}
/**
* @return null if operation did not succeed or the response is null or the "keys" field of the action is empty or
* the response does not contain the key to source.
* List of strings representing the source JSON element(s) otherwise.
*/
public List<String> getSourceAsStringList() {
String[] keys = getKeys();
if (!isSucceeded || jsonObject == null || keys == null || keys.length == 0 || !jsonObject.has(keys[0])) {
return null;
}
List<String> sourceList = new ArrayList<String>();
for (JsonElement element : extractSource(false)) {
sourceList.add(element.toString());
}
return sourceList;
}
public <T> T getSourceAsObject(Class<T> clazz) {
return getSourceAsObject(clazz, true);
}
public <T> T getSourceAsObject(Class<T> clazz, boolean addEsMetadataFields) {
T sourceAsObject = null;
List<T> sources = getSourceAsObjectList(clazz, addEsMetadataFields);
if (sources.size() > 0) {
sourceAsObject = sources.get(0);
}
return sourceAsObject;
}
public <T> List<T> getSourceAsObjectList(Class<T> type) {
return getSourceAsObjectList(type, true);
}
public <T> List<T> getSourceAsObjectList(Class<T> type, boolean addEsMetadataFields) {
List<T> objectList = new ArrayList<T>();
if (isSucceeded) {
for (JsonElement source : extractSource(addEsMetadataFields)) {
T obj = createSourceObject(source, type);
if (obj != null) {
objectList.add(obj);
}
}
}
return objectList;
}
protected List<JsonElement> extractSource() {
return extractSource(true);
}
protected List<JsonElement> extractSource(boolean addEsMetadataFields) {
List<JsonElement> sourceList = new ArrayList<JsonElement>();
if (jsonObject != null) {
String[] keys = getKeys();
if (keys == null) {
sourceList.add(jsonObject);
} else {
String sourceKey = keys[keys.length - 1];
JsonElement obj = jsonObject.get(keys[0]);
if (keys.length > 1) {
for (int i = 1; i < keys.length - 1; i++) {
obj = ((JsonObject) obj).get(keys[i]);
}
if (obj.isJsonObject()) {
JsonElement source = obj.getAsJsonObject().get(sourceKey);
if (source != null) {
sourceList.add(source);
}
} else if (obj.isJsonArray()) {
for (JsonElement element : obj.getAsJsonArray()) {
if (element instanceof JsonObject) {
JsonObject currentObj = element.getAsJsonObject();
JsonObject source = currentObj.getAsJsonObject(sourceKey);
if (source != null) {
JsonObject copy = (JsonObject) CloneUtils.deepClone(source);
if (addEsMetadataFields) {
for (MetaField metaField : META_FIELDS) {
copy.add(metaField.internalFieldName, currentObj.get(metaField.esFieldName));
}
}
sourceList.add(copy);
}
}
}
}
} else if (obj != null) {
JsonElement copy = CloneUtils.deepClone(obj);
if (addEsMetadataFields && copy.isJsonObject()) {
JsonObject copyObject = copy.getAsJsonObject();
for (MetaField metaField : META_FIELDS) {
JsonElement metaElement = jsonObject.get(metaField.esFieldName);
if (metaElement != null) {
copyObject.add(metaField.internalFieldName, metaElement);
}
}
}
sourceList.add(copy);
}
}
}
return sourceList;
}
protected <T> T createSourceObject(JsonElement source, Class<T> type) {
T obj = null;
try {
obj = gson.fromJson(source, type);
// Check if JestId is visible
Class clazz = type;
int knownMetadataFieldsCount = META_FIELDS.size();
int foundFieldsCount = 0;
boolean allFieldsFound = false;
while (clazz != null && !allFieldsFound) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (foundFieldsCount == knownMetadataFieldsCount) {
allFieldsFound = true;
break;
}
for (MetaField metaField : META_FIELDS) {
if (field.isAnnotationPresent(metaField.annotationClass) && setAnnotatedField(obj, source, field, metaField.internalFieldName)) {
foundFieldsCount++;
}
}
}
clazz = clazz.getSuperclass();
}
} catch (Exception e) {
log.error("Unhandled exception occurred while converting source to the object ." + type.getCanonicalName(), e);
}
return obj;
}
private <T> boolean setAnnotatedField(T obj, JsonElement source, Field field, String fieldName) {
try {
field.setAccessible(true);
Object value = field.get(obj);
if (value == null) {
Class<?> fieldType = field.getType();
JsonElement element = ((JsonObject) source).get(fieldName);
field.set(obj, getAs(element, fieldType));
return true;
}
} catch (IllegalAccessException e) {
log.error("Unhandled exception occurred while setting annotated field from source");
}
return false;
}
@SuppressWarnings("unchecked")
private <T> T getAs(JsonElement id, Class<T> fieldType) throws IllegalAccessException {
if (id.isJsonNull()) {
return null;
}
if (fieldType.isAssignableFrom(String.class)) {
return (T) id.getAsString();
}
if (fieldType.isAssignableFrom(Number.class)) {
return (T) id.getAsNumber();
}
if (fieldType.isAssignableFrom(BigDecimal.class)) {
return (T) id.getAsBigDecimal();
}
if (fieldType.isAssignableFrom(Double.class)) {
Object o = id.getAsDouble();
return (T) o;
}
if (fieldType.isAssignableFrom(Float.class)) {
Object o = id.getAsFloat();
return (T) o;
}
if (fieldType.isAssignableFrom(BigInteger.class)) {
return (T) id.getAsBigInteger();
}
if (fieldType.isAssignableFrom(Long.class)) {
Object o = id.getAsLong();
return (T) o;
}
if (fieldType.isAssignableFrom(Integer.class)) {
Object o = id.getAsInt();
return (T) o;
}
if (fieldType.isAssignableFrom(Short.class)) {
Object o = id.getAsShort();
return (T) o;
}
if (fieldType.isAssignableFrom(Character.class)) {
return (T) (Character) id.getAsCharacter();
}
if (fieldType.isAssignableFrom(Byte.class)) {
return (T) (Byte) id.getAsByte();
}
if (fieldType.isAssignableFrom(Boolean.class)) {
return (T) (Boolean) id.getAsBoolean();
}
throw new RuntimeException("cannot assign " + id + " to " + fieldType);
}
protected String[] getKeys() {
return pathToResult == null ? null : pathToResult.split("/");
}
@Override
public String toString() {
return "Result: " + getJsonString()
+ ", isSucceeded: " + isSucceeded()
+ ", response code: " + getResponseCode()
+ ", error message: " + getErrorMessage();
}
}