Debian Codegraph @

documentation/src/main/asciidoc/ch09.asciidoc

raw
1 [[validator-metadata-api]]
2 == Using constraint metadata
3
4 The Bean Validation specification provides not only a validation engine, but also an API for
5 retrieving constraint metadata in a uniform way, no matter whether the constraints are declared
6 using annotations or via XML mappings. Read this chapter to learn more about this API and its
7 possibilities. You can find all the metadata API types in the package `javax.validation.metadata`.
8
9 The examples presented in this chapter are based on the classes and constraint declarations shown in
10 <<metadata-example-car>>.
11
12 [[metadata-example-car]]
13 .Example classes
14 ====
15 [source, JAVA]
16 ----
17 package org.hibernate.validator.referenceguide.chapter07;
18
19 public class Person {
20
21 public interface Basic {
22 }
23
24 @NotNull
25 private String name;
26
27 //getters and setters ...
28 }
29 ----
30
31 [source, JAVA]
32 ----
33 public interface Vehicle {
34
35 public interface Basic {
36 }
37
38 @NotNull(groups = Vehicle.Basic.class)
39 String getManufacturer();
40 }
41 ----
42
43 [source, JAVA]
44 ----
45 @ValidCar
46 public class Car implements Vehicle {
47
48 public interface SeverityInfo extends Payload {
49 }
50
51 private String manufacturer;
52
53 @NotNull
54 @Size(min = 2, max = 14)
55 private String licensePlate;
56
57 private Person driver;
58
59 private String modelName;
60
61 public Car() {
62 }
63
64 public Car(
65 @NotNull String manufacturer,
66 String licencePlate,
67 Person driver,
68 String modelName) {
69
70 this.manufacturer = manufacturer;
71 this.licensePlate = licencePlate;
72 this.driver = driver;
73 this.modelName = modelName;
74 }
75
76 public void driveAway(@Max(75) int speed) {
77 //...
78 }
79
80 @LuggageCountMatchesPassengerCount(
81 piecesOfLuggagePerPassenger = 2,
82 validationAppliesTo = ConstraintTarget.PARAMETERS,
83 payload = SeverityInfo.class,
84 message = "There must not be more than {piecesOfLuggagePerPassenger} pieces of " +
85 "luggage per passenger."
86 )
87 public void load(List<Person> passengers, List<PieceOfLuggage> luggage) {
88 //...
89 }
90
91 @Override
92 @Size(min = 3)
93 public String getManufacturer() {
94 return manufacturer;
95 }
96
97 public void setManufacturer(String manufacturer) {
98 this.manufacturer = manufacturer;
99 }
100
101 @Valid
102 @ConvertGroup(from = Default.class, to = Person.Basic.class)
103 public Person getDriver() {
104 return driver;
105 }
106
107 //further getters and setters...
108 }
109 ----
110 ====
111
112
113 === `BeanDescriptor`
114
115 The entry point into the metadata API is the method `Validator#getConstraintsForClass()`, which
116 returns an instance of the `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.
117 html?javax/validation/metadata/BeanDescriptor.html$$[BeanDescriptor]` interface. Using this
118 descriptor, you can obtain metadata for constraints declared directly on the bean itself (class- or
119 property-level), but also retrieve metadata descriptors representing single properties, methods and
120 constructors.
121
122 <<metadata-example-using-beandescriptor>> demonstrates how to retrieve a `BeanDescriptor` for the
123 `Car` class and how to use this descriptor in form of assertions.
124
125 [TIP]
126 ====
127 If a constraint declaration hosted by the requested class is invalid, a `ValidationException` is thrown.
128 ====
129
130 [[metadata-example-using-beandescriptor]]
131 .Using `BeanDescriptor`
132 ====
133 [source, JAVA]
134 ----
135 Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
136
137 BeanDescriptor carDescriptor = validator.getConstraintsForClass( Car.class );
138
139 assertTrue( carDescriptor.isBeanConstrained() );
140
141 //one class-level constraint
142 assertEquals( 1, carDescriptor.getConstraintDescriptors().size() );
143
144 //manufacturer, licensePlate, driver
145 assertEquals( 3, carDescriptor.getConstrainedProperties().size() );
146
147 //property has constraint
148 assertNotNull( carDescriptor.getConstraintsForProperty( "licensePlate" ) );
149
150 //property is marked with @Valid
151 assertNotNull( carDescriptor.getConstraintsForProperty( "driver" ) );
152
153 //constraints from getter method in interface and implementation class are returned
154 assertEquals(
155 2,
156 carDescriptor.getConstraintsForProperty( "manufacturer" )
157 .getConstraintDescriptors()
158 .size()
159 );
160
161 //property is not constrained
162 assertNull( carDescriptor.getConstraintsForProperty( "modelName" ) );
163
164 //driveAway(int), load(List<Person>, List<PieceOfLuggage>)
165 assertEquals( 2, carDescriptor.getConstrainedMethods( MethodType.NON_GETTER ).size() );
166
167 //driveAway(int), getManufacturer(), getDriver(), load(List<Person>, List<PieceOfLuggage>)
168 assertEquals(
169 4,
170 carDescriptor.getConstrainedMethods( MethodType.NON_GETTER, MethodType.GETTER )
171 .size()
172 );
173
174 //driveAway(int)
175 assertNotNull( carDescriptor.getConstraintsForMethod( "driveAway", int.class ) );
176
177 //getManufacturer()
178 assertNotNull( carDescriptor.getConstraintsForMethod( "getManufacturer" ) );
179
180 //setManufacturer() is not constrained
181 assertNull( carDescriptor.getConstraintsForMethod( "setManufacturer", String.class ) );
182
183 //Car(String, String, Person, String)
184 assertEquals( 1, carDescriptor.getConstrainedConstructors().size() );
185
186 //Car(String, String, Person, String)
187 assertNotNull(
188 carDescriptor.getConstraintsForConstructor(
189 String.class,
190 String.class,
191 Person.class,
192 String.class
193 )
194 );
195 ----
196 ====
197
198 You can determine whether the specified class hosts any class- or property-level constraints via
199 `isBeanConstrained()`. Method or constructor constraints are not considered by `isBeanConstrained()`.
200
201 The method `getConstraintDescriptors()` is common to all descriptors derived from `ElementDescriptor`
202 (see <<validator-metadata-api-elementdescriptor>>) and returns a set of descriptors representing the
203 constraints directly declared on the given element. In case of `BeanDescriptor`, the bean's class-
204 level constraints are returned. More details on `ConstraintDescriptor` can be found in
205 <<section-constraint-descriptor>>.
206
207 Via `getConstraintsForProperty()`, `getConstraintsForMethod()` and `getConstraintsForConstructor()` you
208 can obtain a descriptor representing one given property or executable element, identified by its
209 name and, in case of methods and constructors, parameter types. The different descriptor types
210 returned by these methods are described in the following sections.
211
212 Note that these methods consider constraints declared at super-types according to the rules for
213 constraint inheritance as described in <<section-constraint-inheritance>>. An example is the
214 descriptor for the `manufacturer` property, which provides access to all constraints defined on
215 `Vehicle#getManufacturer()` and the implementing method `Car#getManufacturer()`. `null` is returned in
216 case the specified element does not exist or is not constrained.
217
218 The methods `getConstrainedProperties()`, `getConstrainedMethods()` and `getConstrainedConstructors()`
219 return (potentially empty) sets with all constrained properties, methods and constructors,
220 respectively. An element is considered constrained, if it has at least one constraint or is marked
221 for cascaded validation. When invoking `getConstrainedMethods()`, you can specify the type of the
222 methods to be returned (getters, non-getters or both).
223
224 [[section-property-descriptor]]
225 === `PropertyDescriptor`
226
227 The interface
228 `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/PropertyDescriptor.html$$[PropertyDescriptor]` represents one given property of a
229 class. It is transparent whether constraints are declared on a field or a property getter, provided
230 the JavaBeans naming conventions are respected. <<metadata-example-using-propertydescriptor>> shows
231 how to use the `PropertyDescriptor` interface.
232
233 [[metadata-example-using-propertydescriptor]]
234 .Using `PropertyDescriptor`
235 ====
236 [source, JAVA]
237 ----
238 PropertyDescriptor licensePlateDescriptor = carDescriptor.getConstraintsForProperty(
239 "licensePlate"
240 );
241
242 //"licensePlate" has two constraints, is not marked with @Valid and defines no group conversions
243 assertEquals( "licensePlate", licensePlateDescriptor.getPropertyName() );
244 assertEquals( 2, licensePlateDescriptor.getConstraintDescriptors().size() );
245 assertTrue( licensePlateDescriptor.hasConstraints() );
246 assertFalse( licensePlateDescriptor.isCascaded() );
247 assertTrue( licensePlateDescriptor.getGroupConversions().isEmpty() );
248
249 PropertyDescriptor driverDescriptor = carDescriptor.getConstraintsForProperty( "driver" );
250
251 //"driver" has no constraints, is marked with @Valid and defines one group conversion
252 assertEquals( "driver", driverDescriptor.getPropertyName() );
253 assertTrue( driverDescriptor.getConstraintDescriptors().isEmpty() );
254 assertFalse( driverDescriptor.hasConstraints() );
255 assertTrue( driverDescriptor.isCascaded() );
256 assertEquals( 1, driverDescriptor.getGroupConversions().size() );
257 ----
258 ====
259
260 Using `getConstrainedDescriptors()`, you can retrieve a set of `ConstraintDescriptors` providing more
261 information on the individual constraints of a given property. The method `isCascaded()` returns
262 `true`, if the property is marked for cascaded validation (either using the `@Valid` annotation or via
263 XML), `false` otherwise. Any configured group conversions are returned by `getGroupConversions()`. See
264 <<section-group-conversion-descriptor>> for more details on `GroupConversionDescriptor`.
265
266 === `MethodDescriptor` and `ConstructorDescriptor`
267
268 Constrained methods and constructors are represented by the interfaces
269 `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/MethodDescriptor.html$$[MethodDescriptor]`
270 and `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/ConstructorDescriptor.html$$[ConstructorDescriptor]`, respectively.
271 <<metadata-example-using-methodandconstructordescriptor>> demonstrates how to work with these
272 descriptors.
273
274 [[metadata-example-using-methodandconstructordescriptor]]
275 .Using `MethodDescriptor` and `ConstructorDescriptor`
276 ====
277 [source, JAVA]
278 ----
279 //driveAway(int) has a constrained parameter and an unconstrained return value
280 MethodDescriptor driveAwayDescriptor = carDescriptor.getConstraintsForMethod(
281 "driveAway",
282 int.class
283 );
284 assertEquals( "driveAway", driveAwayDescriptor.getName() );
285 assertTrue( driveAwayDescriptor.hasConstrainedParameters() );
286 assertFalse( driveAwayDescriptor.hasConstrainedReturnValue() );
287
288 //always returns an empty set; constraints are retrievable by navigating to
289 //one of the sub-descriptors, e.g. for the return value
290 assertTrue( driveAwayDescriptor.getConstraintDescriptors().isEmpty() );
291
292 ParameterDescriptor speedDescriptor = driveAwayDescriptor.getParameterDescriptors()
293 .get( 0 );
294
295 //The "speed" parameter is located at index 0, has one constraint and is not cascaded
296 //nor does it define group conversions
297 assertEquals( "arg0", speedDescriptor.getName() );
298 assertEquals( 0, speedDescriptor.getIndex() );
299 assertEquals( 1, speedDescriptor.getConstraintDescriptors().size() );
300 assertFalse( speedDescriptor.isCascaded() );
301 assert speedDescriptor.getGroupConversions().isEmpty();
302
303 //getDriver() has no constrained parameters but its return value is marked for cascaded
304 //validation and declares one group conversion
305 MethodDescriptor getDriverDescriptor = carDescriptor.getConstraintsForMethod(
306 "getDriver"
307 );
308 assertFalse( getDriverDescriptor.hasConstrainedParameters() );
309 assertTrue( getDriverDescriptor.hasConstrainedReturnValue() );
310
311 ReturnValueDescriptor returnValueDescriptor = getDriverDescriptor.getReturnValueDescriptor();
312 assertTrue( returnValueDescriptor.getConstraintDescriptors().isEmpty() );
313 assertTrue( returnValueDescriptor.isCascaded() );
314 assertEquals( 1, returnValueDescriptor.getGroupConversions().size() );
315
316 //load(List<Person>, List<PieceOfLuggage>) has one cross-parameter constraint
317 MethodDescriptor loadDescriptor = carDescriptor.getConstraintsForMethod(
318 "load",
319 List.class,
320 List.class
321 );
322 assertTrue( loadDescriptor.hasConstrainedParameters() );
323 assertFalse( loadDescriptor.hasConstrainedReturnValue() );
324 assertEquals(
325 1,
326 loadDescriptor.getCrossParameterDescriptor().getConstraintDescriptors().size()
327 );
328
329 //Car(String, String, Person, String) has one constrained parameter
330 ConstructorDescriptor constructorDescriptor = carDescriptor.getConstraintsForConstructor(
331 String.class,
332 String.class,
333 Person.class,
334 String.class
335 );
336
337 assertEquals( "Car", constructorDescriptor.getName() );
338 assertFalse( constructorDescriptor.hasConstrainedReturnValue() );
339 assertTrue( constructorDescriptor.hasConstrainedParameters() );
340 assertEquals(
341 1,
342 constructorDescriptor.getParameterDescriptors()
343 .get( 0 )
344 .getConstraintDescriptors()
345 .size()
346 );
347 ----
348 ====
349
350 `getName()` returns the name of the given method or constructor. The methods
351 `hasConstrainedParameters()` and `hasConstrainedReturnValue()` can be used to perform a quick check
352 whether an executable element has any parameter constraints (either constraints on single parameters
353 or cross-parameter constraints) or return value constraints.
354
355 Note that any constraints are not directly exposed on `MethodDescriptor` and `ConstructorDescriptor`,
356 but rather on dedicated descriptors representing an executable's parameters, its return value and
357 its cross-parameter constraints. To get hold of one of these descriptors, invoke
358 `getParameterDescriptors()`, `getReturnValueDescriptor()` or `getCrossParameterDescriptor()`,
359 respectively.
360
361 These descriptors provide access to the element's constraints (`getConstraintDescriptors()`) and, in
362 case of parameters and return value, to its configuration for cascaded validation (`isValid()` and
363 `getGroupConversions()`). For parameters, you also can retrieve the index and the name, as returned by
364 the currently used parameter name provider (see <<section-parameter-name-provider>>) via `getName()`
365 and `getIndex()`.
366
367 [TIP]
368 ====
369 Getter methods following the JavaBeans naming conventions are considered as bean properties but also
370 as constrained methods.
371
372 That means you can retrieve the related metadata either by obtaining a `PropertyDescriptor` (e.g.
373 `BeanDescriptor.getConstraintsForProperty("foo")`) or by examining the return value descriptor of the
374 getter's `MethodDescriptor` (e.g.
375 `BeanDescriptor.getConstraintsForMethod("getFoo").getReturnValueDescriptor())`.
376 ====
377
378
379 [[validator-metadata-api-elementdescriptor]]
380 === `ElementDescriptor`
381
382 The `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/ElementDescriptor.html$$[ElementDiscriptor]`
383 interface is the common base class for the
384 individual descriptor types such as `BeanDescriptor`, `PropertyDescriptor` etc. Besides
385 `getConstraintDescriptors()` it provides some more methods common to all descriptors.
386
387 `hasConstraints()` allows for a quick check whether an element has any direct constraints (e.g. class-
388 level constraints in case of `BeanDescriptor`). `getElementClass()` returns the Java type of the element
389 represented by a given descriptor. More specifically, the method returns
390
391 * the object type when invoked on `BeanDescriptor`,
392 * the type of a property or parameter when invoked on `PropertyDescriptor` or `ParameterDescriptor`
393 respectively,
394 * `Object[].class` when invoked on `CrossParameterDescriptor`,
395 * the return type when invoked on `ConstructorDescriptor`, `MethodDescriptor` or `ReturnValueDescriptor`.
396 `void.class` will be returned for methods which don't have a return value.
397
398 <<metadata-example-using-elementdescriptor>> shows how these methods are used.
399
400 [[metadata-example-using-elementdescriptor]]
401 .Using `ElementDescriptor methods`
402 ====
403 [source, JAVA]
404 ----
405 PropertyDescriptor manufacturerDescriptor = carDescriptor.getConstraintsForProperty(
406 "manufacturer"
407 );
408
409 assertTrue( manufacturerDescriptor.hasConstraints() );
410 assertEquals( String.class, manufacturerDescriptor.getElementClass() );
411
412 CrossParameterDescriptor loadCrossParameterDescriptor = carDescriptor.getConstraintsForMethod(
413 "load",
414 List.class,
415 List.class
416 ).getCrossParameterDescriptor();
417
418 assertTrue( loadCrossParameterDescriptor.hasConstraints() );
419 assertEquals( Object[].class, loadCrossParameterDescriptor.getElementClass() );
420 ----
421 ====
422
423 Finally, `ElementDescriptor` offers access to the `ConstraintFinder` API which allows you to query for
424 constraint metadata in a fine grained way. <<example-constraint-finder>> shows how to retrieve a
425 `ConstraintFinder` instance via `findConstraints()` and use the API to query for constraint metadata.
426
427 [[example-constraint-finder]]
428 .Usage of `ConstraintFinder`
429 ====
430 [source, JAVA]
431 ----
432 PropertyDescriptor manufacturerDescriptor = carDescriptor.getConstraintsForProperty(
433 "manufacturer"
434 );
435
436 //"manufacturer" constraints are declared on the getter, not the field
437 assertTrue(
438 manufacturerDescriptor.findConstraints()
439 .declaredOn( ElementType.FIELD )
440 .getConstraintDescriptors()
441 .isEmpty()
442 );
443
444 //@NotNull on Vehicle#getManufacturer() is part of another group
445 assertEquals(
446 1,
447 manufacturerDescriptor.findConstraints()
448 .unorderedAndMatchingGroups( Default.class )
449 .getConstraintDescriptors()
450 .size()
451 );
452
453 //@Size on Car#getManufacturer()
454 assertEquals(
455 1,
456 manufacturerDescriptor.findConstraints()
457 .lookingAt( Scope.LOCAL_ELEMENT )
458 .getConstraintDescriptors()
459 .size()
460 );
461
462 //@Size on Car#getManufacturer() and @NotNull on Vehicle#getManufacturer()
463 assertEquals(
464 2,
465 manufacturerDescriptor.findConstraints()
466 .lookingAt( Scope.HIERARCHY )
467 .getConstraintDescriptors()
468 .size()
469 );
470
471 //Combining several filter options
472 assertEquals(
473 1,
474 manufacturerDescriptor.findConstraints()
475 .declaredOn( ElementType.METHOD )
476 .lookingAt( Scope.HIERARCHY )
477 .unorderedAndMatchingGroups( Vehicle.Basic.class )
478 .getConstraintDescriptors()
479 .size()
480 );
481 ----
482 ====
483
484 Via `declaredOn()` you can search for `ConstraintDescriptors` declared on certain element types. This is
485 useful to find property constraints declared on either fields or getter methods.
486
487 `unorderedAndMatchingGroups()` restricts the resulting constraints to those matching the given
488 validation group(s).
489
490 `lookingAt()` allows to distinguish between constraints directly specified on the element
491 (`Scope.LOCAL_ELEMENT`) or constraints belonging to the element but hosted anywhere in the class
492 hierarchy (`Scope.HIERARCHY`).
493
494 You can also combine the different options as shown in the last example.
495
496 [WARNING]
497 ====
498 Order is not respected by `unorderedAndMatchingGroups()`, but group inheritance and inheritance via
499 sequence are.
500 ====
501
502 [[section-group-conversion-descriptor]]
503 === `GroupConversionDescriptor`
504
505 All those descriptor types that represent elements which can be subject of cascaded validation
506 (i.e., `PropertyDescriptor`, `ParameterDescriptor` and `ReturnValueDescriptor`) provide access to the
507 element's group conversions via `getGroupConversions()`. The returned set contains a
508 `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/GroupConversionDescriptor.html$$[GroupConversionDescriptor]`
509 for each configured conversion, allowing to retrieve
510 source and target groups of the conversion. <<metadata-example-using-groupconversiondescriptor>>
511 shows an example.
512
513 [[metadata-example-using-groupconversiondescriptor]]
514 .Using `GroupConversionDescriptor`
515
516 ====
517 [source, JAVA]
518 ----
519 PropertyDescriptor driverDescriptor = carDescriptor.getConstraintsForProperty( "driver" );
520
521 Set<GroupConversionDescriptor> groupConversions = driverDescriptor.getGroupConversions();
522 assertEquals( 1, groupConversions.size() );
523
524 GroupConversionDescriptor groupConversionDescriptor = groupConversions.iterator()
525 .next();
526 assertEquals( Default.class, groupConversionDescriptor.getFrom() );
527 assertEquals( Person.Basic.class, groupConversionDescriptor.getTo() );
528 ----
529 ====
530
531 [[section-constraint-descriptor]]
532 === `ConstraintDescriptor`
533
534 Last but not least, the
535 `link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1/api/index.html?javax/validation/metadata/ConstraintDescriptor.html$$[ConstraintDescriptor]`
536 interface describes a
537 single constraint together with its composing constraints. Via an instance of this interface you get
538 access to the constraint annotation and its parameters.
539
540 <<metadata-example-using-constraintdescriptor>>
541 shows how to retrieve default constraint attributes (such as message template, groups etc.) as well
542 as custom constraint attributes (`piecesOfLuggagePerPassenger`) and other metadata such as the
543 constraint's annotation type and its validators from a `ConstraintDescriptor`.
544
545 [[metadata-example-using-constraintdescriptor]]
546 .Using `ConstraintDescriptor`
547 ====
548 [source, JAVA]
549 ----
550 //descriptor for the @LuggageCountMatchesPassengerCount constraint on the
551 //load(List<Person>, List<PieceOfLuggage>) method
552 ConstraintDescriptor<?> constraintDescriptor = carDescriptor.getConstraintsForMethod(
553 "load",
554 List.class,
555 List.class
556 ).getCrossParameterDescriptor().getConstraintDescriptors().iterator().next();
557
558 //constraint type
559 assertEquals(
560 LuggageCountMatchesPassengerCount.class,
561 constraintDescriptor.getAnnotation().annotationType()
562 );
563
564 //standard constraint attributes
565 assertEquals( SeverityInfo.class, constraintDescriptor.getPayload().iterator().next() );
566 assertEquals(
567 ConstraintTarget.PARAMETERS,
568 constraintDescriptor.getValidationAppliesTo()
569 );
570 assertEquals( Default.class, constraintDescriptor.getGroups().iterator().next() );
571 assertEquals(
572 "There must not be more than {piecesOfLuggagePerPassenger} pieces of luggage per " +
573 "passenger.",
574 constraintDescriptor.getMessageTemplate()
575 );
576
577 //custom constraint attribute
578 assertEquals(
579 2,
580 constraintDescriptor.getAttributes().get( "piecesOfLuggagePerPassenger" )
581 );
582
583 //no composing constraints
584 assertTrue( constraintDescriptor.getComposingConstraints().isEmpty() );
585
586 //validator class
587 assertEquals(
588 Arrays.<Class<?>>asList( LuggageCountMatchesPassengerCount.Validator.class ),
589 constraintDescriptor.getConstraintValidatorClasses()
590 );
591 ----
592 ====