-
Notifications
You must be signed in to change notification settings - Fork 1k
/
AbstractAnnotationMetadataBuilder.java
2278 lines (2104 loc) · 102 KB
/
AbstractAnnotationMetadataBuilder.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
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2017-2020 original authors
*
* 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
*
* https://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 io.micronaut.inject.annotation;
import io.micronaut.context.annotation.*;
import io.micronaut.core.annotation.*;
import io.micronaut.core.io.service.ServiceDefinition;
import io.micronaut.core.io.service.SoftServiceLoader;
import io.micronaut.core.naming.NameUtils;
import io.micronaut.core.util.CollectionUtils;
import io.micronaut.core.util.StringUtils;
import io.micronaut.core.value.OptionalValues;
import io.micronaut.inject.visitor.VisitorContext;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import jakarta.inject.Qualifier;
import java.lang.annotation.Annotation;
import java.lang.annotation.RetentionPolicy;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
/**
* An abstract implementation that builds {@link AnnotationMetadata}.
*
* @param <T> The element type
* @param <A> The annotation type
* @author Graeme Rocher
* @since 1.0
*/
public abstract class AbstractAnnotationMetadataBuilder<T, A> {
/**
* Names of annotations that should produce deprecation warnings.
* The key in the map is the deprecated annotation the value the replacement.
*/
private static final Map<String, String> DEPRECATED_ANNOTATION_NAMES = Collections.emptyMap();
private static final Map<String, List<AnnotationMapper<?>>> ANNOTATION_MAPPERS = new HashMap<>(10);
private static final Map<String, List<AnnotationTransformer<Annotation>>> ANNOTATION_TRANSFORMERS = new HashMap<>(5);
private static final Map<String, List<AnnotationRemapper>> ANNOTATION_REMAPPERS = new HashMap<>(5);
private static final Map<MetadataKey, AnnotationMetadata> MUTATED_ANNOTATION_METADATA = new HashMap<>(100);
private static final List<String> DEFAULT_ANNOTATE_EXCLUDES = Arrays.asList(Internal.class.getName(), Experimental.class.getName());
private static final Map<String, Map<String, Object>> ANNOTATION_DEFAULTS = new HashMap<>(20);
static {
SoftServiceLoader<AnnotationMapper> serviceLoader = SoftServiceLoader.load(AnnotationMapper.class, AbstractAnnotationMetadataBuilder.class.getClassLoader());
for (ServiceDefinition<AnnotationMapper> definition : serviceLoader) {
if (definition.isPresent()) {
AnnotationMapper mapper = definition.load();
try {
String name = null;
if (mapper instanceof TypedAnnotationMapper) {
name = ((TypedAnnotationMapper) mapper).annotationType().getName();
} else if (mapper instanceof NamedAnnotationMapper) {
name = ((NamedAnnotationMapper) mapper).getName();
}
if (StringUtils.isNotEmpty(name)) {
ANNOTATION_MAPPERS.computeIfAbsent(name, s -> new ArrayList<>(2)).add(mapper);
}
} catch (Throwable e) {
// mapper, missing dependencies, continue
}
}
}
SoftServiceLoader<AnnotationTransformer> transformerSoftServiceLoader =
SoftServiceLoader.load(AnnotationTransformer.class, AbstractAnnotationMetadataBuilder.class.getClassLoader());
for (ServiceDefinition<AnnotationTransformer> definition : transformerSoftServiceLoader) {
if (definition.isPresent()) {
AnnotationTransformer transformer = definition.load();
try {
String name = null;
if (transformer instanceof TypedAnnotationTransformer) {
name = ((TypedAnnotationTransformer) transformer).annotationType().getName();
} else if (transformer instanceof NamedAnnotationTransformer) {
name = ((NamedAnnotationTransformer) transformer).getName();
}
if (StringUtils.isNotEmpty(name)) {
ANNOTATION_TRANSFORMERS.computeIfAbsent(name, s -> new ArrayList<>(2)).add(transformer);
}
} catch (Throwable e) {
// mapper, missing dependencies, continue
}
}
}
SoftServiceLoader<AnnotationRemapper> remapperLoader = SoftServiceLoader.load(AnnotationRemapper.class, AbstractAnnotationMetadataBuilder.class.getClassLoader());
for (ServiceDefinition<AnnotationRemapper> definition : remapperLoader) {
if (definition.isPresent()) {
AnnotationRemapper mapper = definition.load();
try {
String name = mapper.getPackageName();
if (StringUtils.isNotEmpty(name)) {
ANNOTATION_REMAPPERS.computeIfAbsent(name, s -> new ArrayList<>(2)).add(mapper);
}
} catch (Throwable e) {
// mapper, missing dependencies, continue
}
}
}
}
private boolean validating = true;
private final Set<T> erroneousElements = new HashSet<>();
/**
* Default constructor.
*/
protected AbstractAnnotationMetadataBuilder() {
}
/**
* Build only metadata for declared annotations.
*
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildDeclared(T element) {
DefaultAnnotationMetadata annotationMetadata = new MutableAnnotationMetadata();
try {
AnnotationMetadata metadata = buildInternal(null, element, annotationMetadata, true, true, true);
if (metadata.isEmpty()) {
return AnnotationMetadata.EMPTY_METADATA;
}
return metadata;
} catch (RuntimeException e) {
if ("org.eclipse.jdt.internal.compiler.problem.AbortCompilation".equals(e.getClass().getName())) {
// workaround for a bug in the Eclipse APT implementation. See bug 541466 on their Bugzilla.
return AnnotationMetadata.EMPTY_METADATA;
} else {
throw e;
}
}
}
/**
* Build only metadata for declared annotations.
*
* @param element The element
* @param annotations The annotations
* @param includeTypeAnnotations Whether to include type level annotations in the metadata for the element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildDeclared(T element, List<? extends A> annotations, boolean includeTypeAnnotations) {
if (CollectionUtils.isEmpty(annotations)) {
return AnnotationMetadata.EMPTY_METADATA;
}
DefaultAnnotationMetadata annotationMetadata = new MutableAnnotationMetadata();
if (includeTypeAnnotations) {
buildInternal(element, element, annotationMetadata, false, true, true);
}
try {
includeAnnotations(annotationMetadata, element, false, true, annotations, true);
if (annotationMetadata.isEmpty()) {
return AnnotationMetadata.EMPTY_METADATA;
}
return annotationMetadata;
} catch (RuntimeException e) {
if ("org.eclipse.jdt.internal.compiler.problem.AbortCompilation".equals(e.getClass().getName())) {
// workaround for a bug in the Eclipse APT implementation. See bug 541466 on their Bugzilla.
return AnnotationMetadata.EMPTY_METADATA;
} else {
throw e;
}
}
}
/**
* Build metadata for the given element, including any metadata that is inherited via method or type overrides.
*
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildOverridden(T element) {
final AnnotationMetadata existing = MUTATED_ANNOTATION_METADATA.get(new MetadataKey(getDeclaringType(element), element));
if (existing != null) {
return existing;
} else {
DefaultAnnotationMetadata annotationMetadata = new MutableAnnotationMetadata();
try {
AnnotationMetadata metadata = buildInternal(null, element, annotationMetadata, false, false, true);
if (metadata.isEmpty()) {
return AnnotationMetadata.EMPTY_METADATA;
}
return metadata;
} catch (RuntimeException e) {
if ("org.eclipse.jdt.internal.compiler.problem.AbortCompilation".equals(e.getClass().getName())) {
// workaround for a bug in the Eclipse APT implementation. See bug 541466 on their Bugzilla.
return AnnotationMetadata.EMPTY_METADATA;
} else {
throw e;
}
}
}
}
/**
* Build the meta data for the given element. If the element is a method the class metadata will be included.
*
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata build(T element) {
String declaringType = getDeclaringType(element);
return build(declaringType, element);
}
/**
* Build the meta data for the given element. If the element is a method the class metadata will be included.
*
* @param declaringType The declaring type
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata build(String declaringType, T element) {
final AnnotationMetadata existing = lookupExisting(declaringType, element);
if (existing != null) {
return existing;
} else {
DefaultAnnotationMetadata annotationMetadata = new MutableAnnotationMetadata();
try {
AnnotationMetadata metadata = buildInternal(null, element, annotationMetadata, true, false, true);
if (metadata.isEmpty()) {
return AnnotationMetadata.EMPTY_METADATA;
}
return metadata;
} catch (RuntimeException e) {
if ("org.eclipse.jdt.internal.compiler.problem.AbortCompilation".equals(e.getClass().getName())) {
// workaround for a bug in the Eclipse APT implementation. See bug 541466 on their Bugzilla.
return AnnotationMetadata.EMPTY_METADATA;
} else {
throw e;
}
}
}
}
/**
* Whether the element is a field, method, class or constructor.
*
* @param element The element
* @return True if it is
*/
protected abstract boolean isMethodOrClassElement(T element);
/**
* Obtains the declaring type for an element.
*
* @param element The element
* @return The declaring type
*/
protected abstract @NonNull String getDeclaringType(@NonNull T element);
/**
* Build the meta data for the given method element excluding any class metadata.
*
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForMethod(T element) {
String declaringType = getDeclaringType(element);
final AnnotationMetadata existing = lookupExisting(declaringType, element);
if (existing != null) {
return existing;
} else {
DefaultAnnotationMetadata annotationMetadata = new MutableAnnotationMetadata();
return buildInternal(null, element, annotationMetadata, false, false, true);
}
}
/**
* Get the annotation metadata for the given element and the given parent.
* This method is used for cases when you need to combine annotation metadata for
* two elements, for example a JavaBean property where the field and the method metadata
* need to be combined.
*
* @param parent The parent element
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForParent(T parent, T element) {
return buildForParents(parent == null ? Collections.emptyList() : Collections.singletonList(parent), element);
}
/**
* Get the annotation metadata for the given element and the given parents.
* This method is used for cases when you need to combine annotation metadata for
* two elements, for example a JavaBean property where the field and the method metadata
* need to be combined.
*
* @param parents The parent elements
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForParents(List<T> parents, T element) {
String declaringType = getDeclaringType(element);
return buildForParents(declaringType, parents, element);
}
/**
* Build the meta data for the given parent and method element excluding any class metadata.
*
* @param declaringType The declaring type
* @param parent The parent element
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForParent(String declaringType, T parent, T element) {
return buildForParents(declaringType, parent == null ? Collections.emptyList() : Collections.singletonList(parent), element);
}
/**
* Build the meta data for the given parents and method element excluding any class metadata.
*
* @param declaringType The declaring type
* @param parents The parent elements
* @param element The element
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForParents(String declaringType, List<T> parents, T element) {
final AnnotationMetadata existing = lookupExisting(declaringType, element);
DefaultAnnotationMetadata annotationMetadata;
if (existing instanceof DefaultAnnotationMetadata) {
// ugly, but will have to do
annotationMetadata = ((DefaultAnnotationMetadata) existing).clone();
} else if (existing instanceof AnnotationMetadataHierarchy) {
final AnnotationMetadata declaredMetadata = ((AnnotationMetadataHierarchy) existing).getDeclaredMetadata();
if (declaredMetadata instanceof DefaultAnnotationMetadata) {
annotationMetadata = ((DefaultAnnotationMetadata) declaredMetadata).clone();
} else {
annotationMetadata = new MutableAnnotationMetadata();
}
} else {
annotationMetadata = new MutableAnnotationMetadata();
}
return buildInternalMulti(parents, element, annotationMetadata, false, false, true);
}
/**
* Build the meta data for the given method element excluding any class metadata.
*
* @param parent The parent element
* @param element The element
* @param inheritTypeAnnotations Whether to inherit annotations from type as stereotypes
* @return The {@link AnnotationMetadata}
*/
public AnnotationMetadata buildForParent(T parent, T element, boolean inheritTypeAnnotations) {
String declaringType = getDeclaringType(element);
final AnnotationMetadata existing = lookupExisting(declaringType, element);
DefaultAnnotationMetadata annotationMetadata;
if (existing instanceof DefaultAnnotationMetadata) {
// ugly, but will have to do
annotationMetadata = ((DefaultAnnotationMetadata) existing).clone();
} else if (existing instanceof AnnotationMetadataHierarchy) {
final AnnotationMetadata declaredMetadata = existing.getDeclaredMetadata();
if (declaredMetadata instanceof DefaultAnnotationMetadata) {
annotationMetadata = ((DefaultAnnotationMetadata) declaredMetadata).clone();
} else {
annotationMetadata = new MutableAnnotationMetadata();
}
} else {
annotationMetadata = new MutableAnnotationMetadata();
}
return buildInternal(parent, element, annotationMetadata, inheritTypeAnnotations, false, true);
}
/**
* Get the type of the given annotation.
*
* @param annotationMirror The annotation
* @return The type
*/
protected abstract T getTypeForAnnotation(A annotationMirror);
/**
* Checks whether an annotation is present.
*
* @param element The element
* @param annotation The annotation type
* @return True if the annotation is present
*/
protected abstract boolean hasAnnotation(T element, Class<? extends Annotation> annotation);
/**
* Checks whether an annotation is present.
*
* @param element The element
* @param annotation The annotation type name
* @return True if the annotation is present
*/
protected abstract boolean hasAnnotation(T element, String annotation);
/**
* Checks whether any annotations are present on the given element.
*
* @param element The element
* @return True if the annotation is present
*/
protected abstract boolean hasAnnotations(T element);
/**
* Get the given type of the annotation.
*
* @param annotationMirror The annotation
* @return The type
*/
protected abstract String getAnnotationTypeName(A annotationMirror);
/**
* Get the name for the given element.
* @param element The element
* @return The name
*/
protected abstract String getElementName(T element);
/**
* Obtain the annotations for the given type. This method
* is also responsible for unwrapping repeatable annotations.
*
* For example, {@code @Parent(value = {@Child, @Child})} should result in the two
* child annotations being returned from this method <b>instead</b> of the
* parent annotation.
*
* @param element The type element
* @return The annotations
*/
protected abstract List<? extends A> getAnnotationsForType(T element);
/**
* Build the type hierarchy for the given element.
*
* @param element The element
* @param inheritTypeAnnotations Whether to inherit type annotations
* @param declaredOnly Whether to only include declared annotations
* @return The type hierarchy
*/
protected abstract List<T> buildHierarchy(T element, boolean inheritTypeAnnotations, boolean declaredOnly);
/**
* Read the given member and value, applying conversions if necessary, and place the data in the given map.
*
* @param originatingElement The originating element
* @param annotationName The annotation name
* @param member The member being read from
* @param memberName The member
* @param annotationValue The value
* @param annotationValues The values to populate
*/
protected abstract void readAnnotationRawValues(
T originatingElement,
String annotationName,
T member,
String memberName,
Object annotationValue,
Map<CharSequence, Object> annotationValues);
/**
* Validates an annotation value.
*
* @param originatingElement The originating element
* @param annotationName The annotation name
* @param member The member
* @param memberName The member name
* @param resolvedValue The resolved value
*/
protected void validateAnnotationValue(T originatingElement, String annotationName, T member, String memberName, Object resolvedValue) {
if (!validating) {
return;
}
final AnnotatedElementValidator elementValidator = getElementValidator();
if (elementValidator != null && !erroneousElements.contains(member)) {
boolean shouldValidate = !(annotationName.equals(AliasFor.class.getName())) &&
(!(resolvedValue instanceof String) || !resolvedValue.toString().contains("${"));
if (shouldValidate) {
shouldValidate = isValidationRequired(member);
}
if (shouldValidate) {
AnnotationMetadata metadata;
try {
validating = false;
metadata = buildDeclared(member);
} finally {
validating = true;
}
final Set<String> errors = elementValidator.validatedAnnotatedElement(new AnnotatedElement() {
@NonNull
@Override
public String getName() {
return memberName;
}
@Override
public AnnotationMetadata getAnnotationMetadata() {
return metadata;
}
}, resolvedValue);
if (CollectionUtils.isNotEmpty(errors)) {
erroneousElements.add(member);
for (String error : errors) {
error = "@" + NameUtils.getSimpleName(annotationName) + "." + memberName + ": " + error;
addError(originatingElement, error);
}
}
}
}
}
/**
* Return whether the given member requires validation.
* @param member The member
* @return True if it is
*/
protected abstract boolean isValidationRequired(T member);
/**
* Obtains the element validator.
*
* @return The validator.
*/
protected @Nullable
AnnotatedElementValidator getElementValidator() {
return null;
}
/**
* Adds an error.
*
* @param originatingElement The originating element
* @param error The error
*/
protected abstract void addError(@NonNull T originatingElement, @NonNull String error);
/**
* Adds an warning.
*
* @param originatingElement The originating element
* @param warning The warning
*/
protected abstract void addWarning(@NonNull T originatingElement, @NonNull String warning);
/**
* Read the given member and value, applying conversions if necessary, and place the data in the given map.
*
* @param originatingElement The originating element
* @param member The member
* @param memberName The member name
* @param annotationValue The value
* @return The object
*/
protected abstract Object readAnnotationValue(T originatingElement, T member, String memberName, Object annotationValue);
/**
* Read the raw default annotation values from the given annotation.
*
* @param annotationMirror The annotation
* @return The values
*/
protected abstract Map<? extends T, ?> readAnnotationDefaultValues(A annotationMirror);
/**
* Read the raw default annotation values from the given annotation.
*
* @param annotationName annotation name
* @param annotationType the type
* @return The values
*/
protected abstract Map<? extends T, ?> readAnnotationDefaultValues(String annotationName, T annotationType);
/**
* Read the raw annotation values from the given annotation.
*
* @param annotationMirror The annotation
* @return The values
*/
protected abstract Map<? extends T, ?> readAnnotationRawValues(A annotationMirror);
/**
* Resolve the annotations values from the given member for the given type.
*
* @param originatingElement The originating element
* @param member The member
* @param annotationType The type
* @return The values
*/
protected abstract OptionalValues<?> getAnnotationValues(T originatingElement, T member, Class<?> annotationType);
/**
* Read the name of an annotation member.
*
* @param member The member
* @return The name
*/
protected abstract String getAnnotationMemberName(T member);
/**
* Obtain the name of the repeatable annotation if the annotation is is one.
*
* @param annotationMirror The annotation mirror
* @return Return the name or null
*/
protected abstract @Nullable
String getRepeatableName(A annotationMirror);
/**
* Obtain the name of the repeatable annotation if the annotation is is one.
*
* @param annotationType The annotation mirror
* @return Return the name or null
*/
protected abstract @Nullable
String getRepeatableNameForType(T annotationType);
/**
* @param originatingElement The originating element
* @param annotationMirror The annotation
* @return The annotation value
*/
protected io.micronaut.core.annotation.AnnotationValue readNestedAnnotationValue(T originatingElement, A annotationMirror) {
io.micronaut.core.annotation.AnnotationValue av;
Map<? extends T, ?> annotationValues = readAnnotationRawValues(annotationMirror);
final String annotationTypeName = getAnnotationTypeName(annotationMirror);
if (annotationValues.isEmpty()) {
av = new io.micronaut.core.annotation.AnnotationValue(annotationTypeName);
} else {
Map<CharSequence, Object> resolvedValues = new LinkedHashMap<>();
for (Map.Entry<? extends T, ?> entry : annotationValues.entrySet()) {
T member = entry.getKey();
OptionalValues<?> aliasForValues = getAnnotationValues(originatingElement, member, AliasFor.class);
Object annotationValue = entry.getValue();
Optional<?> aliasMember = aliasForValues.get("member");
Optional<?> aliasAnnotation = aliasForValues.get("annotation");
Optional<?> aliasAnnotationName = aliasForValues.get("annotationName");
if (aliasMember.isPresent() && !(aliasAnnotation.isPresent() || aliasAnnotationName.isPresent())) {
String aliasedNamed = aliasMember.get().toString();
readAnnotationRawValues(originatingElement, annotationTypeName, member, aliasedNamed, annotationValue, resolvedValues);
}
String memberName = getAnnotationMemberName(member);
readAnnotationRawValues(originatingElement, annotationTypeName, member, memberName, annotationValue, resolvedValues);
}
av = new io.micronaut.core.annotation.AnnotationValue(annotationTypeName, resolvedValues);
}
return av;
}
/**
* Return a mirror for the given annotation.
*
* @param annotationName The annotation name
* @return An optional mirror
*/
protected abstract Optional<T> getAnnotationMirror(String annotationName);
/**
* Populate the annotation data for the given annotation.
*
* @param originatingElement The element the annotation data originates from
* @param parent The parent element
* @param annotationMirror The annotation
* @param metadata the metadata
* @param isDeclared Is the annotation a declared annotation
* @param retentionPolicy The retention policy
* @param allowAliases Whether aliases are allowed
* @return The annotation values
*/
protected Map<CharSequence, Object> populateAnnotationData(
T originatingElement,
@Nullable T parent,
A annotationMirror,
DefaultAnnotationMetadata metadata,
boolean isDeclared,
RetentionPolicy retentionPolicy,
boolean allowAliases) {
return populateAnnotationData(
originatingElement,
parent == originatingElement,
annotationMirror,
metadata,
isDeclared,
retentionPolicy,
allowAliases
);
}
/**
* Populate the annotation data for the given annotation.
*
* @param originatingElement The element the annotation data originates from
* @param originatingElementIsSameParent Whether the originating element is considered a parent element
* @param annotationMirror The annotation
* @param metadata the metadata
* @param isDeclared Is the annotation a declared annotation
* @param retentionPolicy The retention policy
* @param allowAliases Whether aliases are allowed
* @return The annotation values
*/
protected Map<CharSequence, Object> populateAnnotationData(
T originatingElement,
boolean originatingElementIsSameParent,
A annotationMirror,
DefaultAnnotationMetadata metadata,
boolean isDeclared,
RetentionPolicy retentionPolicy,
boolean allowAliases) {
String annotationName = getAnnotationTypeName(annotationMirror);
if (retentionPolicy == RetentionPolicy.RUNTIME) {
processAnnotationDefaults(originatingElement, metadata, annotationName, () -> readAnnotationDefaultValues(annotationMirror));
}
List<String> parentAnnotations = new ArrayList<>();
parentAnnotations.add(annotationName);
Map<? extends T, ?> elementValues = readAnnotationRawValues(annotationMirror);
Map<CharSequence, Object> annotationValues;
if (CollectionUtils.isEmpty(elementValues)) {
annotationValues = new LinkedHashMap<>(3);
} else {
annotationValues = new LinkedHashMap<>(5);
Set<String> nonBindingMembers = new HashSet<>(2);
for (Map.Entry<? extends T, ?> entry : elementValues.entrySet()) {
T member = entry.getKey();
if (member == null) {
continue;
}
Object annotationValue = entry.getValue();
if (hasAnnotations(member)) {
final DefaultAnnotationMetadata memberMetadata = new DefaultAnnotationMetadata();
final List<? extends A> annotationsForMember = getAnnotationsForType(member)
.stream().filter((a) -> !getAnnotationTypeName(a).equals(annotationName))
.collect(Collectors.toList());
includeAnnotations(memberMetadata, member, false, true, annotationsForMember, false);
boolean isInstantiatedMember = memberMetadata.hasAnnotation(InstantiatedMember.class);
if (memberMetadata.hasAnnotation(NonBinding.class)) {
final String memberName = getElementName(member);
nonBindingMembers.add(memberName);
}
if (isInstantiatedMember) {
final String memberName = getAnnotationMemberName(member);
final Object rawValue = readAnnotationValue(originatingElement, member, memberName, annotationValue);
if (rawValue instanceof AnnotationClassValue) {
AnnotationClassValue acv = (AnnotationClassValue) rawValue;
annotationValues.put(memberName, new AnnotationClassValue(acv.getName(), true));
}
}
}
if (allowAliases) {
handleAnnotationAlias(
originatingElement,
metadata,
isDeclared,
annotationName,
parentAnnotations,
annotationValues,
member,
annotationValue
);
}
}
if (!nonBindingMembers.isEmpty()) {
T annotationType = getTypeForAnnotation(annotationMirror);
if (!hasAnnotation(annotationType, AnnotationUtil.QUALIFIER) &&
!hasAnnotation(annotationType, Qualifier.class)) {
addError(originatingElement, "@NonBinding annotation is only applicable to annotations that are annotated with @Qualifier");
} else {
metadata.addDeclaredStereotype(
Collections.singletonList(getAnnotationTypeName(annotationMirror)),
AnnotationUtil.QUALIFIER,
Collections.singletonMap("nonBinding", nonBindingMembers)
);
}
}
}
List<AnnotationMapper<?>> mappers = getAnnotationMappers(annotationName);
if (mappers != null) {
AnnotationValue<?> annotationValue = new AnnotationValue(annotationName, annotationValues);
VisitorContext visitorContext = createVisitorContext();
for (AnnotationMapper mapper : mappers) {
List mapped = mapper.map(annotationValue, visitorContext);
if (mapped != null) {
for (Object o : mapped) {
if (o instanceof AnnotationValue) {
AnnotationValue av = (AnnotationValue) o;
retentionPolicy = av.getRetentionPolicy();
String mappedAnnotationName = av.getAnnotationName();
Optional<T> mappedMirror = getAnnotationMirror(mappedAnnotationName);
String repeatableName = mappedMirror.map(this::getRepeatableNameForType).orElse(null);
if (repeatableName != null) {
if (isDeclared) {
metadata.addDeclaredRepeatable(
repeatableName,
av,
retentionPolicy
);
} else {
metadata.addRepeatable(
repeatableName,
av,
retentionPolicy
);
}
} else {
Map<CharSequence, Object> values = av.getValues();
if (isDeclared) {
metadata.addDeclaredAnnotation(
mappedAnnotationName,
values,
retentionPolicy
);
} else {
metadata.addAnnotation(
mappedAnnotationName,
values,
retentionPolicy
);
}
}
RetentionPolicy finalRetentionPolicy = retentionPolicy;
mappedMirror.ifPresent(annMirror -> {
Map<CharSequence, Object> values = av.getValues();
values.forEach((key, value) -> {
T member = getAnnotationMember(annMirror, key);
if (member != null) {
handleAnnotationAlias(
originatingElement,
metadata,
isDeclared,
mappedAnnotationName,
Collections.emptyList(),
annotationValues,
member,
value
);
}
});
if (finalRetentionPolicy == RetentionPolicy.RUNTIME) {
processAnnotationDefaults(originatingElement, metadata, mappedAnnotationName, () -> readAnnotationDefaultValues(mappedAnnotationName, annMirror));
}
final ArrayList<String> parents = new ArrayList<>();
processAnnotationStereotype(
parents,
annMirror,
mappedAnnotationName,
metadata,
isDeclared,
isInheritedAnnotationType(annMirror) || originatingElementIsSameParent);
});
}
}
}
}
}
return annotationValues;
}
private void handleAnnotationAlias(T originatingElement, DefaultAnnotationMetadata metadata, boolean isDeclared, String annotationName, List<String> parentAnnotations, Map<CharSequence, Object> annotationValues, T member, Object annotationValue) {
Optional<?> aliases = getAnnotationValues(originatingElement, member, Aliases.class).get("value");
if (aliases.isPresent()) {
Object value = aliases.get();
if (value instanceof AnnotationValue[]) {
AnnotationValue[] values = (AnnotationValue[]) value;
for (AnnotationValue av : values) {
OptionalValues<Object> aliasForValues = OptionalValues.of(Object.class, av.getValues());
processAnnotationAlias(
originatingElement,
annotationName,
member, metadata,
isDeclared,
parentAnnotations,
annotationValues,
annotationValue,
aliasForValues
);
}
}
readAnnotationRawValues(originatingElement, annotationName, member, getAnnotationMemberName(member), annotationValue, annotationValues);
} else {
OptionalValues<?> aliasForValues = getAnnotationValues(
originatingElement,
member,
AliasFor.class
);
processAnnotationAlias(
originatingElement,
annotationName,
member,
metadata,
isDeclared,
parentAnnotations,
annotationValues,
annotationValue,
aliasForValues
);
readAnnotationRawValues(originatingElement, annotationName, member, getAnnotationMemberName(member), annotationValue, annotationValues);
}
}
/**
* Get the annotation member.
* @param originatingElement The originatig element
* @param member The member
* @return The annotation member
*/
protected abstract @Nullable T getAnnotationMember(T originatingElement, CharSequence member);
/**
* Obtain the annotation mappers for the given annotation name.
* @param annotationName The annotation name
* @return The mappers
*/
protected @NonNull List<AnnotationMapper<? extends Annotation>> getAnnotationMappers(@NonNull String annotationName) {
return ANNOTATION_MAPPERS.get(annotationName);
}
/**
* Obtain the transformers mappers for the given annotation name.
* @param annotationName The annotation name
* @return The transformers
*/
protected @NonNull List<AnnotationTransformer<Annotation>> getAnnotationTransformers(@NonNull String annotationName) {
return ANNOTATION_TRANSFORMERS.get(annotationName);
}
/**
* Creates the visitor context for this implementation.
*
* @return The visitor context
*/
protected abstract VisitorContext createVisitorContext();
private void processAnnotationDefaults(T originatingElement, DefaultAnnotationMetadata metadata, String annotationName, Supplier<Map<? extends T, ?>> elementDefaultValues) {
Map<CharSequence, Object> defaultValues;
final Map<String, Object> defaults = ANNOTATION_DEFAULTS.get(annotationName);
if (defaults != null) {
defaultValues = new LinkedHashMap<>(defaults);
} else {
defaultValues = getAnnotationDefaults(originatingElement, annotationName, elementDefaultValues.get());
if (defaultValues != null) {
ANNOTATION_DEFAULTS.put(annotationName, defaultValues.entrySet().stream()
.collect(Collectors.toMap(
(entry) -> entry.getKey().toString(),
Map.Entry::getValue)));
} else {
defaultValues = Collections.emptyMap();
}
}
metadata.addDefaultAnnotationValues(annotationName, defaultValues);
}
private Map<CharSequence, Object> getAnnotationDefaults(T originatingElement, String annotationName, Map<? extends T, ?> elementDefaultValues) {
if (elementDefaultValues != null) {
Map<CharSequence, Object> defaultValues = new LinkedHashMap<>();
for (Map.Entry<? extends T, ?> entry : elementDefaultValues.entrySet()) {
T member = entry.getKey();
String memberName = getAnnotationMemberName(member);
if (!defaultValues.containsKey(memberName)) {
Object annotationValue = entry.getValue();
readAnnotationRawValues(originatingElement, annotationName, member, memberName, annotationValue, defaultValues);
}
}