forked from apache/beam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
POJOUtils.java
434 lines (392 loc) · 17.6 KB
/
POJOUtils.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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.sdk.schemas.utils;
import com.google.common.collect.Maps;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import net.bytebuddy.ByteBuddy;
import net.bytebuddy.description.field.FieldDescription.ForLoadedField;
import net.bytebuddy.description.type.TypeDescription.ForLoadedType;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.dynamic.loading.ClassLoadingStrategy;
import net.bytebuddy.dynamic.scaffold.InstrumentedType;
import net.bytebuddy.implementation.FixedValue;
import net.bytebuddy.implementation.Implementation;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
import net.bytebuddy.implementation.bytecode.ByteCodeAppender.Size;
import net.bytebuddy.implementation.bytecode.Duplication;
import net.bytebuddy.implementation.bytecode.StackManipulation;
import net.bytebuddy.implementation.bytecode.TypeCreation;
import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
import net.bytebuddy.implementation.bytecode.collection.ArrayAccess;
import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
import net.bytebuddy.implementation.bytecode.member.FieldAccess;
import net.bytebuddy.implementation.bytecode.member.MethodInvocation;
import net.bytebuddy.implementation.bytecode.member.MethodReturn;
import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
import net.bytebuddy.matcher.ElementMatchers;
import org.apache.beam.sdk.annotations.Experimental;
import org.apache.beam.sdk.annotations.Experimental.Kind;
import org.apache.beam.sdk.schemas.FieldValueGetter;
import org.apache.beam.sdk.schemas.FieldValueSetter;
import org.apache.beam.sdk.schemas.FieldValueTypeInformation;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.SchemaUserTypeCreator;
import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertType;
import org.apache.beam.sdk.schemas.utils.ByteBuddyUtils.ConvertValueForGetter;
import org.apache.beam.sdk.schemas.utils.ReflectUtils.ClassWithSchema;
import org.apache.beam.sdk.schemas.utils.StaticSchemaInference.TypeInformation;
import org.apache.beam.sdk.util.common.ReflectHelpers;
import org.apache.beam.sdk.values.TypeDescriptor;
/** A set of utilities yo generate getter and setter classes for POJOs. */
@Experimental(Kind.SCHEMAS)
public class POJOUtils {
public static Schema schemaFromPojoClass(Class<?> clazz) {
// We should cache the field order.
Function<Class, List<TypeInformation>> getTypesForClass =
c ->
ReflectUtils.getFields(c)
.stream()
.map(TypeInformation::forField)
.collect(Collectors.toList());
return StaticSchemaInference.schemaFromClass(clazz, getTypesForClass);
}
// Static ByteBuddy instance used by all helpers.
private static final ByteBuddy BYTE_BUDDY = new ByteBuddy();
private static final Map<ClassWithSchema, List<FieldValueTypeInformation>> CACHED_FIELD_TYPES =
Maps.newConcurrentMap();
public static List<FieldValueTypeInformation> getFieldTypes(Class<?> clazz, Schema schema) {
return CACHED_FIELD_TYPES.computeIfAbsent(
new ClassWithSchema(clazz, schema),
c -> {
Map<String, FieldValueTypeInformation> typeInformationMap =
ReflectUtils.getFields(clazz)
.stream()
.map(FieldValueTypeInformation::of)
.collect(
Collectors.toMap(FieldValueTypeInformation::getName, Function.identity()));
return schema
.getFields()
.stream()
.map(f -> typeInformationMap.get(f.getName()))
.collect(Collectors.toList());
});
}
// The list of getters for a class is cached, so we only create the classes the first time
// getSetters is called.
private static final Map<ClassWithSchema, List<FieldValueGetter>> CACHED_GETTERS =
Maps.newConcurrentMap();
public static List<FieldValueGetter> getGetters(Class<?> clazz, Schema schema) {
// Return the getters ordered by their position in the schema.
return CACHED_GETTERS.computeIfAbsent(
new ClassWithSchema(clazz, schema),
c -> {
Map<String, FieldValueGetter> getterMap =
ReflectUtils.getFields(clazz)
.stream()
.map(POJOUtils::createGetter)
.collect(Collectors.toMap(FieldValueGetter::name, Function.identity()));
return schema
.getFields()
.stream()
.map(f -> getterMap.get(f.getName()))
.collect(Collectors.toList());
});
}
// The list of constructors for a class is cached, so we only create the classes the first time
// getConstructor is called.
public static final Map<ClassWithSchema, SchemaUserTypeCreator> CACHED_CREATORS =
Maps.newConcurrentMap();
public static <T> SchemaUserTypeCreator getCreator(Class<T> clazz, Schema schema) {
return CACHED_CREATORS.computeIfAbsent(
new ClassWithSchema(clazz, schema), c -> createCreator(clazz, schema));
}
private static <T> SchemaUserTypeCreator createCreator(Class<T> clazz, Schema schema) {
// Get the list of class fields ordered by schema.
Map<String, Field> fieldMap =
ReflectUtils.getFields(clazz)
.stream()
.collect(Collectors.toMap(Field::getName, Function.identity()));
List<Field> fields =
schema
.getFields()
.stream()
.map(f -> fieldMap.get(f.getName()))
.collect(Collectors.toList());
try {
DynamicType.Builder<SchemaUserTypeCreator> builder =
BYTE_BUDDY
.subclass(SchemaUserTypeCreator.class)
.method(ElementMatchers.named("create"))
.intercept(new CreateInstruction(fields, clazz));
return builder
.make()
.load(ReflectHelpers.findClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException(
"Unable to generate a creator for class " + clazz + " with schema " + schema);
}
}
/**
* Generate the following {@link FieldValueSetter} class for the {@link Field}.
*
* <pre><code>
* class Getter implements {@literal FieldValueGetter<POJO, FieldType>} {
* {@literal @}Override public String name() { return field.getName(); }
* {@literal @}Override public Class type() { return field.getType(); }
* {@literal @}Override public FieldType get(POJO pojo) {
* return convert(pojo.field);
* }
* }
* </code></pre>
*/
@SuppressWarnings("unchecked")
static <ObjectT, ValueT> FieldValueGetter<ObjectT, ValueT> createGetter(Field field) {
DynamicType.Builder<FieldValueGetter> builder =
ByteBuddyUtils.subclassGetterInterface(
BYTE_BUDDY,
field.getDeclaringClass(),
new ConvertType(false).convert(TypeDescriptor.of(field.getType())));
builder = implementGetterMethods(builder, field);
try {
return builder
.make()
.load(ReflectHelpers.findClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException("Unable to generate a getter for field '" + field + "'.", e);
}
}
private static DynamicType.Builder<FieldValueGetter> implementGetterMethods(
DynamicType.Builder<FieldValueGetter> builder, Field field) {
return builder
.method(ElementMatchers.named("name"))
.intercept(FixedValue.reference(field.getName()))
.method(ElementMatchers.named("get"))
.intercept(new ReadFieldInstruction(field));
}
// The list of setters for a class is cached, so we only create the classes the first time
// getSetters is called.
private static final Map<ClassWithSchema, List<FieldValueSetter>> CACHED_SETTERS =
Maps.newConcurrentMap();
public static List<FieldValueSetter> getSetters(Class<?> clazz, Schema schema) {
// Return the setters, ordered by their position in the schema.
return CACHED_SETTERS.computeIfAbsent(
new ClassWithSchema(clazz, schema),
c -> {
Map<String, FieldValueSetter> setterMap =
ReflectUtils.getFields(clazz)
.stream()
.map(POJOUtils::createSetter)
.collect(Collectors.toMap(FieldValueSetter::name, Function.identity()));
return schema
.getFields()
.stream()
.map(f -> setterMap.get(f.getName()))
.collect(Collectors.toList());
});
}
/**
* Generate the following {@link FieldValueSetter} class for the {@link Field}.
*
* <pre><code>
* class Setter implements {@literal FieldValueSetter<POJO, FieldType>} {
* {@literal @}Override public String name() { return field.getName(); }
* {@literal @}Override public Class type() { return field.getType(); }
* {@literal @}Override public Type elementType() { return elementType; }
* {@literal @}Override public Type mapKeyType() { return mapKeyType; }
* {@literal @}Override public Type mapValueType() { return mapValueType; }
* {@literal @}Override public void set(POJO pojo, FieldType value) {
* pojo.field = convert(value);
* }
* }
* </code></pre>
*/
@SuppressWarnings("unchecked")
private static <ObjectT, ValueT> FieldValueSetter<ObjectT, ValueT> createSetter(Field field) {
DynamicType.Builder<FieldValueSetter> builder =
ByteBuddyUtils.subclassSetterInterface(
BYTE_BUDDY,
field.getDeclaringClass(),
new ConvertType(false).convert(TypeDescriptor.of(field.getType())));
builder = implementSetterMethods(builder, field);
try {
return builder
.make()
.load(ReflectHelpers.findClassLoader(), ClassLoadingStrategy.Default.INJECTION)
.getLoaded()
.getDeclaredConstructor()
.newInstance();
} catch (InstantiationException
| IllegalAccessException
| NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException("Unable to generate a getter for field '" + field + "'.", e);
}
}
private static DynamicType.Builder<FieldValueSetter> implementSetterMethods(
DynamicType.Builder<FieldValueSetter> builder, Field field) {
return builder
.method(ElementMatchers.named("name"))
.intercept(FixedValue.reference(field.getName()))
.method(ElementMatchers.named("set"))
.intercept(new SetFieldInstruction(field));
}
// Implements a method to read a public field out of an object.
static class ReadFieldInstruction implements Implementation {
// Field that will be read.
private Field field;
ReadFieldInstruction(Field field) {
this.field = field;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public ByteCodeAppender appender(final Target implementationTarget) {
return (methodVisitor, implementationContext, instrumentedMethod) -> {
// this + method parameters.
int numLocals = 1 + instrumentedMethod.getParameters().size();
// StackManipulation that will read the value from the class field.
StackManipulation readValue =
new StackManipulation.Compound(
// Method param is offset 1 (offset 0 is the this parameter).
MethodVariableAccess.REFERENCE.loadFrom(1),
// Read the field from the object.
FieldAccess.forField(new ForLoadedField(field)).read());
StackManipulation stackManipulation =
new StackManipulation.Compound(
new ConvertValueForGetter(readValue).convert(TypeDescriptor.of(field.getType())),
MethodReturn.REFERENCE);
StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
return new Size(size.getMaximalSize(), numLocals);
};
}
}
// Implements a method to set a public field in an object.
static class SetFieldInstruction implements Implementation {
// Field that will be read.
private Field field;
SetFieldInstruction(Field field) {
this.field = field;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public ByteCodeAppender appender(final Target implementationTarget) {
return (methodVisitor, implementationContext, instrumentedMethod) -> {
// this + method parameters.
int numLocals = 1 + instrumentedMethod.getParameters().size();
// The instruction to read the field.
StackManipulation readField = MethodVariableAccess.REFERENCE.loadFrom(2);
// Read the object onto the stack.
StackManipulation stackManipulation =
new StackManipulation.Compound(
// Object param is offset 1.
MethodVariableAccess.REFERENCE.loadFrom(1),
// Do any conversions necessary.
new ByteBuddyUtils.ConvertValueForSetter(readField)
.convert(TypeDescriptor.of(field.getType())),
// Now update the field and return void.
FieldAccess.forField(new ForLoadedField(field)).write(),
MethodReturn.VOID);
StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
return new Size(size.getMaximalSize(), numLocals);
};
}
}
// Implements a method to construct an object.
static class CreateInstruction implements Implementation {
private final List<Field> fields;
private final Class pojoClass;
CreateInstruction(List<Field> fields, Class pojoClass) {
this.fields = fields;
this.pojoClass = pojoClass;
}
@Override
public InstrumentedType prepare(InstrumentedType instrumentedType) {
return instrumentedType;
}
@Override
public ByteCodeAppender appender(final Target implementationTarget) {
return (methodVisitor, implementationContext, instrumentedMethod) -> {
// this + method parameters.
int numLocals = 1 + instrumentedMethod.getParameters().size();
// Create the POJO class.
ForLoadedType loadedType = new ForLoadedType(pojoClass);
StackManipulation stackManipulation =
new StackManipulation.Compound(
TypeCreation.of(loadedType),
Duplication.SINGLE,
MethodInvocation.invoke(
loadedType
.getDeclaredMethods()
.filter(
ElementMatchers.isConstructor().and(ElementMatchers.takesArguments(0)))
.getOnly()));
// The types in the POJO might be the types returned by Beam's Row class,
// so we have to convert the types used by Beam's Row class.
ConvertType convertType = new ConvertType(true);
for (int i = 0; i < fields.size(); ++i) {
Field field = fields.get(i);
ForLoadedType convertedType =
new ForLoadedType((Class) convertType.convert(TypeDescriptor.of(field.getType())));
// The instruction to read the parameter.
StackManipulation readParameter =
new StackManipulation.Compound(
MethodVariableAccess.REFERENCE.loadFrom(1),
IntegerConstant.forValue(i),
ArrayAccess.REFERENCE.load(),
TypeCasting.to(convertedType));
StackManipulation updateField =
new StackManipulation.Compound(
// Duplicate object reference.
Duplication.SINGLE,
// Do any conversions necessary.
new ByteBuddyUtils.ConvertValueForSetter(readParameter)
.convert(TypeDescriptor.of(field.getType())),
// Now update the field.
FieldAccess.forField(new ForLoadedField(field)).write());
stackManipulation = new StackManipulation.Compound(stackManipulation, updateField);
}
stackManipulation =
new StackManipulation.Compound(stackManipulation, MethodReturn.REFERENCE);
StackManipulation.Size size = stackManipulation.apply(methodVisitor, implementationContext);
return new Size(size.getMaximalSize(), numLocals);
};
}
}
}