/
ValidatorImpl.java
938 lines (814 loc) · 34.6 KB
/
ValidatorImpl.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
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat, Inc. and/or its affiliates, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* 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 org.hibernate.validator.engine;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.validation.ConstraintValidatorFactory;
import javax.validation.ConstraintViolation;
import javax.validation.MessageInterpolator;
import javax.validation.Path;
import javax.validation.TraversableResolver;
import javax.validation.ValidationException;
import javax.validation.Validator;
import javax.validation.groups.Default;
import javax.validation.metadata.BeanDescriptor;
import com.googlecode.jtype.TypeUtils;
import org.hibernate.validator.MethodConstraintViolation;
import org.hibernate.validator.MethodValidator;
import org.hibernate.validator.engine.groups.Group;
import org.hibernate.validator.engine.groups.GroupChain;
import org.hibernate.validator.engine.groups.GroupChainGenerator;
import org.hibernate.validator.engine.resolver.SingleThreadCachedTraversableResolver;
import org.hibernate.validator.metadata.BeanMetaData;
import org.hibernate.validator.metadata.BeanMetaDataCache;
import org.hibernate.validator.metadata.BeanMetaDataImpl;
import org.hibernate.validator.metadata.ConstraintHelper;
import org.hibernate.validator.metadata.MetaConstraint;
import org.hibernate.validator.metadata.MethodMetaData;
import org.hibernate.validator.metadata.ParameterMetaData;
import org.hibernate.validator.metadata.site.BeanConstraintSite;
import org.hibernate.validator.util.ReflectionHelper;
/**
* The main Bean Validation class. This is the core processing class of Hibernate Validator.
*
* @author Emmanuel Bernard
* @author Hardy Ferentschik
* @author Gunnar Morling
*/
public class ValidatorImpl implements Validator, MethodValidator {
/**
* The default group array used in case any of the validate methods is called without a group.
*/
private static final Class<?>[] DEFAULT_GROUP_ARRAY = new Class<?>[] { Default.class };
/**
* Used to resolve the group execution order for a validate call.
*/
private final transient GroupChainGenerator groupChainGenerator;
private final ConstraintValidatorFactory constraintValidatorFactory;
/**
* {@link MessageInterpolator} as passed to the constructor of this instance.
*/
private final MessageInterpolator messageInterpolator;
/**
* {@link TraversableResolver} as passed to the constructor of this instance.
* Never use it directly, always use {@link #getCachingTraversableResolver()} to retrieved the single threaded caching wrapper.
*/
private final TraversableResolver traversableResolver;
/**
* Passed at creation time of this validator instance.
*/
private final ConstraintHelper constraintHelper;
/**
* Used to get access to the bean meta data. Used to avoid to parsing the constraint configuration for each call
* of a given entity.
*/
private final BeanMetaDataCache beanMetaDataCache;
public ValidatorImpl(ConstraintValidatorFactory constraintValidatorFactory, MessageInterpolator messageInterpolator, TraversableResolver traversableResolver, ConstraintHelper constraintHelper, BeanMetaDataCache beanMetaDataCache) {
this.constraintValidatorFactory = constraintValidatorFactory;
this.messageInterpolator = messageInterpolator;
this.traversableResolver = traversableResolver;
this.constraintHelper = constraintHelper;
this.beanMetaDataCache = beanMetaDataCache;
groupChainGenerator = new GroupChainGenerator();
}
public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) {
if ( object == null ) {
throw new IllegalArgumentException( "Validation of a null object" );
}
GroupChain groupChain = determineGroupExecutionOrder( groups );
ValidationContext<T> validationContext = ValidationContext.getContextForValidate(
object, messageInterpolator, constraintValidatorFactory, getCachingTraversableResolver()
);
ValueContext<?, T> valueContext = ValueContext.getLocalExecutionContext( object, PathImpl.createRootPath() );
List<? extends ConstraintViolation<T>> list = validateInContext( valueContext, validationContext, groupChain );
return new HashSet<ConstraintViolation<T>>( list );
}
public final <T> Set<ConstraintViolation<T>> validateProperty(T object, String propertyName, Class<?>... groups) {
if ( object == null ) {
throw new IllegalArgumentException( "Validated object cannot be null." );
}
sanityCheckPropertyPath( propertyName );
GroupChain groupChain = determineGroupExecutionOrder( groups );
List<ConstraintViolation<T>> failingConstraintViolations = new ArrayList<ConstraintViolation<T>>();
validateProperty(
object, PathImpl.createPathFromString( propertyName ), failingConstraintViolations, groupChain
);
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
}
public final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) {
if ( beanType == null ) {
throw new IllegalArgumentException( "The bean type cannot be null." );
}
sanityCheckPropertyPath( propertyName );
GroupChain groupChain = determineGroupExecutionOrder( groups );
List<ConstraintViolation<T>> failingConstraintViolations = new ArrayList<ConstraintViolation<T>>();
validateValue(
beanType, value, PathImpl.createPathFromString( propertyName ), failingConstraintViolations, groupChain
);
return new HashSet<ConstraintViolation<T>>( failingConstraintViolations );
}
public final <T> Set<MethodConstraintViolation<T>> validateParameter(T object, Method method, Object parameterValue, int parameterIndex, Class<?>... groups) {
if ( method == null ) {
throw new IllegalArgumentException( "The method cannot be null." );
}
GroupChain groupChain = determineGroupExecutionOrder( groups );
return validateParameter( object, method, parameterIndex, parameterValue, groupChain );
}
public final BeanDescriptor getConstraintsForClass(Class<?> clazz) {
return getBeanMetaData( clazz ).getBeanDescriptor();
}
public final <T> T unwrap(Class<T> type) {
if ( type.isAssignableFrom( getClass() ) ) {
return type.cast( this );
}
throw new ValidationException( "Type " + type + " not supported" );
}
private void sanityCheckPropertyPath(String propertyName) {
if ( propertyName == null || propertyName.length() == 0 ) {
throw new IllegalArgumentException( "Invalid property path." );
}
}
private GroupChain determineGroupExecutionOrder(Class<?>[] groups) {
if ( groups == null ) {
throw new IllegalArgumentException( "null passed as group name" );
}
Class<?>[] tmpGroups = groups;
// if no groups is specified use the default
if ( tmpGroups.length == 0 ) {
tmpGroups = DEFAULT_GROUP_ARRAY;
}
return groupChainGenerator.getGroupChainFor( Arrays.asList( tmpGroups ) );
}
/**
* Validates the given object using the available context information.
*
* @param valueContext the current validation context
* @param context the global validation context
* @param groupChain Contains the information which and in which order groups have to be executed
* @param <T> The root bean type
* @param <V> The type of the current object on the validation stack
*
* @return List of constraint violations or the empty set if there were no violations.
*/
private <T, U, V> List<? extends ConstraintViolation<T>> validateInContext(ValueContext<U, V> valueContext, ValidationContext<T> context, GroupChain groupChain) {
if ( valueContext.getCurrentBean() == null ) {
return Collections.emptyList();
}
BeanMetaData<U> beanMetaData = getBeanMetaData( valueContext.getCurrentBeanType() );
if ( beanMetaData.defaultGroupSequenceIsRedefined() ) {
groupChain.assertDefaultGroupSequenceIsExpandable( beanMetaData.getDefaultGroupSequence() );
}
// process first single groups. For these we can optimise object traversal by first running all validations on the current bean
// before traversing the object.
Iterator<Group> groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
valueContext.setCurrentGroup( group.getGroup() );
validateConstraintsForCurrentGroup( context, valueContext );
}
groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
valueContext.setCurrentGroup( group.getGroup() );
validateCascadedConstraints( context, valueContext );
}
// now we process sequences. For sequences I have to traverse the object graph since I have to stop processing when an error occurs.
Iterator<List<Group>> sequenceIterator = groupChain.getSequenceIterator();
while ( sequenceIterator.hasNext() ) {
List<Group> sequence = sequenceIterator.next();
for ( Group group : sequence ) {
int numberOfViolations = context.getFailingConstraints().size();
valueContext.setCurrentGroup( group.getGroup() );
validateConstraintsForCurrentGroup( context, valueContext );
validateCascadedConstraints( context, valueContext );
if ( context.getFailingConstraints().size() > numberOfViolations ) {
break;
}
}
}
return context.getFailingConstraints();
}
private <T, U, V> void validateConstraintsForCurrentGroup(ValidationContext<T> validationContext, ValueContext<U, V> valueContext) {
BeanMetaData<U> beanMetaData = getBeanMetaData( valueContext.getCurrentBeanType() );
boolean validatingDefault = valueContext.validatingDefault();
boolean validatedBeanRedefinesDefault = beanMetaData.defaultGroupSequenceIsRedefined();
// if we are not validating the default group there is nothing special to consider
if ( !validatingDefault ) {
validateConstraintsForNonDefaultGroup( validationContext, valueContext );
return;
}
// if we are validating the default group we have to distinguish between the case where the main entity type redefines the default group and where not
if ( validatedBeanRedefinesDefault ) {
validateConstraintsForRedefinedDefaultGroupOnMainEntity( validationContext, valueContext, beanMetaData );
}
else {
validateConstraintsForRedefinedDefaultGroup( validationContext, valueContext, beanMetaData );
}
}
private <T, U, V> void validateConstraintsForRedefinedDefaultGroup(ValidationContext<T> validationContext, ValueContext<U, V> valueContext, BeanMetaData<U> beanMetaData) {
for ( Map.Entry<Class<?>, List<MetaConstraint<U, ? extends Annotation>>> entry : beanMetaData.getMetaConstraintsAsMap()
.entrySet() ) {
Class<?> hostingBeanClass = entry.getKey();
List<MetaConstraint<U, ? extends Annotation>> constraints = entry.getValue();
List<Class<?>> defaultGroupSequence = getBeanMetaData( hostingBeanClass ).getDefaultGroupSequence();
PathImpl currentPath = valueContext.getPropertyPath();
for ( Class<?> defaultSequenceMember : defaultGroupSequence ) {
valueContext.setCurrentGroup( defaultSequenceMember );
boolean validationSuccessful = true;
for ( MetaConstraint<U, ? extends Annotation> metaConstraint : constraints ) {
boolean tmp = validateConstraint(
validationContext, valueContext, metaConstraint
);
validationSuccessful = validationSuccessful && tmp;
// reset the path
valueContext.setPropertyPath( currentPath );
}
if ( !validationSuccessful ) {
break;
}
}
validationContext.markProcessed(
valueContext.getCurrentBean(),
valueContext.getCurrentGroup(),
valueContext.getPropertyPath()
);
}
}
private <T, U, V> void validateConstraintsForRedefinedDefaultGroupOnMainEntity(ValidationContext<T> validationContext, ValueContext<U, V> valueContext, BeanMetaData<U> beanMetaData) {
List<Class<?>> defaultGroupSequence = beanMetaData.getDefaultGroupSequence();
PathImpl currentPath = valueContext.getPropertyPath();
for ( Class<?> defaultSequenceMember : defaultGroupSequence ) {
valueContext.setCurrentGroup( defaultSequenceMember );
boolean validationSuccessful = true;
for ( MetaConstraint<U, ? extends Annotation> metaConstraint : beanMetaData.getMetaConstraintsAsList() ) {
boolean tmp = validateConstraint( validationContext, valueContext, metaConstraint );
validationSuccessful = validationSuccessful && tmp;
// reset the path
valueContext.setPropertyPath( currentPath );
}
if ( !validationSuccessful ) {
break;
}
}
validationContext.markProcessed(
valueContext.getCurrentBean(),
valueContext.getCurrentGroup(),
valueContext.getPropertyPath()
);
}
private <T, U, V> void validateConstraintsForNonDefaultGroup(ValidationContext<T> validationContext, ValueContext<U, V> valueContext) {
BeanMetaData<U> beanMetaData = getBeanMetaData( valueContext.getCurrentBeanType() );
PathImpl currentPath = valueContext.getPropertyPath();
for ( MetaConstraint<U, ? extends Annotation> metaConstraint : beanMetaData.getMetaConstraintsAsList() ) {
validateConstraint( validationContext, valueContext, metaConstraint );
// reset the path to the state before this call
valueContext.setPropertyPath( currentPath );
}
validationContext.markProcessed(
valueContext.getCurrentBean(),
valueContext.getCurrentGroup(),
valueContext.getPropertyPath()
);
}
private <T, U, V> boolean validateConstraint(ValidationContext<T> validationContext, ValueContext<U, V> valueContext, MetaConstraint<U, ?> metaConstraint) {
boolean validationSuccessful = true;
if ( metaConstraint.getElementType() != ElementType.TYPE ) {
valueContext.appendNode( ( (BeanConstraintSite<?>) metaConstraint.getSite() ).getPropertyName() );
}
if ( isValidationRequired( validationContext, valueContext, metaConstraint ) ) {
Object valueToValidate = metaConstraint.getValue( valueContext.getCurrentBean() );
valueContext.setCurrentValidatedValue( (V) valueToValidate );
validationSuccessful = metaConstraint.validateConstraint( validationContext, valueContext );
}
return validationSuccessful;
}
/**
* Validates all cascaded constraints for the given bean using the current group set in the execution context.
* This method must always be called after validateConstraints for the same context.
*
* @param validationContext The execution context
* @param valueContext Collected information for single validation
*/
private <T, U, V> void validateCascadedConstraints(ValidationContext<T> validationContext, ValueContext<U, V> valueContext) {
List<Member> cascadedMembers = getBeanMetaData( valueContext.getCurrentBeanType() ).getCascadedMembers();
PathImpl currentPath = valueContext.getPropertyPath();
for ( Member member : cascadedMembers ) {
Type type = ReflectionHelper.typeOf( member );
String newNode = ReflectionHelper.getPropertyName( member );
valueContext.appendNode( newNode );
if ( isCascadeRequired( validationContext, valueContext, member ) ) {
Object value = ReflectionHelper.getValue( member, valueContext.getCurrentBean() );
if ( value != null ) {
Iterator<?> iter = createIteratorForCascadedValue( type, value, valueContext );
boolean isIndexable = isIndexable( type );
validateCascadedConstraint(
validationContext,
iter,
isIndexable,
valueContext
);
}
}
// reset the path
valueContext.setPropertyPath( currentPath );
}
}
/**
* Called when processing cascaded constraints. This methods inspects the type of the cascaded constraints and in case
* of a list or array creates an iterator in order to validate each element.
*
* @param type the type of the cascaded field or property.
* @param value the actual value.
*
* @return An iterator over the value of a cascaded property.
*/
private Iterator<?> createIteratorForCascadedValue(Type type, Object value, ValueContext valueContext) {
Iterator<?> iter;
if ( ReflectionHelper.isIterable( type ) ) {
iter = ( (Iterable<?>) value ).iterator();
valueContext.markCurrentPropertyAsIterable();
}
else if ( ReflectionHelper.isMap( type ) ) {
Map<?, ?> map = (Map<?, ?>) value;
iter = map.entrySet().iterator();
valueContext.markCurrentPropertyAsIterable();
}
else if ( TypeUtils.isArray( type ) ) {
List<?> arrayList = Arrays.asList( (Object[]) value );
iter = arrayList.iterator();
valueContext.markCurrentPropertyAsIterable();
}
else {
List<Object> list = new ArrayList<Object>();
list.add( value );
iter = list.iterator();
}
return iter;
}
/**
* Called when processing cascaded constraints. This methods inspects the type of the cascaded constraints and in case
* of a list or array creates an iterator in order to validate each element.
*
* @param type the type of the cascaded field or property.
*
* @return An iterator over the value of a cascaded property.
*/
private boolean isIndexable(Type type) {
boolean isIndexable = false;
if ( ReflectionHelper.isList( type ) ) {
isIndexable = true;
}
else if ( ReflectionHelper.isMap( type ) ) {
isIndexable = true;
}
else if ( TypeUtils.isArray( type ) ) {
isIndexable = true;
}
return isIndexable;
}
private <T> void validateCascadedConstraint(ValidationContext<T> context, Iterator<?> iter, boolean isIndexable, ValueContext valueContext) {
Object value;
Object mapKey;
int i = 0;
while ( iter.hasNext() ) {
value = iter.next();
if ( value instanceof Map.Entry ) {
mapKey = ( (Map.Entry) value ).getKey();
valueContext.setKey( mapKey );
value = ( (Map.Entry) value ).getValue();
}
else if ( isIndexable ) {
valueContext.setIndex( i );
}
if ( !context.isAlreadyValidated(
value, valueContext.getCurrentGroup(), valueContext.getPropertyPath()
) ) {
GroupChain groupChain = groupChainGenerator.getGroupChainFor(
Arrays.<Class<?>>asList( valueContext.getCurrentGroup() )
);
ValueContext<?, T> newValueContext;
if ( value != null ) {
newValueContext = ValueContext.getLocalExecutionContext( value, valueContext.getPropertyPath() );
}
else {
newValueContext = ValueContext.getLocalExecutionContext(
valueContext.getCurrentBeanType(), valueContext.getPropertyPath()
);
}
validateInContext( newValueContext, context, groupChain );
}
i++;
}
}
private <T> void validateProperty(T object, PathImpl propertyPath, List<ConstraintViolation<T>> failingConstraintViolations, GroupChain groupChain) {
@SuppressWarnings("unchecked")
final Class<T> beanType = (Class<T>) object.getClass();
Set<MetaConstraint<T, ?>> metaConstraints = new HashSet<MetaConstraint<T, ?>>();
Iterator<Path.Node> propertyIter = propertyPath.iterator();
Object hostingBeanInstance = collectMetaConstraintsForPath(
beanType, object, propertyIter, metaConstraints
);
if ( hostingBeanInstance == null ) {
throw new IllegalArgumentException( "Invalid property path." );
}
if ( metaConstraints.size() == 0 ) {
return;
}
//this method is at the root of validateProperty calls, share the same cachedTR
TraversableResolver cachedResolver = getCachingTraversableResolver();
Iterator<Group> groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
validatePropertyForGroup(
object,
propertyPath,
failingConstraintViolations,
metaConstraints,
hostingBeanInstance,
group,
cachedResolver
);
}
Iterator<List<Group>> sequenceIterator = groupChain.getSequenceIterator();
while ( sequenceIterator.hasNext() ) {
List<Group> sequence = sequenceIterator.next();
int numberOfConstraintViolationsBefore = failingConstraintViolations.size();
for ( Group group : sequence ) {
validatePropertyForGroup(
object,
propertyPath,
failingConstraintViolations,
metaConstraints,
hostingBeanInstance,
group,
cachedResolver
);
if ( failingConstraintViolations.size() > numberOfConstraintViolationsBefore ) {
break;
}
}
}
}
private <T, U, V> void validatePropertyForGroup(
T object,
PathImpl path,
List<ConstraintViolation<T>> failingConstraintViolations,
Set<MetaConstraint<T, ?>> metaConstraints,
U hostingBeanInstance,
Group group,
TraversableResolver cachedTraversableResolver) {
int numberOfConstraintViolationsBefore = failingConstraintViolations.size();
//TODO GM: is that right?
BeanMetaData<T> beanMetaData = getBeanMetaData( (Class<T>) object.getClass() );
List<Class<?>> groupList;
if ( group.isDefaultGroup() ) {
groupList = beanMetaData.getDefaultGroupSequence();
}
else {
groupList = new ArrayList<Class<?>>();
groupList.add( group.getGroup() );
}
for ( Class<?> groupClass : groupList ) {
for ( MetaConstraint<T, ?> metaConstraint : metaConstraints ) {
ValidationContext<T> context = ValidationContext.getContextForValidateProperty(
object,
messageInterpolator,
constraintValidatorFactory,
cachedTraversableResolver
);
ValueContext<U, V> valueContext = ValueContext.getLocalExecutionContext(
hostingBeanInstance, path
);
valueContext.setCurrentGroup( groupClass );
if ( isValidationRequired( context, valueContext, metaConstraint ) ) {
Object valueToValidate = metaConstraint.getValue( valueContext.getCurrentBean() );
valueContext.setCurrentValidatedValue( (V) valueToValidate );
metaConstraint.validateConstraint( context, valueContext );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
}
if ( failingConstraintViolations.size() > numberOfConstraintViolationsBefore ) {
break;
}
}
}
private <T> void validateValue(Class<T> beanType, Object value, PathImpl propertyPath, List<ConstraintViolation<T>> failingConstraintViolations, GroupChain groupChain) {
Set<MetaConstraint<T, ?>> metaConstraints = new HashSet<MetaConstraint<T, ?>>();
collectMetaConstraintsForPath( beanType, null, propertyPath.iterator(), metaConstraints );
if ( metaConstraints.size() == 0 ) {
return;
}
//root of validateValue calls, share the same cached TraversableResolver
TraversableResolver cachedTraversableResolver = getCachingTraversableResolver();
// process groups
Iterator<Group> groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
validateValueForGroup(
beanType,
value,
propertyPath,
failingConstraintViolations,
metaConstraints,
group,
cachedTraversableResolver
);
}
// process sequences
Iterator<List<Group>> sequenceIterator = groupChain.getSequenceIterator();
while ( sequenceIterator.hasNext() ) {
List<Group> sequence = sequenceIterator.next();
int numberOfConstraintViolations = failingConstraintViolations.size();
for ( Group group : sequence ) {
validateValueForGroup(
beanType,
value,
propertyPath,
failingConstraintViolations,
metaConstraints,
group,
cachedTraversableResolver
);
if ( failingConstraintViolations.size() > numberOfConstraintViolations ) {
break;
}
}
}
}
private <U, V> void validateValueForGroup(
Class<U> beanType,
V value,
PathImpl path,
List<ConstraintViolation<U>> failingConstraintViolations,
Set<MetaConstraint<U, ?>> metaConstraints,
Group group,
TraversableResolver cachedTraversableResolver) {
int numberOfConstraintViolations = failingConstraintViolations.size();
//TODO GM: is that right?
BeanMetaData<U> beanMetaData = getBeanMetaData( beanType );
List<Class<?>> groupList;
if ( group.isDefaultGroup() ) {
groupList = beanMetaData.getDefaultGroupSequence();
}
else {
groupList = new ArrayList<Class<?>>();
groupList.add( group.getGroup() );
}
for ( Class<?> groupClass : groupList ) {
for ( MetaConstraint<U, ?> metaConstraint : metaConstraints ) {
ValidationContext<U> context = ValidationContext.getContextForValidateValue(
beanType, messageInterpolator, constraintValidatorFactory, cachedTraversableResolver
);
ValueContext<U, V> valueContext = ValueContext.getLocalExecutionContext( beanType, path );
valueContext.setCurrentGroup( groupClass );
valueContext.setCurrentValidatedValue( value );
if ( isValidationRequired( context, valueContext, metaConstraint ) ) {
metaConstraint.validateConstraint( context, valueContext );
failingConstraintViolations.addAll( context.getFailingConstraints() );
}
}
if ( failingConstraintViolations.size() > numberOfConstraintViolations ) {
break;
}
}
}
private <V, T> Set<MethodConstraintViolation<T>> validateParameter(T bean, Method method, int parameterIndex, V value, GroupChain groupChain) {
Set<MethodConstraintViolation<T>> constraintViolations = new HashSet<MethodConstraintViolation<T>>();
BeanMetaData<?> beanMetaData = getBeanMetaData( method.getDeclaringClass() );
if ( beanMetaData.defaultGroupSequenceIsRedefined() ) {
groupChain.assertDefaultGroupSequenceIsExpandable( beanMetaData.getDefaultGroupSequence() );
}
MethodValidationContext<T> context = ValidationContext.getContextForValidateParameter(
method, parameterIndex, bean, messageInterpolator, constraintValidatorFactory, getCachingTraversableResolver()
);
ValueContext<?, V> valueContext = ValueContext.getLocalExecutionContext( null, PathImpl.createRootPath() );
valueContext.setCurrentValidatedValue( value );
// process first single groups. For these we can optimise object traversal by first running all validations on the current bean
// before traversing the object.
Iterator<Group> groupIterator = groupChain.getGroupIterator();
// validate constraints at the parameters themselves
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
valueContext.setCurrentGroup( group.getGroup() );
validateParameterForGroup( context, valueContext );
}
constraintViolations.addAll( context.getFailingConstraints() );
// validate parameter beans annotated with @Valid
if ( isCascadeRequired( method, parameterIndex ) && value != null ) {
//TODO GM: is it possible to use the existing context here?
context = ValidationContext.getContextForValidateParameter(
method,
parameterIndex,
bean,
messageInterpolator,
constraintValidatorFactory,
getCachingTraversableResolver()
);
valueContext = ValueContext.getLocalExecutionContext( value, PathImpl.createRootPath() );
groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
valueContext.setCurrentGroup( group.getGroup() );
validateConstraintsForCurrentGroup( context, valueContext );
}
// validate cascaded constraints of parameter bean
groupIterator = groupChain.getGroupIterator();
while ( groupIterator.hasNext() ) {
Group group = groupIterator.next();
valueContext.setCurrentGroup( group.getGroup() );
validateCascadedConstraints( context, valueContext );
}
constraintViolations.addAll( context.getFailingConstraints() );
}
//TODO GM: evaluate group sequences
return constraintViolations;
}
private <T, U, V> Set<MethodConstraintViolation<T>> validateParameterForGroup(MethodValidationContext<T> validationContext, ValueContext<U, V> valueContext) {
Set<MethodConstraintViolation<T>> constraintViolations = new HashSet<MethodConstraintViolation<T>>();
BeanMetaData<?> beanMetaData = getBeanMetaData( validationContext.getMethod().getDeclaringClass() );
Map<Class<?>, MethodMetaData> methodMetaData = beanMetaData.getMetaDataForMethod( validationContext.getMethod() );
for ( Entry<Class<?>, MethodMetaData> constraintsOfOneClass : methodMetaData.entrySet() ) {
ParameterMetaData constraintsOfOneParameter = constraintsOfOneClass.getValue()
.getParameterMetaData( validationContext.getParameterIndex() );
for ( MetaConstraint<?, ? extends Annotation> metaConstraint : constraintsOfOneParameter ) {
if ( !metaConstraint.getGroupList().contains( valueContext.getCurrentGroup() ) ) {
continue;
}
metaConstraint.validateConstraint( validationContext, valueContext );
constraintViolations.addAll( validationContext.getFailingConstraints() );
}
}
return constraintViolations;
}
/**
* Collects all <code>MetaConstraint</code>s which match the given path relative to the specified root class.
* <p>
* This method is called recursively.
* </p>
*
* @param clazz the class type to check for constraints.
* @param value While resolving the property path this instance points to the current object. Might be <code>null</code>.
* @param propertyIter an instance of <code>PropertyIterator</code> in order to iterate the items of the original property path.
* @param metaConstraints Set of <code>MetaConstraint</code>s to collect all matching constraints.
*
* @return Returns the bean hosting the constraints which match the specified property path.
*/
private <T> Object collectMetaConstraintsForPath(Class<T> clazz, Object value, Iterator<Path.Node> propertyIter, Set<MetaConstraint<T, ?>> metaConstraints) {
Path.Node elem = propertyIter.next();
Object newValue = value;
final BeanMetaData<T> metaData = getBeanMetaData( clazz );
//use precomputed method list as ReflectionHelper#containsMember is slow
if ( !metaData.isPropertyPresent( elem.getName() ) ) {
throw new IllegalArgumentException(
"Invalid property path. There is no property " + elem.getName() + " in entity " + metaData.getBeanClass()
.getName()
);
}
if ( !propertyIter.hasNext() ) {
List<MetaConstraint<T, ? extends Annotation>> metaConstraintList = metaData.getMetaConstraintsAsList();
for ( MetaConstraint<T, ?> metaConstraint : metaConstraintList ) {
if ( elem.getName() != null && elem.getName()
.equals( ( (BeanConstraintSite<?>) metaConstraint.getSite() ).getPropertyName() ) ) {
metaConstraints.add( metaConstraint );
}
}
}
else {
List<Member> cascadedMembers = metaData.getCascadedMembers();
for ( Member m : cascadedMembers ) {
if ( ReflectionHelper.getPropertyName( m ).equals( elem.getName() ) ) {
Type type = ReflectionHelper.typeOf( m );
newValue = newValue == null ? null : ReflectionHelper.getValue( m, newValue );
if ( elem.isInIterable() ) {
if ( newValue != null && elem.getIndex() != null ) {
newValue = ReflectionHelper.getIndexedValue( newValue, elem.getIndex() );
}
else if ( newValue != null && elem.getKey() != null ) {
newValue = ReflectionHelper.getMappedValue( newValue, elem.getKey() );
}
else if ( newValue != null ) {
throw new IllegalArgumentException( "Property path must provide index or map key" );
}
type = ReflectionHelper.getIndexedType( type );
}
@SuppressWarnings("unchecked")
Class<T> valueClass = (Class<T>) ( newValue == null ? type : newValue.getClass() );
return collectMetaConstraintsForPath(
valueClass,
newValue,
propertyIter,
metaConstraints
);
}
}
}
return newValue;
}
private <U> BeanMetaData<U> getBeanMetaData(Class<U> beanClass) {
BeanMetaDataImpl<U> beanMetaData = beanMetaDataCache.getBeanMetaData( beanClass );
if ( beanMetaData == null ) {
beanMetaData = new BeanMetaDataImpl<U>( beanClass, constraintHelper, beanMetaDataCache );
beanMetaDataCache.addBeanMetaData( beanClass, beanMetaData );
}
return beanMetaData;
}
/**
* Must be called and stored for the duration of the stack call
* A new instance is returned each time
*
* @return The resolver for the duration of a full validation.
*/
private TraversableResolver getCachingTraversableResolver() {
return new SingleThreadCachedTraversableResolver( traversableResolver );
}
private boolean isValidationRequired(ValidationContext validationContext, ValueContext valueContext, MetaConstraint metaConstraint) {
if ( !metaConstraint.getGroupList().contains( valueContext.getCurrentGroup() ) ) {
return false;
}
boolean isReachable;
PathImpl path = valueContext.getPropertyPath();
Path pathToObject = path.getPathWithoutLeafNode();
try {
isReachable = validationContext.getTraversableResolver().isReachable(
valueContext.getCurrentBean(),
path.getLeafNode(),
validationContext.getRootBeanClass(),
pathToObject,
metaConstraint.getElementType()
);
}
catch ( RuntimeException e ) {
throw new ValidationException( "Call to TraversableResolver.isReachable() threw an exception", e );
}
return isReachable;
}
private boolean isCascadeRequired(ValidationContext validationContext, ValueContext valueContext, Member member) {
final ElementType type = member instanceof Field ? ElementType.FIELD : ElementType.METHOD;
boolean isReachable;
boolean isCascadable;
PathImpl path = valueContext.getPropertyPath();
Path pathToObject = path.getPathWithoutLeafNode();
try {
isReachable = validationContext.getTraversableResolver().isReachable(
valueContext.getCurrentBean(),
path.getLeafNode(),
validationContext.getRootBeanClass(),
pathToObject,
type
);
}
catch ( RuntimeException e ) {
throw new ValidationException( "Call to TraversableResolver.isReachable() threw an exception", e );
}
try {
isCascadable = validationContext.getTraversableResolver().isCascadable(
valueContext.getCurrentBean(),
path.getLeafNode(),
validationContext.getRootBeanClass(),
pathToObject,
type
);
}
catch ( RuntimeException e ) {
throw new ValidationException( "Call to TraversableResolver.isCascadable() threw an exception", e );
}
return isReachable && isCascadable;
}
private boolean isCascadeRequired(Method method, int parameterIndex) {
BeanMetaData<?> beanMetaData = getBeanMetaData( method.getDeclaringClass() );
Map<Class<?>, MethodMetaData> methodMetaData = beanMetaData.getMetaDataForMethod( method );
for ( MethodMetaData oneMethodMetaData : methodMetaData.values() ) {
if ( oneMethodMetaData.getParameterMetaData( parameterIndex ).isCascading() ) {
return true;
}
}
return false;
}
}