/
DefaultEntityFactory.java
514 lines (469 loc) · 20.9 KB
/
DefaultEntityFactory.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
* Copyright DataStax, Inc.
*
* Licensed 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 com.datastax.oss.driver.internal.mapper.processor.entity;
import com.datastax.oss.driver.api.mapper.annotations.ClusteringColumn;
import com.datastax.oss.driver.api.mapper.annotations.Computed;
import com.datastax.oss.driver.api.mapper.annotations.CqlName;
import com.datastax.oss.driver.api.mapper.annotations.Entity;
import com.datastax.oss.driver.api.mapper.annotations.NamingStrategy;
import com.datastax.oss.driver.api.mapper.annotations.PartitionKey;
import com.datastax.oss.driver.api.mapper.annotations.Transient;
import com.datastax.oss.driver.api.mapper.annotations.TransientProperties;
import com.datastax.oss.driver.api.mapper.entity.naming.NamingConvention;
import com.datastax.oss.driver.internal.mapper.processor.ProcessorContext;
import com.datastax.oss.driver.internal.mapper.processor.util.AnnotationScanner;
import com.datastax.oss.driver.internal.mapper.processor.util.HierarchyScanner;
import com.datastax.oss.driver.internal.mapper.processor.util.ResolvedAnnotation;
import com.datastax.oss.driver.internal.mapper.processor.util.generation.PropertyType;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableList;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableMap;
import com.datastax.oss.driver.shaded.guava.common.collect.ImmutableSet;
import com.datastax.oss.driver.shaded.guava.common.collect.Maps;
import com.datastax.oss.driver.shaded.guava.common.collect.Sets;
import com.squareup.javapoet.ClassName;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.beans.Introspector;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import javax.lang.model.element.VariableElement;
import javax.lang.model.type.TypeKind;
import javax.lang.model.type.TypeMirror;
public class DefaultEntityFactory implements EntityFactory {
private final ProcessorContext context;
// property annotations of which only 1 is allowed on a property
private static final Set<Class<? extends Annotation>> EXCLUSIVE_PROPERTY_ANNOTATIONS =
ImmutableSet.of(ClusteringColumn.class, PartitionKey.class, Transient.class, Computed.class);
// all valid property annotations to scan for.
private static final Set<Class<? extends Annotation>> PROPERTY_ANNOTATIONS =
ImmutableSet.<Class<? extends Annotation>>builder()
.addAll(EXCLUSIVE_PROPERTY_ANNOTATIONS)
.add(CqlName.class)
.build();
public DefaultEntityFactory(ProcessorContext context) {
this.context = context;
}
@Override
public EntityDefinition getDefinition(TypeElement classElement) {
Set<TypeMirror> types = HierarchyScanner.resolveTypeHierarchy(classElement, context);
Set<TypeElement> typeHierarchy = Sets.newLinkedHashSet();
for (TypeMirror type : types) {
typeHierarchy.add((TypeElement) context.getTypeUtils().asElement(type));
}
CqlNameGenerator cqlNameGenerator = buildCqlNameGenerator(typeHierarchy);
Set<String> transientProperties = getTransientPropertyNames(typeHierarchy);
Set<String> encounteredPropertyNames = Sets.newHashSet();
SortedMap<Integer, PropertyDefinition> partitionKey = new TreeMap<>();
SortedMap<Integer, PropertyDefinition> clusteringColumns = new TreeMap<>();
ImmutableList.Builder<PropertyDefinition> regularColumns = ImmutableList.builder();
ImmutableList.Builder<PropertyDefinition> computedValues = ImmutableList.builder();
// scan hierarchy for properties
for (TypeElement typeElement : typeHierarchy) {
for (Element child : typeElement.getEnclosedElements()) {
Set<Modifier> modifiers = child.getModifiers();
if (child.getKind() != ElementKind.METHOD
|| modifiers.contains(Modifier.STATIC)
|| modifiers.contains(Modifier.PRIVATE)) {
continue;
}
ExecutableElement getMethod = (ExecutableElement) child;
String getMethodName = getMethod.getSimpleName().toString();
if (!getMethodName.startsWith("get") || !getMethod.getParameters().isEmpty()) {
continue;
}
TypeMirror typeMirror = getMethod.getReturnType();
if (typeMirror.getKind() == TypeKind.VOID) {
continue;
}
String propertyName = Introspector.decapitalize(getMethodName.substring(3));
// skip properties we've already encountered.
if (encounteredPropertyNames.contains(propertyName)) {
continue;
}
String setMethodName = getMethodName.replaceFirst("get", "set");
ExecutableElement setMethod = findSetMethod(typeHierarchy, setMethodName, typeMirror);
if (setMethod == null) {
continue; // must have both
}
VariableElement field = findField(typeHierarchy, propertyName, typeMirror);
Map<Class<? extends Annotation>, Annotation> propertyAnnotations =
scanPropertyAnnotations(typeHierarchy, getMethod, field);
if (isTransient(propertyAnnotations, propertyName, transientProperties, getMethod, field)) {
continue;
}
int partitionKeyIndex = getPartitionKeyIndex(propertyAnnotations);
int clusteringColumnIndex = getClusteringColumnIndex(propertyAnnotations);
Optional<String> customCqlName = getCustomCqlName(propertyAnnotations);
Optional<String> computedFormula =
getComputedFormula(propertyAnnotations, getMethod, field);
PropertyType propertyType = PropertyType.parse(typeMirror, context);
PropertyDefinition property =
new DefaultPropertyDefinition(
propertyName,
customCqlName,
computedFormula,
getMethodName,
setMethodName,
propertyType,
cqlNameGenerator);
encounteredPropertyNames.add(propertyName);
if (partitionKeyIndex >= 0) {
PropertyDefinition previous = partitionKey.putIfAbsent(partitionKeyIndex, property);
if (previous != null) {
context
.getMessager()
.error(
getMethod,
"Duplicate partition key index: if multiple properties are annotated "
+ "with @%s, the annotation must be parameterized with an integer "
+ "indicating the position. Found duplicate index %d for %s and %s.",
PartitionKey.class.getSimpleName(),
partitionKeyIndex,
previous.getGetterName(),
property.getGetterName());
}
} else if (clusteringColumnIndex >= 0) {
PropertyDefinition previous =
clusteringColumns.putIfAbsent(clusteringColumnIndex, property);
if (previous != null) {
context
.getMessager()
.error(
getMethod,
"Duplicate clustering column index: if multiple properties are annotated "
+ "with @%s, the annotation must be parameterized with an integer "
+ "indicating the position. Found duplicate index %d for %s and %s.",
ClusteringColumn.class.getSimpleName(),
clusteringColumnIndex,
previous.getGetterName(),
property.getGetterName());
}
} else if (computedFormula.isPresent()) {
computedValues.add(property);
} else {
regularColumns.add(property);
}
}
}
if (encounteredPropertyNames.isEmpty()) {
context
.getMessager()
.error(
classElement,
"@%s-annotated class must have at least one property defined.",
Entity.class.getSimpleName());
}
String entityName = Introspector.decapitalize(classElement.getSimpleName().toString());
String defaultKeyspace = classElement.getAnnotation(Entity.class).defaultKeyspace();
return new DefaultEntityDefinition(
ClassName.get(classElement),
entityName,
defaultKeyspace.isEmpty() ? null : defaultKeyspace,
Optional.ofNullable(classElement.getAnnotation(CqlName.class)).map(CqlName::value),
ImmutableList.copyOf(partitionKey.values()),
ImmutableList.copyOf(clusteringColumns.values()),
regularColumns.build(),
computedValues.build(),
cqlNameGenerator);
}
@Nullable
private VariableElement findField(
Set<TypeElement> typeHierarchy, String propertyName, TypeMirror fieldType) {
for (TypeElement classElement : typeHierarchy) {
// skip interfaces as they can't have fields
if (classElement.getKind().isInterface()) {
continue;
}
for (Element child : classElement.getEnclosedElements()) {
if (child.getKind() != ElementKind.FIELD) {
continue;
}
VariableElement field = (VariableElement) child;
if (field.getSimpleName().toString().equals(propertyName)
&& context.getTypeUtils().isAssignable(fieldType, field.asType())) {
return field;
}
}
}
return null;
}
@Nullable
private ExecutableElement findSetMethod(
Set<TypeElement> typeHierarchy, String setMethodName, TypeMirror fieldType) {
for (TypeElement classElement : typeHierarchy) {
for (Element child : classElement.getEnclosedElements()) {
Set<Modifier> modifiers = child.getModifiers();
if (child.getKind() != ElementKind.METHOD
|| modifiers.contains(Modifier.STATIC)
|| modifiers.contains(Modifier.PRIVATE)) {
continue;
}
ExecutableElement setMethod = (ExecutableElement) child;
List<? extends VariableElement> parameters = setMethod.getParameters();
if (setMethod.getSimpleName().toString().equals(setMethodName)
&& parameters.size() == 1
&& context.getTypeUtils().isAssignable(fieldType, parameters.get(0).asType())) {
return setMethod;
}
}
}
return null;
}
private Optional<String> getCustomCqlName(
Map<Class<? extends Annotation>, Annotation> annotations) {
CqlName cqlName = (CqlName) annotations.get(CqlName.class);
return cqlName != null ? Optional.of(cqlName.value()) : Optional.empty();
}
private int getPartitionKeyIndex(Map<Class<? extends Annotation>, Annotation> annotations) {
PartitionKey partitionKey = (PartitionKey) annotations.get(PartitionKey.class);
return partitionKey != null ? partitionKey.value() : -1;
}
private int getClusteringColumnIndex(Map<Class<? extends Annotation>, Annotation> annotations) {
ClusteringColumn clusteringColumn = (ClusteringColumn) annotations.get(ClusteringColumn.class);
return clusteringColumn != null ? clusteringColumn.value() : -1;
}
private Optional<String> getComputedFormula(
Map<Class<? extends Annotation>, Annotation> annotations,
ExecutableElement getMethod,
@Nullable VariableElement field) {
Computed annotation = (Computed) annotations.get(Computed.class);
if (annotation != null) {
// ensure formula is non-empty
String value = annotation.value();
if (value.isEmpty()) {
Element element =
field != null && field.getAnnotation(Computed.class) != null ? field : getMethod;
context.getMessager().error(element, "@Computed value should be non-empty.");
}
return Optional.of(value);
}
return Optional.empty();
}
private CqlNameGenerator buildCqlNameGenerator(Set<TypeElement> typeHierarchy) {
Optional<ResolvedAnnotation<NamingStrategy>> annotation =
AnnotationScanner.getClassAnnotation(NamingStrategy.class, typeHierarchy);
if (!annotation.isPresent()) {
return CqlNameGenerator.DEFAULT;
}
NamingStrategy namingStrategy = annotation.get().getAnnotation();
Element classElement = annotation.get().getElement();
if (namingStrategy == null) {
return CqlNameGenerator.DEFAULT;
}
NamingConvention[] conventions = namingStrategy.convention();
TypeMirror[] customConverterClasses = readCustomConverterClasses(classElement);
if (conventions.length > 0 && customConverterClasses.length > 0) {
context
.getMessager()
.error(
classElement,
"Invalid annotation configuration: %s must have either a 'convention' "
+ "or 'customConverterClass' argument, but not both",
NamingStrategy.class.getSimpleName());
// Return a generator anyway, so that the processor doesn't crash downstream
return new CqlNameGenerator(conventions[0]);
} else if (conventions.length == 0 && customConverterClasses.length == 0) {
context
.getMessager()
.error(
classElement,
"Invalid annotation configuration: %s must have either a 'convention' "
+ "or 'customConverterClass' argument",
NamingStrategy.class.getSimpleName());
return CqlNameGenerator.DEFAULT;
} else if (conventions.length > 0) {
if (conventions.length > 1) {
context
.getMessager()
.warn(
classElement,
"Too many naming conventions: %s must have at most one 'convention' "
+ "argument (will use the first one: %s)",
NamingStrategy.class.getSimpleName(),
conventions[0]);
}
return new CqlNameGenerator(conventions[0]);
} else {
if (customConverterClasses.length > 1) {
context
.getMessager()
.warn(
classElement,
"Too many custom converters: %s must have at most one "
+ "'customConverterClass' argument (will use the first one: %s)",
NamingStrategy.class.getSimpleName(),
customConverterClasses[0]);
}
return new CqlNameGenerator(customConverterClasses[0]);
}
}
private TypeMirror[] readCustomConverterClasses(Element classElement) {
// customConverterClass references a class that might not be compiled yet, so we can't read it
// directly, we need to go through mirrors.
AnnotationMirror annotationMirror = null;
for (AnnotationMirror candidate : classElement.getAnnotationMirrors()) {
if (context.getClassUtils().isSame(candidate.getAnnotationType(), NamingStrategy.class)) {
annotationMirror = candidate;
break;
}
}
assert annotationMirror != null; // We've checked that in the caller already
for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry :
annotationMirror.getElementValues().entrySet()) {
if (entry.getKey().getSimpleName().contentEquals("customConverterClass")) {
@SuppressWarnings("unchecked")
List<? extends AnnotationValue> values = (List) entry.getValue().getValue();
TypeMirror[] result = new TypeMirror[values.size()];
for (int i = 0; i < values.size(); i++) {
result[i] = ((TypeMirror) values.get(i).getValue());
}
return result;
}
}
return new TypeMirror[0];
}
private boolean isTransient(
Map<Class<? extends Annotation>, Annotation> annotations,
String propertyName,
Set<String> transientProperties,
ExecutableElement getMethod,
@Nullable VariableElement field) {
Transient transientAnnotation = (Transient) annotations.get(Transient.class);
// check if property name is included in @TransientProperties
// -or- if property is annotated with @Transient
// -or- if field has transient keyword modifier
boolean isTransient =
transientProperties.contains(propertyName)
|| transientAnnotation != null
|| (field != null && field.getModifiers().contains(Modifier.TRANSIENT));
// if annotations contains an exclusive annotation that isn't transient, raise
// an error here.
Class<? extends Annotation> exclusiveAnnotation = getExclusiveAnnotation(annotations);
if (isTransient && transientAnnotation == null && exclusiveAnnotation != null) {
Element element = field != null ? field : getMethod;
context
.getMessager()
.error(
element,
"Property that is considered transient cannot be annotated with @%s.",
exclusiveAnnotation.getSimpleName());
}
return isTransient;
}
private Set<String> getTransientPropertyNames(Set<TypeElement> typeHierarchy) {
Optional<ResolvedAnnotation<TransientProperties>> annotation =
AnnotationScanner.getClassAnnotation(TransientProperties.class, typeHierarchy);
return annotation.isPresent()
? Sets.newHashSet(annotation.get().getAnnotation().value())
: Collections.emptySet();
}
private void reportMultipleAnnotationError(
Element element, Class<? extends Annotation> a0, Class<? extends Annotation> a1) {
if (a0 == a1) {
context
.getMessager()
.warn(
element,
"@%s should be used either on the field or the getter, but not both. "
+ "The annotation on this field will be ignored.",
a0.getSimpleName());
} else {
context
.getMessager()
.error(
element,
"Properties can't be annotated with both @%s and @%s.",
a0.getSimpleName(),
a1.getSimpleName());
}
}
private Map<Class<? extends Annotation>, Annotation> scanPropertyAnnotations(
Set<TypeElement> typeHierarchy,
ExecutableElement getMethod,
@Nullable VariableElement field) {
Map<Class<? extends Annotation>, Annotation> annotations = Maps.newHashMap();
// scan methods first as they should take precedence.
scanMethodAnnotations(typeHierarchy, getMethod, annotations);
if (field != null) {
scanFieldAnnotations(field, annotations);
}
return ImmutableMap.copyOf(annotations);
}
@Nullable
private Class<? extends Annotation> getExclusiveAnnotation(
Map<Class<? extends Annotation>, Annotation> annotations) {
for (Class<? extends Annotation> annotationClass : annotations.keySet()) {
if (EXCLUSIVE_PROPERTY_ANNOTATIONS.contains(annotationClass)) {
return annotationClass;
}
}
return null;
}
private void scanFieldAnnotations(
VariableElement field, Map<Class<? extends Annotation>, Annotation> annotations) {
Class<? extends Annotation> exclusiveAnnotation = getExclusiveAnnotation(annotations);
for (Class<? extends Annotation> annotationClass : PROPERTY_ANNOTATIONS) {
Annotation annotation = field.getAnnotation(annotationClass);
if (annotation != null) {
if (EXCLUSIVE_PROPERTY_ANNOTATIONS.contains(annotationClass)) {
if (exclusiveAnnotation == null) {
exclusiveAnnotation = annotationClass;
} else {
reportMultipleAnnotationError(field, exclusiveAnnotation, annotationClass);
}
}
if (!annotations.containsKey(annotationClass)) {
annotations.put(annotationClass, annotation);
}
}
}
}
private void scanMethodAnnotations(
Set<TypeElement> typeHierarchy,
ExecutableElement getMethod,
Map<Class<? extends Annotation>, Annotation> annotations) {
Class<? extends Annotation> exclusiveAnnotation = getExclusiveAnnotation(annotations);
for (Class<? extends Annotation> annotationClass : PROPERTY_ANNOTATIONS) {
Optional<? extends ResolvedAnnotation<? extends Annotation>> annotation =
AnnotationScanner.getMethodAnnotation(annotationClass, getMethod, typeHierarchy);
if (annotation.isPresent()) {
if (EXCLUSIVE_PROPERTY_ANNOTATIONS.contains(annotationClass)) {
if (exclusiveAnnotation == null) {
exclusiveAnnotation = annotationClass;
} else {
reportMultipleAnnotationError(
annotation.get().getElement(), exclusiveAnnotation, annotationClass);
}
}
if (!annotations.containsKey(annotationClass)) {
annotations.put(annotationClass, annotation.get().getAnnotation());
}
}
}
}
}