-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathInfluxDBResultMapper.java
393 lines (356 loc) · 16 KB
/
InfluxDBResultMapper.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* The MIT License (MIT)
*
* Copyright (c) 2017 azeti Networks AG (<[email protected]>)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.influxdb.impl;
import org.influxdb.InfluxDBMapperException;
import org.influxdb.annotation.Column;
import org.influxdb.annotation.Exclude;
import org.influxdb.annotation.Measurement;
import org.influxdb.dto.QueryResult;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.time.Instant;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.temporal.ChronoField;
import java.util.LinkedList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
/**
* Main class responsible for mapping a QueryResult to a POJO.
*
* @author fmachado
*/
public class InfluxDBResultMapper {
/**
* Data structure used to cache classes used as measurements.
*/
private static class ClassInfo {
ConcurrentMap<String, Field> fieldMap;
ConcurrentMap<Field, TypeMapper> typeMappers;
}
private static final
ConcurrentMap<String, ClassInfo> CLASS_INFO_CACHE = new ConcurrentHashMap<>();
private static final int FRACTION_MIN_WIDTH = 0;
private static final int FRACTION_MAX_WIDTH = 9;
private static final boolean ADD_DECIMAL_POINT = true;
/**
* When a query is executed without {@link TimeUnit}, InfluxDB returns the <code>time</code>
* column as a RFC3339 date.
*/
private static final DateTimeFormatter RFC3339_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd'T'HH:mm:ss")
.appendFraction(ChronoField.NANO_OF_SECOND, FRACTION_MIN_WIDTH, FRACTION_MAX_WIDTH, ADD_DECIMAL_POINT)
.appendZoneOrOffsetId()
.toFormatter();
/**
* <p>
* Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
* data structure and creating the respective object instances based on the Class passed as
* parameter.
* </p>
*
* @param queryResult the InfluxDB result object
* @param clazz the Class that will be used to hold your measurement data
* @param <T> the target type
*
* @return a {@link List} of objects from the same Class passed as parameter and sorted on the
* same order as received from InfluxDB.
*
* @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
* <code>clazz</code> parameter is not annotated with @Measurement or it was not
* possible to define the values of your POJO (e.g. due to an unsupported field type).
*/
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz) throws InfluxDBMapperException {
return toPOJO(queryResult, clazz, TimeUnit.MILLISECONDS);
}
/**
* <p>
* Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
* data structure and creating the respective object instances based on the Class passed as
* parameter.
* </p>
*
* @param queryResult the InfluxDB result object
* @param clazz the Class that will be used to hold your measurement data
* @param precision the time precision of results
* @param <T> the target type
*
* @return a {@link List} of objects from the same Class passed as parameter and sorted on the
* same order as received from InfluxDB.
*
* @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
* <code>clazz</code> parameter is not annotated with @Measurement or it was not
* possible to define the values of your POJO (e.g. due to an unsupported field type).
*/
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz,
final TimeUnit precision) throws InfluxDBMapperException {
throwExceptionIfMissingAnnotation(clazz);
String measurementName = getMeasurementName(clazz);
return this.toPOJO(queryResult, clazz, measurementName, precision);
}
/**
* <p>
* Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
* data structure and creating the respective object instances based on the Class passed as
* parameter.
* </p>
*
* @param queryResult the InfluxDB result object
* @param clazz the Class that will be used to hold your measurement data
* @param <T> the target type
* @param measurementName name of the Measurement
*
* @return a {@link List} of objects from the same Class passed as parameter and sorted on the
* same order as received from InfluxDB.
*
* @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
* <code>clazz</code> parameter is not annotated with @Measurement or it was not
* possible to define the values of your POJO (e.g. due to an unsupported field type).
*/
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz, final String measurementName)
throws InfluxDBMapperException {
return toPOJO(queryResult, clazz, measurementName, TimeUnit.MILLISECONDS);
}
/**
* <p>
* Process a {@link QueryResult} object returned by the InfluxDB client inspecting the internal
* data structure and creating the respective object instances based on the Class passed as
* parameter.
* </p>
*
* @param queryResult the InfluxDB result object
* @param clazz the Class that will be used to hold your measurement data
* @param <T> the target type
* @param measurementName name of the Measurement
* @param precision the time precision of results
*
* @return a {@link List} of objects from the same Class passed as parameter and sorted on the
* same order as received from InfluxDB.
*
* @throws InfluxDBMapperException If {@link QueryResult} parameter contain errors,
* <code>clazz</code> parameter is not annotated with @Measurement or it was not
* possible to define the values of your POJO (e.g. due to an unsupported field type).
*/
public <T> List<T> toPOJO(final QueryResult queryResult, final Class<T> clazz, final String measurementName,
final TimeUnit precision)
throws InfluxDBMapperException {
Objects.requireNonNull(measurementName, "measurementName");
Objects.requireNonNull(queryResult, "queryResult");
Objects.requireNonNull(clazz, "clazz");
throwExceptionIfResultWithError(queryResult);
cacheMeasurementClass(clazz);
List<T> result = new LinkedList<T>();
queryResult.getResults().stream()
.filter(internalResult -> Objects.nonNull(internalResult) && Objects.nonNull(internalResult.getSeries()))
.forEach(internalResult -> {
internalResult.getSeries().stream()
.filter(series -> series.getName().equals(measurementName))
.forEachOrdered(series -> {
parseSeriesAs(series, clazz, result, precision);
});
});
return result;
}
void throwExceptionIfMissingAnnotation(final Class<?> clazz) {
if (!clazz.isAnnotationPresent(Measurement.class)) {
throw new IllegalArgumentException(
"Class " + clazz.getName() + " is not annotated with @" + Measurement.class.getSimpleName());
}
}
void throwExceptionIfResultWithError(final QueryResult queryResult) {
if (queryResult.getError() != null) {
throw new InfluxDBMapperException("InfluxDB returned an error: " + queryResult.getError());
}
queryResult.getResults().forEach(seriesResult -> {
if (seriesResult.getError() != null) {
throw new InfluxDBMapperException("InfluxDB returned an error with Series: " + seriesResult.getError());
}
});
}
void cacheMeasurementClass(final Class<?>... classVarAgrs) {
for (Class<?> clazz : classVarAgrs) {
if (CLASS_INFO_CACHE.containsKey(clazz.getName())) {
continue;
}
ConcurrentMap<String, Field> fieldMap = new ConcurrentHashMap<>();
ConcurrentMap<Field, TypeMapper> typeMappers = new ConcurrentHashMap<>();
Measurement measurement = clazz.getAnnotation(Measurement.class);
boolean allFields = measurement != null && measurement.allFields();
Class<?> c = clazz;
TypeMapper typeMapper = TypeMapper.empty();
while (c != null) {
for (Field field : c.getDeclaredFields()) {
Column colAnnotation = field.getAnnotation(Column.class);
if (colAnnotation == null && !(allFields
&& !field.isAnnotationPresent(Exclude.class) && !Modifier.isStatic(field.getModifiers()))) {
continue;
}
fieldMap.put(getFieldName(field, colAnnotation), field);
typeMappers.put(field, typeMapper);
}
Class<?> superclass = c.getSuperclass();
Type genericSuperclass = c.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
typeMapper = TypeMapper.of((ParameterizedType) genericSuperclass, superclass);
} else {
typeMapper = TypeMapper.empty();
}
c = superclass;
}
ClassInfo classInfo = new ClassInfo();
classInfo.fieldMap = fieldMap;
classInfo.typeMappers = typeMappers;
CLASS_INFO_CACHE.putIfAbsent(clazz.getName(), classInfo);
}
}
private static String getFieldName(final Field field, final Column colAnnotation) {
if (colAnnotation != null && !colAnnotation.name().isEmpty()) {
return colAnnotation.name();
}
return field.getName();
}
String getMeasurementName(final Class<?> clazz) {
return ((Measurement) clazz.getAnnotation(Measurement.class)).name();
}
String getDatabaseName(final Class<?> clazz) {
return ((Measurement) clazz.getAnnotation(Measurement.class)).database();
}
String getRetentionPolicy(final Class<?> clazz) {
return ((Measurement) clazz.getAnnotation(Measurement.class)).retentionPolicy();
}
<T> List<T> parseSeriesAs(final QueryResult.Series series, final Class<T> clazz, final List<T> result) {
return parseSeriesAs(series, clazz, result, TimeUnit.MILLISECONDS);
}
<T> List<T> parseSeriesAs(final QueryResult.Series series, final Class<T> clazz, final List<T> result,
final TimeUnit precision) {
int columnSize = series.getColumns().size();
ClassInfo classInfo = CLASS_INFO_CACHE.get(clazz.getName());
try {
T object = null;
for (List<Object> row : series.getValues()) {
for (int i = 0; i < columnSize; i++) {
Field correspondingField = classInfo.fieldMap.get(series.getColumns().get(i)/*InfluxDB columnName*/);
if (correspondingField != null) {
if (object == null) {
object = clazz.newInstance();
}
setFieldValue(object, correspondingField, row.get(i), precision,
classInfo.typeMappers.get(correspondingField));
}
}
// When the "GROUP BY" clause is used, "tags" are returned as Map<String,String> and
// accordingly with InfluxDB documentation
// https://docs.influxdata.com/influxdb/v1.2/concepts/glossary/#tag-value
// "tag" values are always String.
if (series.getTags() != null && !series.getTags().isEmpty()) {
for (Entry<String, String> entry : series.getTags().entrySet()) {
Field correspondingField = classInfo.fieldMap.get(entry.getKey()/*InfluxDB columnName*/);
if (correspondingField != null) {
// I don't think it is possible to reach here without a valid "object"
setFieldValue(object, correspondingField, entry.getValue(), precision,
classInfo.typeMappers.get(correspondingField));
}
}
}
if (object != null) {
result.add(object);
object = null;
}
}
} catch (InstantiationException | IllegalAccessException e) {
throw new InfluxDBMapperException(e);
}
return result;
}
/**
* InfluxDB client returns any number as Double.
* See <a href="https://github.com/influxdata/influxdb-java/issues/153#issuecomment-259681987">...</a>
* for more information.
*
*/
private static <T> void setFieldValue(final T object, final Field field, final Object value, final TimeUnit precision,
final TypeMapper typeMapper)
throws IllegalArgumentException, IllegalAccessException {
if (value == null) {
return;
}
Type fieldType = typeMapper.resolve(field.getGenericType());
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(object, adaptValue((Class<?>) fieldType, value, precision, field.getName(), object.getClass().getName()));
}
private static Object adaptValue(final Class<?> fieldType, final Object value, final TimeUnit precision,
final String fieldName, final String className) {
try {
if (String.class.isAssignableFrom(fieldType)) {
return String.valueOf(value);
}
if (Instant.class.isAssignableFrom(fieldType)) {
if (value instanceof String) {
return Instant.from(RFC3339_FORMATTER.parse(String.valueOf(value)));
}
if (value instanceof Long) {
return Instant.ofEpochMilli(toMillis((long) value, precision));
}
if (value instanceof Double) {
return Instant.ofEpochMilli(toMillis(((Double) value).longValue(), precision));
}
if (value instanceof Integer) {
return Instant.ofEpochMilli(toMillis(((Integer) value).longValue(), precision));
}
throw new InfluxDBMapperException("Unsupported type " + fieldType + " for field " + fieldName);
}
if (Double.class.isAssignableFrom(fieldType) || double.class.isAssignableFrom(fieldType)) {
return value;
}
if (Long.class.isAssignableFrom(fieldType) || long.class.isAssignableFrom(fieldType)) {
return ((Double) value).longValue();
}
if (Integer.class.isAssignableFrom(fieldType) || int.class.isAssignableFrom(fieldType)) {
return ((Double) value).intValue();
}
if (Boolean.class.isAssignableFrom(fieldType) || boolean.class.isAssignableFrom(fieldType)) {
return Boolean.valueOf(String.valueOf(value));
}
if (Enum.class.isAssignableFrom(fieldType)) {
//noinspection unchecked
return Enum.valueOf((Class<Enum>) fieldType, String.valueOf(value));
}
} catch (ClassCastException e) {
String msg = "Class '%s' field '%s' was defined with a different field type and caused a ClassCastException. "
+ "The correct type is '%s' (current field value: '%s').";
throw new InfluxDBMapperException(
String.format(msg, className, fieldName, value.getClass().getName(), value));
}
throw new InfluxDBMapperException(
String.format("Class '%s' field '%s' is from an unsupported type '%s'.", className, fieldName, fieldType));
}
private static long toMillis(final long value, final TimeUnit precision) {
return TimeUnit.MILLISECONDS.convert(value, precision);
}
}