-
Notifications
You must be signed in to change notification settings - Fork 566
/
AnnotationMetaDataProvider.java
865 lines (731 loc) · 34.2 KB
/
AnnotationMetaDataProvider.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
/*
* Hibernate Validator, declare and validate application constraints
*
* License: Apache License, Version 2.0
* See the license.txt file in the root directory or <http://www.apache.org/licenses/LICENSE-2.0>.
*/
package org.hibernate.validator.internal.metadata.provider;
import static org.hibernate.validator.internal.util.CollectionHelper.newArrayList;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashMap;
import static org.hibernate.validator.internal.util.CollectionHelper.newHashSet;
import static org.hibernate.validator.internal.util.ConcurrentReferenceHashMap.ReferenceType.SOFT;
import static org.hibernate.validator.internal.util.logging.Messages.MESSAGES;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.AnnotatedArrayType;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.AnnotatedParameterizedType;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Executable;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.validation.GroupSequence;
import javax.validation.Valid;
import javax.validation.groups.ConvertGroup;
import org.hibernate.validator.group.GroupSequenceProvider;
import org.hibernate.validator.internal.engine.valueextraction.ArrayElement;
import org.hibernate.validator.internal.engine.valueextraction.ValueExtractorManager;
import org.hibernate.validator.internal.metadata.aggregated.CascadingMetaDataBuilder;
import org.hibernate.validator.internal.metadata.core.AnnotationProcessingOptions;
import org.hibernate.validator.internal.metadata.core.AnnotationProcessingOptionsImpl;
import org.hibernate.validator.internal.metadata.core.ConstraintHelper;
import org.hibernate.validator.internal.metadata.core.MetaConstraint;
import org.hibernate.validator.internal.metadata.core.MetaConstraints;
import org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl;
import org.hibernate.validator.internal.metadata.descriptor.ConstraintDescriptorImpl.ConstraintType;
import org.hibernate.validator.internal.metadata.location.ConstraintLocation;
import org.hibernate.validator.internal.metadata.raw.BeanConfiguration;
import org.hibernate.validator.internal.metadata.raw.ConfigurationSource;
import org.hibernate.validator.internal.metadata.raw.ConstrainedElement;
import org.hibernate.validator.internal.metadata.raw.ConstrainedExecutable;
import org.hibernate.validator.internal.metadata.raw.ConstrainedField;
import org.hibernate.validator.internal.metadata.raw.ConstrainedParameter;
import org.hibernate.validator.internal.metadata.raw.ConstrainedType;
import org.hibernate.validator.internal.util.CollectionHelper;
import org.hibernate.validator.internal.util.ConcurrentReferenceHashMap;
import org.hibernate.validator.internal.util.ExecutableHelper;
import org.hibernate.validator.internal.util.ReflectionHelper;
import org.hibernate.validator.internal.util.TypeResolutionHelper;
import org.hibernate.validator.internal.util.logging.Log;
import org.hibernate.validator.internal.util.logging.LoggerFactory;
import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredConstructors;
import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredFields;
import org.hibernate.validator.internal.util.privilegedactions.GetDeclaredMethods;
import org.hibernate.validator.internal.util.privilegedactions.GetMethods;
import org.hibernate.validator.internal.util.privilegedactions.NewInstance;
import org.hibernate.validator.spi.group.DefaultGroupSequenceProvider;
/**
* {@code MetaDataProvider} which reads the metadata from annotations which is the default configuration source.
*
* @author Gunnar Morling
* @author Hardy Ferentschik
*/
public class AnnotationMetaDataProvider implements MetaDataProvider {
private static final Log log = LoggerFactory.make();
/**
* The default initial capacity for this cache.
*/
static final int DEFAULT_INITIAL_CAPACITY = 16;
protected final ConstraintHelper constraintHelper;
protected final TypeResolutionHelper typeResolutionHelper;
protected final ConcurrentReferenceHashMap<Class<?>, BeanConfiguration<?>> configuredBeans;
protected final AnnotationProcessingOptions annotationProcessingOptions;
protected final ValueExtractorManager valueExtractorManager;
public AnnotationMetaDataProvider(ConstraintHelper constraintHelper,
TypeResolutionHelper typeResolutionHelper,
ValueExtractorManager valueExtractorManager,
AnnotationProcessingOptions annotationProcessingOptions) {
this.constraintHelper = constraintHelper;
this.typeResolutionHelper = typeResolutionHelper;
this.valueExtractorManager = valueExtractorManager;
this.annotationProcessingOptions = annotationProcessingOptions;
this.configuredBeans = new ConcurrentReferenceHashMap<>(
DEFAULT_INITIAL_CAPACITY,
SOFT,
SOFT
);
}
@Override
public AnnotationProcessingOptions getAnnotationProcessingOptions() {
return new AnnotationProcessingOptionsImpl();
}
@Override
public <T> BeanConfiguration<T> getBeanConfiguration(Class<T> beanClass) {
@SuppressWarnings("unchecked")
BeanConfiguration<T> configuration = (BeanConfiguration<T>) configuredBeans.
computeIfAbsent( beanClass, bc -> retrieveBeanConfiguration( beanClass ) );
return configuration;
}
/**
* @param beanClass The bean class for which to retrieve the meta data
*
* @return Retrieves constraint related meta data from the annotations of the given type.
*/
private <T> BeanConfiguration<T> retrieveBeanConfiguration(Class<T> beanClass) {
Set<ConstrainedElement> constrainedElements = getFieldMetaData( beanClass );
constrainedElements.addAll( getMethodMetaData( beanClass ) );
constrainedElements.addAll( getConstructorMetaData( beanClass ) );
//TODO GM: currently class level constraints are represented by a PropertyMetaData. This
//works but seems somewhat unnatural
Set<MetaConstraint<?>> classLevelConstraints = getClassLevelConstraints( beanClass );
if ( !classLevelConstraints.isEmpty() ) {
ConstrainedType classLevelMetaData =
new ConstrainedType(
ConfigurationSource.ANNOTATION,
beanClass,
classLevelConstraints
);
constrainedElements.add( classLevelMetaData );
}
return new BeanConfiguration<>(
ConfigurationSource.ANNOTATION,
beanClass,
constrainedElements,
getDefaultGroupSequence( beanClass ),
getDefaultGroupSequenceProvider( beanClass )
);
}
private List<Class<?>> getDefaultGroupSequence(Class<?> beanClass) {
GroupSequence groupSequenceAnnotation = beanClass.getAnnotation( GroupSequence.class );
return groupSequenceAnnotation != null ? Arrays.asList( groupSequenceAnnotation.value() ) : null;
}
private <T> DefaultGroupSequenceProvider<? super T> getDefaultGroupSequenceProvider(Class<T> beanClass) {
GroupSequenceProvider groupSequenceProviderAnnotation = beanClass.getAnnotation( GroupSequenceProvider.class );
if ( groupSequenceProviderAnnotation != null ) {
@SuppressWarnings("unchecked")
Class<? extends DefaultGroupSequenceProvider<? super T>> providerClass =
(Class<? extends DefaultGroupSequenceProvider<? super T>>) groupSequenceProviderAnnotation.value();
return newGroupSequenceProviderClassInstance( beanClass, providerClass );
}
return null;
}
private <T> DefaultGroupSequenceProvider<? super T> newGroupSequenceProviderClassInstance(Class<T> beanClass,
Class<? extends DefaultGroupSequenceProvider<? super T>> providerClass) {
Method[] providerMethods = run( GetMethods.action( providerClass ) );
for ( Method method : providerMethods ) {
Class<?>[] paramTypes = method.getParameterTypes();
if ( "getValidationGroups".equals( method.getName() ) && !method.isBridge()
&& paramTypes.length == 1 && paramTypes[0].isAssignableFrom( beanClass ) ) {
return run(
NewInstance.action( providerClass, "the default group sequence provider" )
);
}
}
throw log.getWrongDefaultGroupSequenceProviderTypeException( beanClass );
}
private Set<MetaConstraint<?>> getClassLevelConstraints(Class<?> clazz) {
if ( annotationProcessingOptions.areClassLevelConstraintsIgnoredFor( clazz ) ) {
return Collections.emptySet();
}
Set<MetaConstraint<?>> classLevelConstraints = newHashSet();
// HV-262
List<ConstraintDescriptorImpl<?>> classMetaData = findClassLevelConstraints( clazz );
ConstraintLocation location = ConstraintLocation.forClass( clazz );
for ( ConstraintDescriptorImpl<?> constraintDescription : classMetaData ) {
classLevelConstraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescription, location ) );
}
return classLevelConstraints;
}
private Set<ConstrainedElement> getFieldMetaData(Class<?> beanClass) {
Set<ConstrainedElement> propertyMetaData = newHashSet();
for ( Field field : run( GetDeclaredFields.action( beanClass ) ) ) {
// HV-172
if ( Modifier.isStatic( field.getModifiers() ) ||
annotationProcessingOptions.areMemberConstraintsIgnoredFor( field ) ||
field.isSynthetic() ) {
continue;
}
propertyMetaData.add( findPropertyMetaData( field ) );
}
return propertyMetaData;
}
private ConstrainedField findPropertyMetaData(Field field) {
Set<MetaConstraint<?>> constraints = convertToMetaConstraints(
findConstraints( field, ElementType.FIELD ),
field
);
CascadingMetaDataBuilder cascadingMetaDataBuilder = findCascadingMetaData( field );
Set<MetaConstraint<?>> typeArgumentsConstraints = findTypeAnnotationConstraints( field );
return new ConstrainedField(
ConfigurationSource.ANNOTATION,
field,
constraints,
typeArgumentsConstraints,
cascadingMetaDataBuilder
);
}
private Set<MetaConstraint<?>> convertToMetaConstraints(List<ConstraintDescriptorImpl<?>> constraintDescriptors, Field field) {
if ( constraintDescriptors.isEmpty() ) {
return Collections.emptySet();
}
Set<MetaConstraint<?>> constraints = newHashSet();
ConstraintLocation location = ConstraintLocation.forField( field );
for ( ConstraintDescriptorImpl<?> constraintDescription : constraintDescriptors ) {
constraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescription, location ) );
}
return constraints;
}
private Set<ConstrainedExecutable> getConstructorMetaData(Class<?> clazz) {
Executable[] declaredConstructors = run( GetDeclaredConstructors.action( clazz ) );
return getMetaData( declaredConstructors );
}
private Set<ConstrainedExecutable> getMethodMetaData(Class<?> clazz) {
Executable[] declaredMethods = run( GetDeclaredMethods.action( clazz ) );
return getMetaData( declaredMethods );
}
private Set<ConstrainedExecutable> getMetaData(Executable[] executableElements) {
Set<ConstrainedExecutable> executableMetaData = newHashSet();
for ( Executable executable : executableElements ) {
// HV-172; ignoring synthetic methods (inserted by the compiler), as they can't have any constraints
// anyway and possibly hide the actual method with the same signature in the built meta model
if ( Modifier.isStatic( executable.getModifiers() ) || executable.isSynthetic() ) {
continue;
}
executableMetaData.add( findExecutableMetaData( executable ) );
}
return executableMetaData;
}
/**
* Finds all constraint annotations defined for the given method or constructor.
*
* @param executable The executable element to check for constraints annotations.
*
* @return A meta data object describing the constraints specified for the
* given element.
*/
private ConstrainedExecutable findExecutableMetaData(Executable executable) {
List<ConstrainedParameter> parameterConstraints = getParameterMetaData( executable );
Map<ConstraintType, List<ConstraintDescriptorImpl<?>>> executableConstraints = findConstraints( executable, ExecutableHelper.getElementType( executable ) )
.stream()
.collect( Collectors.groupingBy( ConstraintDescriptorImpl::getConstraintType ) );
Set<MetaConstraint<?>> crossParameterConstraints;
if ( annotationProcessingOptions.areCrossParameterConstraintsIgnoredFor( executable ) ) {
crossParameterConstraints = Collections.emptySet();
}
else {
crossParameterConstraints = convertToMetaConstraints(
executableConstraints.get( ConstraintType.CROSS_PARAMETER ),
executable
);
}
Set<MetaConstraint<?>> returnValueConstraints;
Set<MetaConstraint<?>> typeArgumentsConstraints;
CascadingMetaDataBuilder cascadingMetaDataBuilder;
if ( annotationProcessingOptions.areReturnValueConstraintsIgnoredFor( executable ) ) {
returnValueConstraints = Collections.emptySet();
typeArgumentsConstraints = Collections.emptySet();
cascadingMetaDataBuilder = CascadingMetaDataBuilder.nonCascading();
}
else {
AnnotatedType annotatedReturnType = executable.getAnnotatedReturnType();
typeArgumentsConstraints = findTypeAnnotationConstraints( executable, annotatedReturnType );
returnValueConstraints = convertToMetaConstraints(
executableConstraints.get( ConstraintType.GENERIC ),
executable
);
cascadingMetaDataBuilder = findCascadingMetaData( executable, annotatedReturnType );
}
return new ConstrainedExecutable(
ConfigurationSource.ANNOTATION,
executable,
parameterConstraints,
crossParameterConstraints,
returnValueConstraints,
typeArgumentsConstraints,
cascadingMetaDataBuilder
);
}
private Set<MetaConstraint<?>> convertToMetaConstraints(List<ConstraintDescriptorImpl<?>> constraintsDescriptors, Executable executable) {
if ( constraintsDescriptors == null ) {
return Collections.emptySet();
}
Set<MetaConstraint<?>> constraints = newHashSet();
ConstraintLocation returnValueLocation = ConstraintLocation.forReturnValue( executable );
ConstraintLocation crossParameterLocation = ConstraintLocation.forCrossParameter( executable );
for ( ConstraintDescriptorImpl<?> constraintDescriptor : constraintsDescriptors ) {
ConstraintLocation location = constraintDescriptor.getConstraintType() == ConstraintType.GENERIC ? returnValueLocation : crossParameterLocation;
constraints.add( MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescriptor, location ) );
}
return constraints;
}
/**
* Retrieves constraint related meta data for the parameters of the given
* executable.
*
* @param executable The executable of interest.
*
* @return A list with parameter meta data for the given executable.
*/
private List<ConstrainedParameter> getParameterMetaData(Executable executable) {
List<ConstrainedParameter> metaData = newArrayList();
int i = 0;
for ( Parameter parameter : executable.getParameters() ) {
Annotation[] parameterAnnotations;
try {
parameterAnnotations = parameter.getAnnotations();
}
catch (ArrayIndexOutOfBoundsException ex) {
log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex );
parameterAnnotations = new Annotation[0];
}
Set<MetaConstraint<?>> parameterConstraints = newHashSet();
if ( annotationProcessingOptions.areParameterConstraintsIgnoredFor( executable, i ) ) {
Type type = ReflectionHelper.typeOf( executable, i );
metaData.add(
new ConstrainedParameter(
ConfigurationSource.ANNOTATION,
executable,
type,
i,
parameterConstraints,
Collections.emptySet(),
CascadingMetaDataBuilder.nonCascading()
)
);
i++;
continue;
}
ConstraintLocation location = ConstraintLocation.forParameter( executable, i );
for ( Annotation parameterAnnotation : parameterAnnotations ) {
// collect constraints if this annotation is a constraint annotation
List<ConstraintDescriptorImpl<?>> constraints = findConstraintAnnotations(
executable, parameterAnnotation, ElementType.PARAMETER
);
for ( ConstraintDescriptorImpl<?> constraintDescriptorImpl : constraints ) {
parameterConstraints.add(
MetaConstraints.create( typeResolutionHelper, valueExtractorManager, constraintDescriptorImpl, location )
);
}
}
AnnotatedType parameterAnnotatedType = parameter.getAnnotatedType();
Set<MetaConstraint<?>> typeArgumentsConstraints = findTypeAnnotationConstraintsForExecutableParameter( executable, i, parameterAnnotatedType );
CascadingMetaDataBuilder cascadingMetaData = findCascadingMetaData( executable, i, parameterAnnotatedType );
metaData.add(
new ConstrainedParameter(
ConfigurationSource.ANNOTATION,
executable,
ReflectionHelper.typeOf( executable, i ),
i,
parameterConstraints,
typeArgumentsConstraints,
cascadingMetaData
)
);
i++;
}
return metaData;
}
/**
* Finds all constraint annotations defined for the given member and returns them in a list of
* constraint descriptors.
*
* @param member The member to check for constraints annotations.
* @param type The element type the constraint/annotation is placed on.
*
* @return A list of constraint descriptors for all constraint specified for the given member.
*/
private List<ConstraintDescriptorImpl<?>> findConstraints(Member member, ElementType type) {
List<ConstraintDescriptorImpl<?>> metaData = newArrayList();
for ( Annotation annotation : ( (AccessibleObject) member ).getDeclaredAnnotations() ) {
metaData.addAll( findConstraintAnnotations( member, annotation, type ) );
}
return metaData;
}
/**
* Finds all constraint annotations defined for the given class and returns them in a list of
* constraint descriptors.
*
* @param beanClass The class to check for constraints annotations.
*
* @return A list of constraint descriptors for all constraint specified on the given class.
*/
private List<ConstraintDescriptorImpl<?>> findClassLevelConstraints(Class<?> beanClass) {
List<ConstraintDescriptorImpl<?>> metaData = newArrayList();
for ( Annotation annotation : beanClass.getDeclaredAnnotations() ) {
metaData.addAll( findConstraintAnnotations( null, annotation, ElementType.TYPE ) );
}
return metaData;
}
/**
* Examines the given annotation to see whether it is a single- or multi-valued constraint annotation.
*
* @param member The member to check for constraints annotations
* @param annotation The annotation to examine
* @param type the element type on which the annotation/constraint is placed on
* @param <A> the annotation type
*
* @return A list of constraint descriptors or the empty list in case {@code annotation} is neither a
* single nor multi-valued annotation.
*/
protected <A extends Annotation> List<ConstraintDescriptorImpl<?>> findConstraintAnnotations(Member member,
A annotation,
ElementType type) {
// HV-1049 and HV-1311 - Ignore annotations from the JDK (jdk.internal.* and java.*); They cannot be constraint
// annotations so skip them right here, as for the proper check we'd need package access permission for
// "jdk.internal" and "java".
if ( constraintHelper.isJdkAnnotation( annotation.annotationType() ) ) {
return Collections.emptyList();
}
List<Annotation> constraints = newArrayList();
Class<? extends Annotation> annotationType = annotation.annotationType();
if ( constraintHelper.isConstraintAnnotation( annotationType ) ) {
constraints.add( annotation );
}
else if ( constraintHelper.isMultiValueConstraint( annotationType ) ) {
constraints.addAll( constraintHelper.getConstraintsFromMultiValueConstraint( annotation ) );
}
return constraints.stream()
.map( c -> buildConstraintDescriptor( member, c, type ) )
.collect( Collectors.toList() );
}
private Map<Class<?>, Class<?>> getGroupConversions(AnnotatedElement annotatedElement) {
return getGroupConversions(
annotatedElement.getAnnotation( ConvertGroup.class ),
annotatedElement.getAnnotation( ConvertGroup.List.class )
);
}
private Map<Class<?>, Class<?>> getGroupConversions(ConvertGroup groupConversion, ConvertGroup.List groupConversionList) {
Map<Class<?>, Class<?>> groupConversions = newHashMap();
if ( groupConversion != null ) {
groupConversions.put( groupConversion.from(), groupConversion.to() );
}
if ( groupConversionList != null ) {
for ( ConvertGroup conversion : groupConversionList.value() ) {
if ( groupConversions.containsKey( conversion.from() ) ) {
throw log.getMultipleGroupConversionsForSameSourceException(
conversion.from(),
CollectionHelper.<Class<?>>asSet(
groupConversions.get( conversion.from() ),
conversion.to()
)
);
}
groupConversions.put( conversion.from(), conversion.to() );
}
}
return groupConversions;
}
private <A extends Annotation> ConstraintDescriptorImpl<A> buildConstraintDescriptor(Member member,
A annotation,
ElementType type) {
return new ConstraintDescriptorImpl<>(
constraintHelper,
member,
annotation,
type
);
}
/**
* Runs the given privileged action, using a privileged block if required.
* <p>
* <b>NOTE:</b> This must never be changed into a publicly available method to avoid execution of arbitrary
* privileged actions within HV's protection domain.
*/
private <T> T run(PrivilegedAction<T> action) {
return System.getSecurityManager() != null ? AccessController.doPrivileged( action ) : action.run();
}
/**
* Finds type arguments constraints for fields.
*/
protected Set<MetaConstraint<?>> findTypeAnnotationConstraints(Field field) {
return findTypeArgumentsConstraints(
field,
new TypeArgumentFieldLocation( field ),
field.getAnnotatedType()
);
}
/**
* Finds type arguments constraints for method return values.
*/
protected Set<MetaConstraint<?>> findTypeAnnotationConstraints(Executable executable, AnnotatedType annotatedReturnType) {
return findTypeArgumentsConstraints(
executable,
new TypeArgumentReturnValueLocation( executable ),
annotatedReturnType
);
}
private CascadingMetaDataBuilder findCascadingMetaData(Executable executable, int i, AnnotatedType parameterAnnotatedType) {
Parameter parameter = executable.getParameters()[i];
TypeVariable<?>[] typeParameters = parameter.getType().getTypeParameters();
Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( parameterAnnotatedType,
typeParameters );
try {
return getCascadingMetaData( ReflectionHelper.typeOf( parameter.getDeclaringExecutable(), i ),
parameter, containerElementTypesCascadingMetaData );
}
catch (ArrayIndexOutOfBoundsException ex) {
log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex );
return CascadingMetaDataBuilder.nonCascading();
}
}
private CascadingMetaDataBuilder findCascadingMetaData(Field field) {
TypeVariable<?>[] typeParameters = field.getType().getTypeParameters();
AnnotatedType annotatedType = field.getAnnotatedType();
Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( annotatedType, typeParameters );
return getCascadingMetaData( ReflectionHelper.typeOf( field ), field, containerElementTypesCascadingMetaData );
}
private CascadingMetaDataBuilder findCascadingMetaData(Executable executable, AnnotatedType annotatedReturnType) {
TypeVariable<?>[] typeParameters;
if ( executable instanceof Method ) {
typeParameters = ( (Method) executable ).getReturnType().getTypeParameters();
}
else {
typeParameters = ( (Constructor<?>) executable ).getDeclaringClass().getTypeParameters();
}
Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData = getTypeParametersCascadingMetadata( annotatedReturnType,
typeParameters );
return getCascadingMetaData( ReflectionHelper.typeOf( executable ), executable, containerElementTypesCascadingMetaData );
}
private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetadata(AnnotatedType annotatedType,
TypeVariable<?>[] typeParameters) {
if ( annotatedType instanceof AnnotatedArrayType ) {
return getTypeParametersCascadingMetaDataForArrayType( (AnnotatedArrayType) annotatedType );
}
else if ( annotatedType instanceof AnnotatedParameterizedType ) {
return getTypeParametersCascadingMetaDataForParameterizedType( (AnnotatedParameterizedType) annotatedType, typeParameters );
}
else {
return Collections.emptyMap();
}
}
private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForParameterizedType(
AnnotatedParameterizedType annotatedParameterizedType, TypeVariable<?>[] typeParameters) {
Map<TypeVariable<?>, CascadingMetaDataBuilder> typeParametersCascadingMetadata = CollectionHelper.newHashMap( typeParameters.length );
AnnotatedType[] annotatedTypeArguments = annotatedParameterizedType.getAnnotatedActualTypeArguments();
int i = 0;
for ( AnnotatedType annotatedTypeArgument : annotatedTypeArguments ) {
Map<TypeVariable<?>, CascadingMetaDataBuilder> nestedTypeParametersCascadingMetadata = getTypeParametersCascadingMetaDataForAnnotatedType(
annotatedTypeArgument );
typeParametersCascadingMetadata.put( typeParameters[i], new CascadingMetaDataBuilder( annotatedParameterizedType.getType(), typeParameters[i],
annotatedTypeArgument.isAnnotationPresent( Valid.class ), nestedTypeParametersCascadingMetadata,
getGroupConversions( annotatedTypeArgument ) ) );
i++;
}
return typeParametersCascadingMetadata;
}
private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForArrayType(AnnotatedArrayType annotatedArrayType) {
// HV-1428 Container element support is disabled for arrays
return Collections.emptyMap();
// Map<TypeVariable<?>, CascadingTypeParameter> typeParametersCascadingMetadata = CollectionHelper.newHashMap( 1 );
// AnnotatedType containerElementAnnotatedType = annotatedArrayType.getAnnotatedGenericComponentType();
//
// Map<TypeVariable<?>, CascadingTypeParameter> nestedTypeParametersCascadingMetadata = getTypeParametersCascadingMetaDataForAnnotatedType(
// containerElementAnnotatedType );
//
// TypeVariable<?> arrayElement = new ArrayElement( annotatedArrayType );
// typeParametersCascadingMetadata.put( arrayElement, new CascadingTypeParameter( annotatedArrayType.getType(),
// arrayElement,
// annotatedArrayType.isAnnotationPresent( Valid.class ),
// nestedTypeParametersCascadingMetadata,
// getGroupConversions( annotatedArrayType ) ) );
//
// return typeParametersCascadingMetadata;
}
private Map<TypeVariable<?>, CascadingMetaDataBuilder> getTypeParametersCascadingMetaDataForAnnotatedType(AnnotatedType annotatedType) {
if ( annotatedType instanceof AnnotatedArrayType ) {
return getTypeParametersCascadingMetaDataForArrayType( (AnnotatedArrayType) annotatedType );
}
else if ( annotatedType instanceof AnnotatedParameterizedType ) {
return getTypeParametersCascadingMetaDataForParameterizedType( (AnnotatedParameterizedType) annotatedType,
ReflectionHelper.getClassFromType( annotatedType.getType() ).getTypeParameters() );
}
else {
return Collections.emptyMap();
}
}
/**
* Finds type arguments constraints for parameters.
*
* @param executable the executable
* @param i the parameter index
*
* @return a set of type arguments constraints, or an empty set if no constrained type arguments are found
*/
protected Set<MetaConstraint<?>> findTypeAnnotationConstraintsForExecutableParameter(Executable executable, int i, AnnotatedType parameterAnnotatedType) {
try {
return findTypeArgumentsConstraints(
executable,
new TypeArgumentExecutableParameterLocation( executable, i ),
parameterAnnotatedType
);
}
catch (ArrayIndexOutOfBoundsException ex) {
log.warn( MESSAGES.constraintOnConstructorOfNonStaticInnerClass(), ex );
return Collections.emptySet();
}
}
private Set<MetaConstraint<?>> findTypeArgumentsConstraints(Member member, TypeArgumentLocation location, AnnotatedType annotatedType) {
// HV-1428 Container element support is disabled for arrays
if ( !(annotatedType instanceof AnnotatedParameterizedType) ) {
return Collections.emptySet();
}
Set<MetaConstraint<?>> typeArgumentConstraints = new HashSet<>();
// if we have an array, we need to unwrap the array first
if ( annotatedType instanceof AnnotatedArrayType ) {
AnnotatedArrayType annotatedArrayType = (AnnotatedArrayType) annotatedType;
Type validatedType = annotatedArrayType.getAnnotatedGenericComponentType().getType();
TypeVariable<?> arrayElementTypeArgument = new ArrayElement( annotatedArrayType );
typeArgumentConstraints.addAll( findTypeUseConstraints( member, annotatedArrayType, arrayElementTypeArgument, location, validatedType ) );
typeArgumentConstraints.addAll( findTypeArgumentsConstraints( member,
new NestedTypeArgumentLocation( location, arrayElementTypeArgument, validatedType ),
annotatedArrayType.getAnnotatedGenericComponentType() ) );
}
else if ( annotatedType instanceof AnnotatedParameterizedType ) {
AnnotatedParameterizedType annotatedParameterizedType = (AnnotatedParameterizedType) annotatedType;
int i = 0;
for ( TypeVariable<?> typeVariable : ReflectionHelper.getClassFromType( annotatedType.getType() ).getTypeParameters() ) {
AnnotatedType annotatedTypeParameter = annotatedParameterizedType.getAnnotatedActualTypeArguments()[i];
// HV-925
// We need to determine the validated type used for constraint validator resolution.
// Iterables and maps need special treatment at this point, since the validated type is the type of the
// specified type parameter. In the other cases the validated type is the parameterized type, eg Optional<String>.
// In the latter case a value unwrapping has to occur
Type validatedType = annotatedTypeParameter.getType();
typeArgumentConstraints.addAll( findTypeUseConstraints( member, annotatedTypeParameter, typeVariable, location, validatedType ) );
if ( validatedType instanceof ParameterizedType ) {
typeArgumentConstraints.addAll( findTypeArgumentsConstraints( member,
new NestedTypeArgumentLocation( location, typeVariable, validatedType ),
annotatedTypeParameter ) );
}
i++;
}
}
return typeArgumentConstraints.isEmpty() ? Collections.emptySet() : typeArgumentConstraints;
}
/**
* Finds type use annotation constraints defined on the type argument.
*/
private Set<MetaConstraint<?>> findTypeUseConstraints(Member member, AnnotatedType typeArgument, TypeVariable<?> typeVariable, TypeArgumentLocation location, Type type) {
Set<MetaConstraint<?>> constraints = Arrays.stream( typeArgument.getAnnotations() )
.flatMap( a -> findConstraintAnnotations( member, a, ElementType.TYPE_USE ).stream() )
.map( d -> createTypeArgumentMetaConstraint( d, location, typeVariable, type ) )
.collect( Collectors.toSet() );
return constraints;
}
/**
* Creates a {@code MetaConstraint} for a type argument constraint.
*/
private <A extends Annotation> MetaConstraint<?> createTypeArgumentMetaConstraint(ConstraintDescriptorImpl<A> descriptor, TypeArgumentLocation location,
TypeVariable<?> typeVariable, Type type) {
ConstraintLocation constraintLocation = ConstraintLocation.forTypeArgument( location.toConstraintLocation(), typeVariable, type );
return MetaConstraints.create( typeResolutionHelper, valueExtractorManager, descriptor, constraintLocation );
}
private CascadingMetaDataBuilder getCascadingMetaData(Type type, AnnotatedElement annotatedElement,
Map<TypeVariable<?>, CascadingMetaDataBuilder> containerElementTypesCascadingMetaData) {
return CascadingMetaDataBuilder.annotatedObject( type, annotatedElement.isAnnotationPresent( Valid.class ), containerElementTypesCascadingMetaData,
getGroupConversions( annotatedElement ) );
}
/**
* The location of a type argument before it is really considered a constraint location.
* <p>
* It avoids initializing a constraint location if we did not find any constraints. This is especially useful in
* a Java 9 environment as {@link ConstraintLocation#forProperty(Member) tries to make the {@code Member} accessible
* which might not be possible (for instance for {@code java.util} classes).
*/
private interface TypeArgumentLocation {
ConstraintLocation toConstraintLocation();
}
private static class TypeArgumentExecutableParameterLocation implements TypeArgumentLocation {
private final Executable executable;
private final int index;
private TypeArgumentExecutableParameterLocation(Executable executable, int index) {
this.executable = executable;
this.index = index;
}
@Override
public ConstraintLocation toConstraintLocation() {
return ConstraintLocation.forParameter( executable, index );
}
}
private static class TypeArgumentFieldLocation implements TypeArgumentLocation {
private final Field field;
private TypeArgumentFieldLocation(Field field) {
this.field = field;
}
@Override
public ConstraintLocation toConstraintLocation() {
return ConstraintLocation.forField( field );
}
}
private static class TypeArgumentReturnValueLocation implements TypeArgumentLocation {
private final Executable executable;
private TypeArgumentReturnValueLocation(Executable executable) {
this.executable = executable;
}
@Override
public ConstraintLocation toConstraintLocation() {
return ConstraintLocation.forReturnValue( executable );
}
}
private static class NestedTypeArgumentLocation implements TypeArgumentLocation {
private final TypeArgumentLocation parentLocation;
private final TypeVariable<?> typeParameter;
private final Type typeOfAnnotatedElement;
private NestedTypeArgumentLocation(TypeArgumentLocation parentLocation, TypeVariable<?> typeParameter, Type typeOfAnnotatedElement) {
this.parentLocation = parentLocation;
this.typeParameter = typeParameter;
this.typeOfAnnotatedElement = typeOfAnnotatedElement;
}
@Override
public ConstraintLocation toConstraintLocation() {
return ConstraintLocation.forTypeArgument( parentLocation.toConstraintLocation(), typeParameter, typeOfAnnotatedElement );
}
}
}