-
Notifications
You must be signed in to change notification settings - Fork 282
/
JavaClassProcessor.java
774 lines (645 loc) · 32 KB
/
JavaClassProcessor.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
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
/*
* Copyright 2014-2020 TNG Technology Consulting GmbH
*
* 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.tngtech.archunit.core.importer;
import java.lang.reflect.Array;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.primitives.Booleans;
import com.google.common.primitives.Bytes;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Floats;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;
import com.tngtech.archunit.Internal;
import com.tngtech.archunit.base.Function;
import com.tngtech.archunit.base.HasDescription;
import com.tngtech.archunit.base.Optional;
import com.tngtech.archunit.core.MayResolveTypesViaReflection;
import com.tngtech.archunit.core.domain.JavaAnnotation;
import com.tngtech.archunit.core.domain.JavaClass;
import com.tngtech.archunit.core.domain.JavaEnumConstant;
import com.tngtech.archunit.core.domain.JavaMethod;
import com.tngtech.archunit.core.domain.JavaModifier;
import com.tngtech.archunit.core.domain.JavaType;
import com.tngtech.archunit.core.importer.DomainBuilders.JavaAnnotationBuilder.ValueBuilder;
import com.tngtech.archunit.core.importer.RawAccessRecord.CodeUnit;
import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.nullToEmpty;
import static com.tngtech.archunit.core.domain.JavaConstructor.CONSTRUCTOR_NAME;
import static com.tngtech.archunit.core.domain.JavaStaticInitializer.STATIC_INITIALIZER_NAME;
import static com.tngtech.archunit.core.importer.ClassFileProcessor.ASM_API_VERSION;
class JavaClassProcessor extends ClassVisitor {
private static final Logger LOG = LoggerFactory.getLogger(JavaClassProcessor.class);
private static final AccessHandler NO_OP = new AccessHandler.NoOp();
private DomainBuilders.JavaClassBuilder javaClassBuilder;
private final Set<DomainBuilders.JavaAnnotationBuilder> annotations = new HashSet<>();
private final URI sourceURI;
private final DeclarationHandler declarationHandler;
private final AccessHandler accessHandler;
private String className;
JavaClassProcessor(URI sourceURI, DeclarationHandler declarationHandler) {
this(sourceURI, declarationHandler, NO_OP);
}
JavaClassProcessor(URI sourceURI, DeclarationHandler declarationHandler, AccessHandler accessHandler) {
super(ASM_API_VERSION);
this.sourceURI = sourceURI;
this.declarationHandler = declarationHandler;
this.accessHandler = accessHandler;
}
Optional<JavaClass> createJavaClass() {
return javaClassBuilder != null ? Optional.of(javaClassBuilder.build()) : Optional.<JavaClass>absent();
}
@Override
public void visitSource(String source, String debug) {
if (!importAborted() && source != null) {
javaClassBuilder.withSourceFileName(source);
}
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
LOG.debug("Analyzing class '{}'", name);
JavaType javaType = JavaTypeImporter.createFromAsmObjectTypeName(name);
if (alreadyImported(javaType)) {
return;
}
ImmutableSet<String> interfaceNames = createInterfaceNames(interfaces);
LOG.trace("Found interfaces {} on class '{}'", interfaceNames, name);
boolean opCodeForInterfaceIsPresent = (access & Opcodes.ACC_INTERFACE) != 0;
boolean opCodeForEnumIsPresent = (access & Opcodes.ACC_ENUM) != 0;
Optional<String> superClassName = getSuperClassName(superName, opCodeForInterfaceIsPresent);
LOG.trace("Found superclass {} on class '{}'", superClassName.orNull(), name);
javaClassBuilder = new DomainBuilders.JavaClassBuilder()
.withSourceUri(sourceURI)
.withType(javaType)
.withInterface(opCodeForInterfaceIsPresent)
.withEnum(opCodeForEnumIsPresent)
.withModifiers(JavaModifier.getModifiersForClass(access));
className = javaType.getName();
declarationHandler.onNewClass(className, superClassName, interfaceNames);
}
private boolean alreadyImported(JavaType javaType) {
return !declarationHandler.isNew(javaType.getName());
}
// NOTE: For some reason ASM claims superName == java/lang/Object for Interfaces???
// This is inconsistent with the behavior of Class.getSuperClass()
private Optional<String> getSuperClassName(String superName, boolean isInterface) {
return superName != null && !isInterface ?
Optional.of(createTypeName(superName)) :
Optional.<String>absent();
}
private boolean importAborted() {
return javaClassBuilder == null;
}
@Override
public void visitInnerClass(String name, String outerName, String innerName, int access) {
if (importAborted()) {
return;
}
String innerTypeName = createTypeName(name);
if (!visitingCurrentClass(innerTypeName)) {
return;
}
javaClassBuilder.withSimpleName(nullToEmpty(innerName));
// Javadoc for innerName: "May be null for anonymous inner classes."
boolean isAnonymousClass = innerName == null;
javaClassBuilder.withAnonymousClass(isAnonymousClass);
// Javadoc for outerName: "May be null for not member classes."
boolean isMemberClass = outerName != null;
javaClassBuilder.withMemberClass(isMemberClass);
if (isMemberClass) {
javaClassBuilder.withModifiers(JavaModifier.getModifiersForClass(access));
declarationHandler.registerEnclosingClass(innerTypeName, createTypeName(outerName));
}
}
// visitInnerClass is called for named inner classes, even if we are currently importing
// this class itself (i.e. visit(..) and visitInnerClass(..) are called with the same class name.
// visitInnerClass offers some more properties like correct modifiers.
// Modifier handling is somewhat counter intuitive for nested named classes, even though we 'visit' the nested class
// like any outer class in visit(..) before, the modifiers like 'PUBLIC' or 'PRIVATE'
// are found in the access flags of visitInnerClass(..)
private boolean visitingCurrentClass(String innerTypeName) {
return innerTypeName.equals(className);
}
@Override
public void visitOuterClass(String owner, String name, String desc) {
if (importAborted()) {
return;
}
declarationHandler.registerEnclosingClass(className, createTypeName(owner));
}
private ImmutableSet<String> createInterfaceNames(String[] interfaces) {
ImmutableSet.Builder<String> result = ImmutableSet.builder();
for (String i : interfaces) {
result.add(createTypeName(i));
}
return result.build();
}
private String createTypeName(String name) {
return name.replace("/", ".");
}
@Override
public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) {
if (importAborted()) {
return super.visitField(access, name, desc, signature, value);
}
DomainBuilders.JavaFieldBuilder fieldBuilder = new DomainBuilders.JavaFieldBuilder()
.withName(name)
.withType(JavaTypeImporter.importAsmType(Type.getType(desc)))
.withModifiers(JavaModifier.getModifiersForField(access))
.withDescriptor(desc);
declarationHandler.onDeclaredField(fieldBuilder);
return new FieldProcessor(fieldBuilder);
}
@Override
public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {
if (importAborted()) {
return super.visitMethod(access, name, desc, signature, exceptions);
}
LOG.trace("Analyzing method {}.{}:{}", className, name, desc);
accessHandler.setContext(new CodeUnit(name, namesOf(Type.getArgumentTypes(desc)), className));
DomainBuilders.JavaCodeUnitBuilder<?, ?> codeUnitBuilder = addCodeUnitBuilder(name);
Type methodType = Type.getMethodType(desc);
codeUnitBuilder
.withName(name)
.withModifiers(JavaModifier.getModifiersForMethod(access))
.withParameters(typesFrom(methodType.getArgumentTypes()))
.withReturnType(JavaTypeImporter.importAsmType(methodType.getReturnType()))
.withDescriptor(desc)
.withThrowsClause(typesFrom(exceptions));
return new MethodProcessor(className, accessHandler, codeUnitBuilder);
}
private List<JavaType> typesFrom(Type[] asmTypes) {
List<JavaType> result = new ArrayList<>();
for (Type asmType : asmTypes) {
result.add(JavaTypeImporter.importAsmType(asmType));
}
return result;
}
private List<JavaType> typesFrom(String[] throwsDeclarations) {
List<JavaType> result = new ArrayList<>();
if (throwsDeclarations != null) {
for (String throwsDeclaration : throwsDeclarations) {
result.add(JavaTypeImporter.createFromAsmObjectTypeName(throwsDeclaration));
}
}
return result;
}
private DomainBuilders.JavaCodeUnitBuilder<?, ?> addCodeUnitBuilder(String name) {
if (CONSTRUCTOR_NAME.equals(name)) {
DomainBuilders.JavaConstructorBuilder builder = new DomainBuilders.JavaConstructorBuilder();
declarationHandler.onDeclaredConstructor(builder);
return builder;
} else if (STATIC_INITIALIZER_NAME.equals(name)) {
DomainBuilders.JavaStaticInitializerBuilder builder = new DomainBuilders.JavaStaticInitializerBuilder();
declarationHandler.onDeclaredStaticInitializer(builder);
return builder;
} else {
DomainBuilders.JavaMethodBuilder builder = new DomainBuilders.JavaMethodBuilder();
declarationHandler.onDeclaredMethod(builder);
return builder;
}
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
if (importAborted()) {
return super.visitAnnotation(desc, visible);
}
return new AnnotationProcessor(addAnnotationTo(annotations), annotationBuilderFor(desc));
}
@Override
public void visitEnd() {
if (importAborted()) {
return;
}
declarationHandler.onDeclaredAnnotations(annotations);
LOG.trace("Done analyzing {}", className);
}
private static List<String> namesOf(Type[] types) {
ImmutableList.Builder<String> result = ImmutableList.builder();
for (Type type : types) {
result.add(JavaTypeImporter.importAsmType(type).getName());
}
return result.build();
}
private static class MethodProcessor extends MethodVisitor {
private final String declaringClassName;
private final AccessHandler accessHandler;
private final DomainBuilders.JavaCodeUnitBuilder<?, ?> codeUnitBuilder;
private final Set<DomainBuilders.JavaAnnotationBuilder> annotations = new HashSet<>();
private int actualLineNumber;
MethodProcessor(String declaringClassName, AccessHandler accessHandler, DomainBuilders.JavaCodeUnitBuilder<?, ?> codeUnitBuilder) {
super(ASM_API_VERSION);
this.declaringClassName = declaringClassName;
this.accessHandler = accessHandler;
this.codeUnitBuilder = codeUnitBuilder;
}
@Override
public void visitCode() {
actualLineNumber = 0;
}
// NOTE: ASM does not reliably visit this method, so if this method is skipped, line number 0 is recorded
@Override
public void visitLineNumber(int line, Label start) {
LOG.trace("Examining line number {}", line);
codeUnitBuilder.recordLineNumber(line);
actualLineNumber = line;
accessHandler.setLineNumber(actualLineNumber);
}
@Override
public void visitFieldInsn(int opcode, String owner, String name, String desc) {
accessHandler.handleFieldInstruction(opcode, owner, name, desc);
}
@Override
public void visitMethodInsn(int opcode, String owner, String name, String desc, boolean itf) {
accessHandler.handleMethodInstruction(owner, name, desc);
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return new AnnotationProcessor(addAnnotationTo(annotations), annotationBuilderFor(desc));
}
@Override
public AnnotationVisitor visitAnnotationDefault() {
return new AnnotationDefaultProcessor(declaringClassName, codeUnitBuilder);
}
@Override
public void visitEnd() {
codeUnitBuilder.withAnnotations(annotations);
}
private static class AnnotationDefaultProcessor extends AnnotationVisitor {
private final String annotationTypeName;
private final DomainBuilders.JavaMethodBuilder methodBuilder;
AnnotationDefaultProcessor(String annotationTypeName, DomainBuilders.JavaCodeUnitBuilder<?, ?> codeUnitBuilder) {
super(ClassFileProcessor.ASM_API_VERSION);
this.annotationTypeName = annotationTypeName;
checkArgument(codeUnitBuilder instanceof DomainBuilders.JavaMethodBuilder,
"tried to import annotation defaults for code unit '%s' that is not a method " +
"(as any annotation.property() is assumed to be), " +
"this is likely a bug", codeUnitBuilder.getName());
methodBuilder = (DomainBuilders.JavaMethodBuilder) codeUnitBuilder;
}
@Override
public void visit(String name, Object value) {
methodBuilder.withAnnotationDefaultValue(AnnotationTypeConversion.convert(value));
}
@Override
public void visitEnum(String name, String desc, String value) {
methodBuilder.withAnnotationDefaultValue(javaEnumBuilder(desc, value));
}
@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
return new AnnotationProcessor(new SetAsAnnotationDefault(annotationTypeName, methodBuilder), annotationBuilderFor(desc));
}
@Override
public AnnotationVisitor visitArray(String name) {
return new AnnotationArrayProcessor(new SetAsAnnotationDefault(annotationTypeName, methodBuilder));
}
}
}
private static class SetAsAnnotationDefault implements TakesAnnotationBuilder, AnnotationArrayContext {
private final String annotationTypeName;
private final DomainBuilders.JavaMethodBuilder methodBuilder;
private SetAsAnnotationDefault(String annotationTypeName, DomainBuilders.JavaMethodBuilder methodBuilder) {
this.annotationTypeName = annotationTypeName;
this.methodBuilder = methodBuilder;
}
@Override
public void add(DomainBuilders.JavaAnnotationBuilder annotation) {
setArrayResult(ValueBuilder.from(annotation));
}
@Override
public String getDeclaringAnnotationTypeName() {
return annotationTypeName;
}
@Override
public String getDeclaringAnnotationMemberName() {
return methodBuilder.getName();
}
@Override
public void setArrayResult(ValueBuilder valueBuilder) {
methodBuilder.withAnnotationDefaultValue(valueBuilder);
}
}
interface DeclarationHandler {
boolean isNew(String className);
void onNewClass(String className, Optional<String> superClassName, Set<String> interfaceNames);
void onDeclaredField(DomainBuilders.JavaFieldBuilder fieldBuilder);
void onDeclaredConstructor(DomainBuilders.JavaConstructorBuilder builder);
void onDeclaredMethod(DomainBuilders.JavaMethodBuilder builder);
void onDeclaredStaticInitializer(DomainBuilders.JavaStaticInitializerBuilder builder);
void onDeclaredAnnotations(Set<DomainBuilders.JavaAnnotationBuilder> annotations);
void registerEnclosingClass(String ownerName, String enclosingClassName);
}
interface AccessHandler {
void handleFieldInstruction(int opcode, String owner, String name, String desc);
void setContext(CodeUnit codeUnit);
void setLineNumber(int lineNumber);
void handleMethodInstruction(String owner, String name, String desc);
@Internal
class NoOp implements AccessHandler {
@Override
public void handleFieldInstruction(int opcode, String owner, String name, String desc) {
}
@Override
public void setContext(CodeUnit codeUnit) {
}
@Override
public void setLineNumber(int lineNumber) {
}
@Override
public void handleMethodInstruction(String owner, String name, String desc) {
}
}
}
private static class FieldProcessor extends FieldVisitor {
private final DomainBuilders.JavaFieldBuilder fieldBuilder;
private final Set<DomainBuilders.JavaAnnotationBuilder> annotations = new HashSet<>();
private FieldProcessor(DomainBuilders.JavaFieldBuilder fieldBuilder) {
super(ASM_API_VERSION);
this.fieldBuilder = fieldBuilder;
}
@Override
public AnnotationVisitor visitAnnotation(String desc, boolean visible) {
return new AnnotationProcessor(addAnnotationTo(annotations), annotationBuilderFor(desc));
}
@Override
public void visitEnd() {
fieldBuilder.withAnnotations(annotations);
}
}
private static DomainBuilders.JavaAnnotationBuilder annotationBuilderFor(String desc) {
return new DomainBuilders.JavaAnnotationBuilder().withType(JavaTypeImporter.importAsmType(Type.getType(desc)));
}
private static class AnnotationProcessor extends AnnotationVisitor {
private final TakesAnnotationBuilder takesAnnotationBuilder;
private final DomainBuilders.JavaAnnotationBuilder annotationBuilder;
private AnnotationProcessor(TakesAnnotationBuilder takesAnnotationBuilder, DomainBuilders.JavaAnnotationBuilder annotationBuilder) {
super(ASM_API_VERSION);
this.takesAnnotationBuilder = takesAnnotationBuilder;
this.annotationBuilder = annotationBuilder;
}
@Override
public void visit(String name, Object value) {
annotationBuilder.addProperty(name, AnnotationTypeConversion.convert(value));
}
@Override
public void visitEnum(String name, String desc, String value) {
annotationBuilder.addProperty(name, javaEnumBuilder(desc, value));
}
@Override
public AnnotationVisitor visitAnnotation(final String name, String desc) {
return new AnnotationProcessor(addAnnotationAsProperty(name, annotationBuilder), annotationBuilderFor(desc));
}
@Override
public AnnotationVisitor visitArray(final String name) {
return new AnnotationArrayProcessor(new AnnotationArrayContext() {
@Override
public String getDeclaringAnnotationTypeName() {
return annotationBuilder.getJavaType().getName();
}
@Override
public String getDeclaringAnnotationMemberName() {
return name;
}
@Override
public void setArrayResult(ValueBuilder valueBuilder) {
annotationBuilder.addProperty(name, valueBuilder);
}
});
}
@Override
public void visitEnd() {
takesAnnotationBuilder.add(annotationBuilder);
}
}
private static TakesAnnotationBuilder addAnnotationTo(final Collection<? super DomainBuilders.JavaAnnotationBuilder> collection) {
return new TakesAnnotationBuilder() {
@Override
public void add(DomainBuilders.JavaAnnotationBuilder annotation) {
collection.add(annotation);
}
};
}
private static TakesAnnotationBuilder addAnnotationAsProperty(final String name, final DomainBuilders.JavaAnnotationBuilder annotationBuilder) {
return new TakesAnnotationBuilder() {
@Override
public void add(DomainBuilders.JavaAnnotationBuilder builder) {
annotationBuilder.addProperty(name, ValueBuilder.from(builder));
}
};
}
private interface TakesAnnotationBuilder {
void add(DomainBuilders.JavaAnnotationBuilder annotation);
}
private static class AnnotationArrayProcessor extends AnnotationVisitor {
private final AnnotationArrayContext annotationArrayContext;
private Class<?> derivedComponentType;
private final List<ValueBuilder> values = new ArrayList<>();
private AnnotationArrayProcessor(AnnotationArrayContext annotationArrayContext) {
super(ASM_API_VERSION);
this.annotationArrayContext = annotationArrayContext;
}
@Override
public void visit(String name, Object value) {
setDerivedComponentType(value);
values.add(AnnotationTypeConversion.convert(value));
}
@Override
public AnnotationVisitor visitAnnotation(String name, String desc) {
setDerivedComponentType(JavaAnnotation.class);
return new AnnotationProcessor(new TakesAnnotationBuilder() {
@Override
public void add(DomainBuilders.JavaAnnotationBuilder annotationBuilder) {
values.add(ValueBuilder.from(annotationBuilder));
}
}, annotationBuilderFor(desc));
}
@Override
public void visitEnum(String name, final String desc, final String value) {
setDerivedComponentType(JavaEnumConstant.class);
values.add(javaEnumBuilder(desc, value));
}
private void setDerivedComponentType(Object value) {
setDerivedComponentType(value.getClass());
}
// NOTE: If the declared annotation is not imported itself, we can still use this heuristic,
// to determine additional information about the respective array.
// (It the annotation is imported itself, we could easily determine this from the respective
// JavaClass methods)
private void setDerivedComponentType(Class<?> type) {
type = AnnotationTypeConversion.convert(type);
checkState(derivedComponentType == null || derivedComponentType.equals(type),
"Found mixed component types while importing array, this is most likely a bug");
derivedComponentType = type;
}
@Override
public void visitEnd() {
annotationArrayContext.setArrayResult(new ArrayValueBuilder());
}
private class ArrayValueBuilder extends ValueBuilder {
@Override
public <T extends HasDescription> Optional<Object> build(T owner, ClassesByTypeName importedClasses) {
Optional<Class<?>> componentType = determineComponentType(importedClasses);
if (!componentType.isPresent()) {
return Optional.absent();
}
return Optional.of(toArray(componentType.get(), buildValues(owner, importedClasses)));
}
@SuppressWarnings({"unchecked", "rawtypes"}) // NOTE: We assume the component type matches the list
private Object toArray(Class<?> componentType, List<Object> values) {
if (componentType == boolean.class) {
return Booleans.toArray((Collection) values);
} else if (componentType == byte.class) {
return Bytes.toArray((Collection) values);
} else if (componentType == short.class) {
return Shorts.toArray((Collection) values);
} else if (componentType == int.class) {
return Ints.toArray((Collection) values);
} else if (componentType == long.class) {
return Longs.toArray((Collection) values);
} else if (componentType == float.class) {
return Floats.toArray((Collection) values);
} else if (componentType == double.class) {
return Doubles.toArray((Collection) values);
} else if (componentType == char.class) {
return Chars.toArray((Collection) values);
}
return values.toArray((Object[]) Array.newInstance(componentType, values.size()));
}
private <T extends HasDescription> List<Object> buildValues(T owner, ClassesByTypeName importedClasses) {
List<Object> result = new ArrayList<>();
for (ValueBuilder value : values) {
result.addAll(value.build(owner, importedClasses).asSet());
}
return result;
}
private Optional<Class<?>> determineComponentType(ClassesByTypeName importedClasses) {
if (derivedComponentType != null) {
return Optional.<Class<?>>of(derivedComponentType);
}
JavaClass annotationType = importedClasses.get(annotationArrayContext.getDeclaringAnnotationTypeName());
Optional<JavaMethod> method = annotationType
.tryGetMethod(annotationArrayContext.getDeclaringAnnotationMemberName());
return method.isPresent() ?
determineComponentTypeFromReturnValue(method) :
Optional.<Class<?>>absent();
}
private Optional<Class<?>> determineComponentTypeFromReturnValue(Optional<JavaMethod> method) {
String name = method.get().getRawReturnType().getName();
Optional<Class<?>> result = AnnotationTypeConversion.tryConvert(name);
if (result.isPresent()) {
return Optional.<Class<?>>of(result.get().getComponentType());
}
return resolveComponentTypeFrom(name);
}
@MayResolveTypesViaReflection(reason = "Resolving primitives does not really use reflection")
private Optional<Class<?>> resolveComponentTypeFrom(String name) {
JavaType type = JavaType.From.name(name);
JavaType componentType = getComponentType(type);
if (componentType.isPrimitive()) {
return Optional.<Class<?>>of(componentType.resolveClass());
}
if (String.class.getName().equals(componentType.getName())) {
return Optional.<Class<?>>of(String.class);
}
// if we couldn't determine the type up to now, it must be an empty enum or annotation array,
// it's not completely consistent, but we'll just treat this as Object array for now and see
// if this will ever make a problem, since annotation proxy would to the conversion backwards
// and if one has to handle get(property): Object, this to be an empty Object[]
// instead of a JavaEnumConstant[] or JavaAnnotation<?>[] should hardly cause any real problems
return Optional.<Class<?>>of(Object.class);
}
private JavaType getComponentType(JavaType type) {
Optional<JavaType> result = type.tryGetComponentType();
checkState(result.isPresent(), "Couldn't determine component type of array return type %s, " +
"this is most likely a bug", type.getName());
return result.get();
}
}
}
private interface AnnotationArrayContext {
String getDeclaringAnnotationTypeName();
String getDeclaringAnnotationMemberName();
void setArrayResult(ValueBuilder valueBuilder);
}
private static ValueBuilder javaEnumBuilder(final String desc, final String value) {
return new ValueBuilder() {
@Override
public <T extends HasDescription> Optional<Object> build(T owner, ClassesByTypeName importedClasses) {
return Optional.<Object>of(
new DomainBuilders.JavaEnumConstantBuilder()
.withDeclaringClass(importedClasses.get(Type.getType(desc).getClassName()))
.withName(value)
.build());
}
};
}
private static class AnnotationTypeConversion {
private static final Map<String, Class<?>> externalTypeToInternalType = ImmutableMap.of(
Type.class.getName(), JavaClass.class,
Class.class.getName(), JavaClass.class,
Class[].class.getName(), JavaClass[].class
);
private static final Map<Class<?>, Function<Object, ValueBuilder>> importedValueToInternalValue =
ImmutableMap.<Class<?>, Function<Object, ValueBuilder>>of(
Type.class, new Function<Object, ValueBuilder>() {
@Override
public ValueBuilder apply(final Object input) {
return new ValueBuilder() {
@Override
public <T extends HasDescription> Optional<Object> build(T owner, ClassesByTypeName importedClasses) {
return Optional.<Object>of(importedClasses.get(((Type) input).getClassName()));
}
};
}
}
);
static Class<?> convert(Class<?> type) {
return externalTypeToInternalType.containsKey(type.getName()) ?
externalTypeToInternalType.get(type.getName()) :
type;
}
static Optional<Class<?>> tryConvert(String typeName) {
return externalTypeToInternalType.containsKey(typeName) ?
Optional.<Class<?>>of(externalTypeToInternalType.get(typeName)) :
Optional.<Class<?>>absent();
}
static ValueBuilder convert(Object value) {
return importedValueToInternalValue.containsKey(value.getClass()) ?
importedValueToInternalValue.get(value.getClass()).apply(value) :
ValueBuilder.ofFinished(value);
}
}
}