| 1 |
[[chapter-method-constraints]] |
| 2 |
== Declaring and validating method constraints |
| 3 |
|
| 4 |
As of Bean Validation 1.1, constraints can not only be applied to JavaBeans and their properties, |
| 5 |
but also to the parameters and return values of the methods and constructors of any Java type. That |
| 6 |
way Bean Validation constraints can be used to specify |
| 7 |
|
| 8 |
* the preconditions that must be satisfied by the caller before a method or constructor may be |
| 9 |
invoked (by applying constraints to the parameters of an executable) |
| 10 |
* the postconditions that are guaranteed to the caller after a method or constructor invocation |
| 11 |
returns (by applying constraints to the return value of an executable) |
| 12 |
|
| 13 |
[NOTE] |
| 14 |
==== |
| 15 |
For the purpose of this reference guide, the term _method constraint_ refers to both, method and |
| 16 |
constructor constraints, if not stated otherwise. Occasionally, the term _executable_ is used when |
| 17 |
referring to methods and constructors. |
| 18 |
==== |
| 19 |
|
| 20 |
This approach has several advantages over traditional ways of checking the correctness of parameters |
| 21 |
and return values: |
| 22 |
|
| 23 |
* the checks don't have to be performed manually (e.g. by throwing `IllegalArgumentException` or |
| 24 |
similar), resulting in less code to write and maintain |
| 25 |
* an executable's pre- and postconditions don't have to be expressed again in its documentation, |
| 26 |
since the constraint annotations will automatically be included in the generated JavaDoc. This |
| 27 |
avoids redundancies and reduces the chance of inconsistencies between implementation and |
| 28 |
documentation |
| 29 |
|
| 30 |
[TIP] |
| 31 |
==== |
| 32 |
In order to make annotations show up in the JavaDoc of annotated elements, the annotation types |
| 33 |
themselves must be annotated with the meta annotation @Documented. This is the case for all built-in |
| 34 |
constraints and is considered a best practice for any custom constraints. |
| 35 |
==== |
| 36 |
|
| 37 |
In the remainder of this chapter you will learn how to declare parameter and return value |
| 38 |
constraints and how to validate them using the `ExecutableValidator` API. |
| 39 |
|
| 40 |
[[section-declaring-method-constraints]] |
| 41 |
=== Declaring method constraints |
| 42 |
|
| 43 |
==== Parameter constraints |
| 44 |
|
| 45 |
You specify the preconditions of a method or constructor by adding constraint annotations to its |
| 46 |
parameters as demonstrated in <<example-declaring-parameter-constraints>>. |
| 47 |
|
| 48 |
[[example-declaring-parameter-constraints]] |
| 49 |
.Declaring method and constructor parameter constraints |
| 50 |
==== |
| 51 |
[source, JAVA] |
| 52 |
---- |
| 53 |
package org.hibernate.validator.referenceguide.chapter03.parameter; |
| 54 |
|
| 55 |
public class RentalStation { |
| 56 |
|
| 57 |
public RentalStation(@NotNull String name) { |
| 58 |
//... |
| 59 |
} |
| 60 |
|
| 61 |
public void rentCar( |
| 62 |
@NotNull Customer customer, |
| 63 |
@NotNull @Future Date startDate, |
| 64 |
@Min(1) int durationInDays) { |
| 65 |
//... |
| 66 |
} |
| 67 |
} |
| 68 |
---- |
| 69 |
==== |
| 70 |
|
| 71 |
The following preconditions are declared here: |
| 72 |
|
| 73 |
* The `name` passed to the `RentalCar` constructor must not be `null` |
| 74 |
* When invoking the `rentCar()` method, the given `customer` must not be `null`, the rental's start |
| 75 |
date must not be `null` as well as be in the future and finally the rental duration must be at least |
| 76 |
one day |
| 77 |
|
| 78 |
Note that declaring method or constructor constraints itself does not automatically cause their |
| 79 |
validation upon invocation of the executable. Instead, the `ExecutableValidator` API (see |
| 80 |
<<section-validating-executable-constraints>>) must be used to perform the validation, which is |
| 81 |
often done using a method interception facility such as AOP, proxy objects etc. |
| 82 |
|
| 83 |
Constraints may only be applied to instance methods, i.e. declaring constraints on static methods is |
| 84 |
not supported. Depending on the interception facility you use for triggering method validation, |
| 85 |
additional restrictions may apply, e.g. with respect to the visibility of methods supported as |
| 86 |
target of interception. Refer to the documentation of the interception technology to find out |
| 87 |
whether any such limitations exist. |
| 88 |
|
| 89 |
===== Cross-parameter constraints |
| 90 |
|
| 91 |
Sometimes validation does not only depend on a single parameter but on several or even all |
| 92 |
parameters of a method or constructor. This kind of requirement can be fulfilled with help of a |
| 93 |
cross-parameter constraint. |
| 94 |
|
| 95 |
Cross-parameter constraints can be considered as the method validation equivalent to class-level |
| 96 |
constraints. Both can be used to implement validation requirements which are based on several |
| 97 |
elements. While class-level constraints apply to several properties of a bean, cross-parameter |
| 98 |
constraints apply to several parameters of an executable. |
| 99 |
|
| 100 |
In contrast to single-parameter constraints, cross-parameter constraints are declared on the method |
| 101 |
or constructor as you can see in <<example-using-cross-parameter-constraint>>. Here the cross- |
| 102 |
parameter constraint `@LuggageCountMatchesPassengerCount` declared on the `load()` method is used to |
| 103 |
ensure that no passenger has more than two pieces of luggage. |
| 104 |
|
| 105 |
[[example-using-cross-parameter-constraint]] |
| 106 |
.Declaring a cross-parameter constraint |
| 107 |
==== |
| 108 |
[source, JAVA] |
| 109 |
---- |
| 110 |
package org.hibernate.validator.referenceguide.chapter03.crossparameter; |
| 111 |
|
| 112 |
public class Car { |
| 113 |
|
| 114 |
@LuggageCountMatchesPassengerCount(piecesOfLuggagePerPassenger = 2) |
| 115 |
public void load(List<Person> passengers, List<PieceOfLuggage> luggage) { |
| 116 |
//... |
| 117 |
} |
| 118 |
} |
| 119 |
---- |
| 120 |
==== |
| 121 |
|
| 122 |
As you will learn in the next section, return value constraints are also declared on the method |
| 123 |
level. In order to distinguish cross-parameter constraints from return value constraints, the |
| 124 |
constraint target is configured in the `ConstraintValidator` implementation using the |
| 125 |
`@SupportedValidationTarget` annotation. You can find out about the details in |
| 126 |
<<section-cross-parameter-constraints>> which shows how to implement your own cross-parameter constraint. |
| 127 |
|
| 128 |
In some cases a constraint can be applied to an executable's parameters (i.e. it is a cross- |
| 129 |
parameter constraint), but also to the return value. One example for this are custom constraints |
| 130 |
which allow to specify validation rules using expression or script languages. |
| 131 |
|
| 132 |
Such constraints must define a member `validationAppliesTo()` which can be used at declaration time to |
| 133 |
specify the constraint target. As shown in <<example-specifying-constraint-target>> you apply the |
| 134 |
constraint to an executable's parameters by specifying |
| 135 |
`validationAppliesTo = ConstraintTarget.PARAMETERS`, while `ConstraintTarget.RETURN_VALUE` is used |
| 136 |
to apply the constraint to the executable return value. |
| 137 |
|
| 138 |
[[example-specifying-constraint-target]] |
| 139 |
.Specifying a constraint's target |
| 140 |
==== |
| 141 |
[source, JAVA] |
| 142 |
---- |
| 143 |
package org.hibernate.validator.referenceguide.chapter03.crossparameter.constrainttarget; |
| 144 |
|
| 145 |
public class Garage { |
| 146 |
|
| 147 |
@ELAssert(expression = "...", validationAppliesTo = ConstraintTarget.PARAMETERS) |
| 148 |
public Car buildCar(List<Part> parts) { |
| 149 |
//... |
| 150 |
} |
| 151 |
|
| 152 |
@ELAssert(expression = "...", validationAppliesTo = ConstraintTarget.RETURN_VALUE) |
| 153 |
public Car paintCar(int color) { |
| 154 |
//... |
| 155 |
} |
| 156 |
} |
| 157 |
---- |
| 158 |
==== |
| 159 |
|
| 160 |
Although such a constraint is applicable to the parameters and return value of an executable, the |
| 161 |
target can often be inferred automatically. This is the case, if the constraint is declared on |
| 162 |
|
| 163 |
* a void method with parameters (the constraint applies to the parameters) |
| 164 |
* an executable with return value but no parameters (the constraint applies to the return value) |
| 165 |
* neither a method nor a constructor, but a field, parameter etc. (the constraint applies to the |
| 166 |
annotated element) |
| 167 |
|
| 168 |
In these situations you don't have to specify the constraint target. It is still recommended to do |
| 169 |
so if it increases readability of the source code. If the constraint target is not specified in |
| 170 |
situations where it can't be determined automatically, a ConstraintDeclarationException is raised. |
| 171 |
|
| 172 |
==== Return value constraints |
| 173 |
|
| 174 |
The postconditions of a method or constructor are declared by adding constraint annotations to the |
| 175 |
executable as shown in <<example-declaring-return-value-constraints>>. |
| 176 |
|
| 177 |
[[example-declaring-return-value-constraints]] |
| 178 |
.Declaring method and constructor return value constraints |
| 179 |
==== |
| 180 |
[source, JAVA] |
| 181 |
---- |
| 182 |
package org.hibernate.validator.referenceguide.chapter03.returnvalue; |
| 183 |
|
| 184 |
public class RentalStation { |
| 185 |
|
| 186 |
@ValidRentalStation |
| 187 |
public RentalStation() { |
| 188 |
//... |
| 189 |
} |
| 190 |
|
| 191 |
@NotNull |
| 192 |
@Size(min = 1) |
| 193 |
public List<Customer> getCustomers() { |
| 194 |
//... |
| 195 |
} |
| 196 |
} |
| 197 |
---- |
| 198 |
==== |
| 199 |
|
| 200 |
The following constraints apply to the executables of RentalStation: |
| 201 |
|
| 202 |
* Any newly created `RentalStation` object must satisfy the `@ValidRentalStation` constraint |
| 203 |
* The customer list returned by `getCustomers()` must not be `null` and must contain at least on element |
| 204 |
|
| 205 |
==== Cascaded validation |
| 206 |
|
| 207 |
Similar to the cascaded validation of JavaBeans properties (see |
| 208 |
<<section-object-graph-validation>>), the `@Valid` annotation can be used to mark executable |
| 209 |
parameters and return values for cascaded validation. When validating a parameter or return value |
| 210 |
annotated with `@Valid`, the constraints declared on the parameter or return value object are |
| 211 |
validated as well. |
| 212 |
|
| 213 |
In <<example-cascaded-executable-validation>>, the `car` parameter of the method `Garage#checkCar()` as |
| 214 |
well as the return value of the `Garage` constructor are marked for cascaded validation. |
| 215 |
|
| 216 |
[[example-cascaded-executable-validation]] |
| 217 |
.Marking executable parameters and return values for cascaded validation |
| 218 |
==== |
| 219 |
[source, JAVA] |
| 220 |
---- |
| 221 |
package org.hibernate.validator.referenceguide.chapter03.cascaded; |
| 222 |
|
| 223 |
public class Garage { |
| 224 |
|
| 225 |
@NotNull |
| 226 |
private String name; |
| 227 |
|
| 228 |
@Valid |
| 229 |
public Garage(String name) { |
| 230 |
this.name = name; |
| 231 |
} |
| 232 |
|
| 233 |
public boolean checkCar(@Valid @NotNull Car car) { |
| 234 |
//... |
| 235 |
} |
| 236 |
} |
| 237 |
---- |
| 238 |
|
| 239 |
[source, JAVA] |
| 240 |
---- |
| 241 |
package org.hibernate.validator.referenceguide.chapter03.cascaded; |
| 242 |
|
| 243 |
public class Car { |
| 244 |
|
| 245 |
@NotNull |
| 246 |
private String manufacturer; |
| 247 |
|
| 248 |
@NotNull |
| 249 |
@Size(min = 2, max = 14) |
| 250 |
private String licensePlate; |
| 251 |
|
| 252 |
public Car(String manufacturer, String licencePlate) { |
| 253 |
this.manufacturer = manufacturer; |
| 254 |
this.licensePlate = licencePlate; |
| 255 |
} |
| 256 |
|
| 257 |
//getters and setters ... |
| 258 |
} |
| 259 |
---- |
| 260 |
==== |
| 261 |
|
| 262 |
When validating the arguments of the `checkCar()` method, the constraints on the properties of the |
| 263 |
passed `Car` object are evaluated as well. Similarly, the `@NotNull` constraint on the name field of |
| 264 |
`Garage` is checked when validating the return value of the `Garage` constructor. |
| 265 |
|
| 266 |
Generally, the cascaded validation works for executables in exactly the same way as it does for |
| 267 |
JavaBeans properties. |
| 268 |
|
| 269 |
In particular, `null` values are ignored during cascaded validation (naturally this can't happen |
| 270 |
during constructor return value validation) and cascaded validation is performed recursively, i.e. |
| 271 |
if a parameter or return value object which is marked for cascaded validation itself has properties |
| 272 |
marked with `@Valid`, the constraints declared on the referenced elements will be validated as well. |
| 273 |
|
| 274 |
Cascaded validation can not only be applied to simple object references but also to collection-typed |
| 275 |
parameters and return values. This means when putting the `@Valid` annotation to a parameter or return |
| 276 |
value which |
| 277 |
|
| 278 |
* is an array |
| 279 |
* implements `java.lang.Iterable` |
| 280 |
* or implements `java.util.Map` |
| 281 |
|
| 282 |
each contained element gets validated. So when validating the arguments of the `checkCars()` method in |
| 283 |
<<example-cascaded-executable-validation-listtyped>>, each element instance of the passed list will |
| 284 |
be validated and a `ConstraintViolation` created when any of the contained `Car` instances is invalid. |
| 285 |
|
| 286 |
[[example-cascaded-executable-validation-listtyped]] |
| 287 |
.List-typed method parameter marked for cascaded validation |
| 288 |
==== |
| 289 |
[source, JAVA] |
| 290 |
---- |
| 291 |
package org.hibernate.validator.referenceguide.chapter03.cascaded.collection; |
| 292 |
|
| 293 |
public class Garage { |
| 294 |
|
| 295 |
public boolean checkCars(@Valid @NotNull List<Car> cars) { |
| 296 |
//... |
| 297 |
} |
| 298 |
} |
| 299 |
---- |
| 300 |
==== |
| 301 |
|
| 302 |
[[section-method-constraints-inheritance-hierarchies]] |
| 303 |
==== Method constraints in inheritance hierarchies |
| 304 |
|
| 305 |
When declaring method constraints in inheritance hierarchies, it is important to be aware of the |
| 306 |
following rules: |
| 307 |
|
| 308 |
* The preconditions to be satisfied by the caller of a method may not be strengthened in subtypes |
| 309 |
* The postconditions guaranteed to the caller of a method may not be weakened in subtypes |
| 310 |
|
| 311 |
These rules are motivated by the concept of _behavioral subtyping_ which requires that wherever a |
| 312 |
type `T` is used, also a subtype `S` of `T` may be used without altering the program's behavior. |
| 313 |
|
| 314 |
As an example, consider a class invoking a method on an object with the static type `T`. If the |
| 315 |
runtime type of that object was `S` and `S` imposed additional preconditions, the client class might |
| 316 |
fail to satisfy these preconditions as is not aware of them. The rules of behavioral subtyping are |
| 317 |
also known as the link:$$http://en.wikipedia.org/wiki/Liskov_substitution_principle$$[Liskov |
| 318 |
substitution principle]. |
| 319 |
|
| 320 |
The Bean Validation specification implements the first rule by disallowing parameter constraints on |
| 321 |
methods which override or implement a method declared in a supertype (superclass or interface). |
| 322 |
<<example-illegal-parameter-constraints>> shows a violation of this rule. |
| 323 |
|
| 324 |
[[example-illegal-parameter-constraints]] |
| 325 |
.Illegal method parameter constraint in subtype |
| 326 |
==== |
| 327 |
[source, JAVA] |
| 328 |
---- |
| 329 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.parameter; |
| 330 |
|
| 331 |
public interface Vehicle { |
| 332 |
|
| 333 |
void drive(@Max(75) int speedInMph); |
| 334 |
} |
| 335 |
---- |
| 336 |
|
| 337 |
[source, JAVA] |
| 338 |
---- |
| 339 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.parameter; |
| 340 |
|
| 341 |
public class Car implements Vehicle { |
| 342 |
|
| 343 |
@Override |
| 344 |
public void drive(@Max(55) int speedInMph) { |
| 345 |
//... |
| 346 |
} |
| 347 |
} |
| 348 |
---- |
| 349 |
==== |
| 350 |
|
| 351 |
The `@Max` constraint on `Car#drive()` is illegal since this method implements the interface method |
| 352 |
`Vehicle#drive()`. Note that parameter constraints on overriding methods are also disallowed, if the |
| 353 |
supertype method itself doesn't declare any parameter constraints. |
| 354 |
|
| 355 |
Furthermore, if a method overrides or implements a method declared in several parallel supertypes |
| 356 |
(e.g. two interfaces not extending each other or a class and an interface not implemented by that |
| 357 |
class), no parameter constraints may be specified for the method in any of the involved types. The |
| 358 |
types in <<example-illegal-parameter-constraints-parallel-types>> demonstrate a violation of that |
| 359 |
rule. The method `RacingCar#drive()` overrides `Vehicle#drive()` as well as `Car#drive()`. |
| 360 |
Therefore the constraint on `Vehicle#drive()` is illegal. |
| 361 |
|
| 362 |
[[example-illegal-parameter-constraints-parallel-types]] |
| 363 |
.Illegal method parameter constraint in parallel types of a hierarchy |
| 364 |
==== |
| 365 |
[source, JAVA] |
| 366 |
---- |
| 367 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel; |
| 368 |
|
| 369 |
public interface Vehicle { |
| 370 |
|
| 371 |
void drive(@Max(75) int speedInMph); |
| 372 |
} |
| 373 |
---- |
| 374 |
|
| 375 |
|
| 376 |
[source, JAVA] |
| 377 |
---- |
| 378 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel; |
| 379 |
|
| 380 |
public interface Car { |
| 381 |
|
| 382 |
public void drive(int speedInMph); |
| 383 |
} |
| 384 |
---- |
| 385 |
|
| 386 |
[source, JAVA] |
| 387 |
---- |
| 388 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.parallel; |
| 389 |
|
| 390 |
public class RacingCar implements Car, Vehicle { |
| 391 |
|
| 392 |
@Override |
| 393 |
public void drive(int speedInMph) { |
| 394 |
//... |
| 395 |
} |
| 396 |
} |
| 397 |
---- |
| 398 |
==== |
| 399 |
|
| 400 |
The previously described restrictions only apply to parameter constraints. In contrast, return value |
| 401 |
constraints may be added in methods overriding or implementing any supertype methods. |
| 402 |
|
| 403 |
In this case, all the method's return value constraints apply for the subtype method, i.e. the |
| 404 |
constraints declared on the subtype method itself as well as any return value constraints on |
| 405 |
overridden/implemented supertype methods. This is legal as putting additional return value |
| 406 |
constraints in place may never represent a weakening of the postconditions guaranteed to the caller |
| 407 |
of a method. |
| 408 |
|
| 409 |
So when validating the return value of the method `Car#getPassengers()` shown in |
| 410 |
<<example-return-value-constraints-in-hierarchy>>, the `@Size` constraint on the method itself as well |
| 411 |
as the `@NotNull` constraint on the implemented interface method `Vehicle#getPassengers()` apply. |
| 412 |
|
| 413 |
[[example-return-value-constraints-in-hierarchy]] |
| 414 |
.Return value constraints on supertype and subtype method |
| 415 |
==== |
| 416 |
[source, JAVA] |
| 417 |
---- |
| 418 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.returnvalue; |
| 419 |
|
| 420 |
public interface Vehicle { |
| 421 |
|
| 422 |
@NotNull |
| 423 |
List<Person> getPassengers(); |
| 424 |
} |
| 425 |
---- |
| 426 |
|
| 427 |
|
| 428 |
[source, JAVA] |
| 429 |
---- |
| 430 |
package org.hibernate.validator.referenceguide.chapter03.inheritance.returnvalue; |
| 431 |
|
| 432 |
public class Car implements Vehicle { |
| 433 |
|
| 434 |
@Override |
| 435 |
@Size(min = 1) |
| 436 |
public List<Person> getPassengers() { |
| 437 |
//... |
| 438 |
} |
| 439 |
} |
| 440 |
---- |
| 441 |
==== |
| 442 |
|
| 443 |
If the validation engine detects a violation of any of the aforementioned rules, a |
| 444 |
`ConstraintDeclarationException` will be raised. |
| 445 |
|
| 446 |
[NOTE] |
| 447 |
==== |
| 448 |
The rules described in this section only apply to methods but not constructors. By definition, |
| 449 |
constructors never override supertype constructors. Therefore, when validating the parameters or the |
| 450 |
return value of a constructor invocation only the constraints declared on the constructor itself |
| 451 |
apply, but never any constraints declared on supertype constructors. |
| 452 |
==== |
| 453 |
|
| 454 |
[TIP] |
| 455 |
==== |
| 456 |
Enforcement of these rules may be relaxed by setting the configuration parameters contained in |
| 457 |
the `MethodValidationConfiguration` property of the `HibernateValidatorConfiguration` before creating |
| 458 |
the `Validator` instance. See also <<section-method-validation-prerequisite-relaxation>>. |
| 459 |
==== |
| 460 |
|
| 461 |
[[section-validating-executable-constraints]] |
| 462 |
=== Validating method constraints |
| 463 |
|
| 464 |
The validation of method constraints is done using the `ExecutableValidator` interface. |
| 465 |
|
| 466 |
In <<section-obtaining-executable-validator>> you will learn how to obtain an `ExecutableValidator` |
| 467 |
instance while <<section-executable-validator-methods>> shows how to use the different methods |
| 468 |
offered by this interface. |
| 469 |
|
| 470 |
Instead of calling the `ExecutableValidator` methods directly from within application code, they are |
| 471 |
usually invoked via a method interception technology such as AOP, proxy objects, etc. This causes |
| 472 |
executable constraints to be validated automatically and transparently upon method or constructor |
| 473 |
invocation. Typically a `ConstraintViolationException` is raised by the integration layer in case any |
| 474 |
of the constraints is violated. |
| 475 |
|
| 476 |
[[section-obtaining-executable-validator]] |
| 477 |
==== Obtaining an `ExecutableValidator` instance |
| 478 |
|
| 479 |
You can retrieve an `ExecutableValidator` instance via `Validator#forExecutables()` as shown in |
| 480 |
<<example-obtaining-executable-validator>>. |
| 481 |
|
| 482 |
[[example-obtaining-executable-validator]] |
| 483 |
.Obtaining an `ExecutableValidator` instance |
| 484 |
==== |
| 485 |
[source, JAVA] |
| 486 |
---- |
| 487 |
ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); |
| 488 |
executableValidator = factory.getValidator().forExecutables(); |
| 489 |
---- |
| 490 |
==== |
| 491 |
|
| 492 |
In the example the executable validator is retrieved from the default validator factory, but if |
| 493 |
required you could also bootstrap a specifically configured factory as described in |
| 494 |
<<chapter-bootstrapping>>, for instance in order to use a specific parameter name provider |
| 495 |
(see <<section-parameter-name-provider>>). |
| 496 |
|
| 497 |
[[section-executable-validator-methods]] |
| 498 |
==== `ExecutableValidator` methods |
| 499 |
|
| 500 |
The `ExecutableValidator` interface offers altogether four methods: |
| 501 |
|
| 502 |
* `validateParameters()` and `validateReturnValue()` for method validation |
| 503 |
* `validateConstructorParameters()` and `validateConstructorReturnValue()` for constructor validation |
| 504 |
|
| 505 |
Just as the methods on `Validator`, all these methods return a `Set<ConstraintViolation>` which contains |
| 506 |
a `ConstraintViolation` instance for each violated constraint and which is empty if the validation |
| 507 |
succeeds. Also all the methods have a var-args groups parameter by which you can pass the validation |
| 508 |
groups to be considered for validation. |
| 509 |
|
| 510 |
The examples in the following sections are based on the methods on constructors of the `Car` class |
| 511 |
shown in <<example-executable-validator-class-car>>. |
| 512 |
|
| 513 |
[[example-executable-validator-class-car]] |
| 514 |
.Class `Car` with constrained methods and constructors |
| 515 |
==== |
| 516 |
[source, JAVA] |
| 517 |
---- |
| 518 |
package org.hibernate.validator.referenceguide.chapter03.validation; |
| 519 |
|
| 520 |
public class Car { |
| 521 |
|
| 522 |
public Car(@NotNull String manufacturer) { |
| 523 |
//... |
| 524 |
} |
| 525 |
|
| 526 |
@ValidRacingCar |
| 527 |
public Car(String manufacturer, String team) { |
| 528 |
//... |
| 529 |
} |
| 530 |
|
| 531 |
public void drive(@Max(75) int speedInMph) { |
| 532 |
//... |
| 533 |
} |
| 534 |
|
| 535 |
@Size(min = 1) |
| 536 |
public List<Passenger> getPassengers() { |
| 537 |
//... |
| 538 |
} |
| 539 |
} |
| 540 |
---- |
| 541 |
==== |
| 542 |
|
| 543 |
===== `ExecutableValidator#validateParameters()` |
| 544 |
|
| 545 |
The method `validateParameters()` is used to validate the arguments of a method invocation. |
| 546 |
<<example-executable-validator-validate-parameters>> shows an example. The validation results in a |
| 547 |
violation of the `@Max` constraint on the parameter of the `drive()` method. |
| 548 |
|
| 549 |
[[example-executable-validator-validate-parameters]] |
| 550 |
.Using `ExecutableValidator#validateParameters()` |
| 551 |
==== |
| 552 |
[source, JAVA] |
| 553 |
---- |
| 554 |
Car object = new Car( "Morris" ); |
| 555 |
Method method = Car.class.getMethod( "drive", int.class ); |
| 556 |
Object[] parameterValues = { 80 }; |
| 557 |
Set<ConstraintViolation<Car>> violations = executableValidator.validateParameters( |
| 558 |
object, |
| 559 |
method, |
| 560 |
parameterValues |
| 561 |
); |
| 562 |
|
| 563 |
assertEquals( 1, violations.size() ); |
| 564 |
Class<? extends Annotation> constraintType = violations.iterator() |
| 565 |
.next() |
| 566 |
.getConstraintDescriptor() |
| 567 |
.getAnnotation() |
| 568 |
.annotationType(); |
| 569 |
assertEquals( Max.class, constraintType ); |
| 570 |
---- |
| 571 |
==== |
| 572 |
|
| 573 |
Note that `validateParameters()` validates all the parameter constraints of a method, i.e. constraints |
| 574 |
on individual parameters as well as cross-parameter constraints. |
| 575 |
|
| 576 |
===== `ExecutableValidator#validateReturnValue()` |
| 577 |
|
| 578 |
Using `validateReturnValue()` the return value of a method can can be validated. The validation in |
| 579 |
<<example-executable-validator-validate-return-value>> yields one constraint violation since the |
| 580 |
`getPassengers()` method is expect to return at least one `Passenger` instance. |
| 581 |
|
| 582 |
[[example-executable-validator-validate-return-value]] |
| 583 |
.Using `ExecutableValidator#validateReturnValue()` |
| 584 |
==== |
| 585 |
[source, JAVA] |
| 586 |
---- |
| 587 |
Car object = new Car( "Morris" ); |
| 588 |
Method method = Car.class.getMethod( "getPassengers" ); |
| 589 |
Object returnValue = Collections.<Passenger>emptyList(); |
| 590 |
Set<ConstraintViolation<Car>> violations = executableValidator.validateReturnValue( |
| 591 |
object, |
| 592 |
method, |
| 593 |
returnValue |
| 594 |
); |
| 595 |
|
| 596 |
assertEquals( 1, violations.size() ); |
| 597 |
Class<? extends Annotation> constraintType = violations.iterator() |
| 598 |
.next() |
| 599 |
.getConstraintDescriptor() |
| 600 |
.getAnnotation() |
| 601 |
.annotationType(); |
| 602 |
assertEquals( Size.class, constraintType ); |
| 603 |
---- |
| 604 |
==== |
| 605 |
|
| 606 |
===== `ExecutableValidator#validateConstructorParameters()` |
| 607 |
|
| 608 |
The arguments of constructor invocations can be validated with `validateConstructorParameters()` as |
| 609 |
shown in method <<example-executable-validator-validate-constructor-parameters>>. Due to the |
| 610 |
`@NotNull` constraint on the manufacturer parameter, the validation call returns one constraint |
| 611 |
violation. |
| 612 |
|
| 613 |
[[example-executable-validator-validate-constructor-parameters]] |
| 614 |
.Using `ExecutableValidator#validateConstructorParameters()` |
| 615 |
==== |
| 616 |
[source, JAVA] |
| 617 |
---- |
| 618 |
Constructor<Car> constructor = Car.class.getConstructor( String.class ); |
| 619 |
Object[] parameterValues = { null }; |
| 620 |
Set<ConstraintViolation<Car>> violations = executableValidator.validateConstructorParameters( |
| 621 |
constructor, |
| 622 |
parameterValues |
| 623 |
); |
| 624 |
|
| 625 |
assertEquals( 1, violations.size() ); |
| 626 |
Class<? extends Annotation> constraintType = violations.iterator() |
| 627 |
.next() |
| 628 |
.getConstraintDescriptor() |
| 629 |
.getAnnotation() |
| 630 |
.annotationType(); |
| 631 |
assertEquals( NotNull.class, constraintType ); |
| 632 |
---- |
| 633 |
==== |
| 634 |
|
| 635 |
===== `ExecutableValidator#validateConstructorReturnValue()` |
| 636 |
|
| 637 |
Finally, by using `validateConstructorReturnValue()` you can validate a constructor's return value. In |
| 638 |
<<example-executable-validator-validate-constructor-return-value>>, `validateConstructorReturnValue()` |
| 639 |
returns one constraint violation, since the `Car` instance returned by the constructor doesn't satisfy |
| 640 |
the `@ValidRacingCar` constraint (not shown). |
| 641 |
|
| 642 |
[[example-executable-validator-validate-constructor-return-value]] |
| 643 |
.Using `ExecutableValidator#validateConstructorReturnValue()` |
| 644 |
==== |
| 645 |
[source, JAVA] |
| 646 |
---- |
| 647 |
//constructor for creating racing cars |
| 648 |
Constructor<Car> constructor = Car.class.getConstructor( String.class, String.class ); |
| 649 |
Car createdObject = new Car( "Morris", null ); |
| 650 |
Set<ConstraintViolation<Car>> violations = executableValidator.validateConstructorReturnValue( |
| 651 |
constructor, |
| 652 |
createdObject |
| 653 |
); |
| 654 |
|
| 655 |
assertEquals( 1, violations.size() ); |
| 656 |
Class<? extends Annotation> constraintType = violations.iterator() |
| 657 |
.next() |
| 658 |
.getConstraintDescriptor() |
| 659 |
.getAnnotation() |
| 660 |
.annotationType(); |
| 661 |
assertEquals( ValidRacingCar.class, constraintType ); |
| 662 |
---- |
| 663 |
==== |
| 664 |
|
| 665 |
==== `ConstraintViolation` methods for method validation |
| 666 |
|
| 667 |
In addition to the methods introduced in <<section-constraint-violation-methods>>, |
| 668 |
`ConstraintViolation` provides two more methods specific to the validation of executable parameters |
| 669 |
and return values. |
| 670 |
|
| 671 |
`ConstraintViolation#getExecutableParameters()` returns the validated parameter array in case of |
| 672 |
method or constructor parameter validation, while `ConstraintViolation#getExecutableReturnValue()` |
| 673 |
provides access to the validated object in case of return value validation. |
| 674 |
|
| 675 |
All the other `ConstraintViolation` methods generally work for method validation in the same way as |
| 676 |
for validation of beans. Refer to the link:$$http://docs.jboss.org/hibernate/beanvalidation/spec/1.1 |
| 677 |
/api/index.html?javax/validation/metadata/BeanDescriptor.html$$[JavaDoc] to learn more about the |
| 678 |
behavior of the individual methods and their return values during bean and method validation. |
| 679 |
|
| 680 |
Note that `getPropertyPath()` can be very useful in order to obtain detailed information about the |
| 681 |
validated parameter or return value, e.g. for logging purposes. In particular, you can retrieve name |
| 682 |
and argument types of the concerned method as well as the index of the concerned parameter from the |
| 683 |
path nodes. How this can be done is shown in <<example-executable-validation-property-path>>. |
| 684 |
|
| 685 |
[[example-executable-validation-property-path]] |
| 686 |
.Retrieving method and parameter information |
| 687 |
==== |
| 688 |
[source, JAVA] |
| 689 |
---- |
| 690 |
Car object = new Car( "Morris" ); |
| 691 |
Method method = Car.class.getMethod( "drive", int.class ); |
| 692 |
Object[] parameterValues = { 80 }; |
| 693 |
Set<ConstraintViolation<Car>> violations = executableValidator.validateParameters( |
| 694 |
object, |
| 695 |
method, |
| 696 |
parameterValues |
| 697 |
); |
| 698 |
|
| 699 |
assertEquals( 1, violations.size() ); |
| 700 |
Iterator<Node> propertyPath = violations.iterator() |
| 701 |
.next() |
| 702 |
.getPropertyPath() |
| 703 |
.iterator(); |
| 704 |
|
| 705 |
MethodNode methodNode = propertyPath.next().as( MethodNode.class ); |
| 706 |
assertEquals( "drive", methodNode.getName() ); |
| 707 |
assertEquals( Arrays.<Class<?>>asList( int.class ), methodNode.getParameterTypes() ); |
| 708 |
|
| 709 |
ParameterNode parameterNode = propertyPath.next().as( ParameterNode.class ); |
| 710 |
assertEquals( "arg0", parameterNode.getName() ); |
| 711 |
assertEquals( 0, parameterNode.getParameterIndex() ); |
| 712 |
---- |
| 713 |
==== |
| 714 |
|
| 715 |
The parameter name is determined using the current `ParameterNameProvider` (see |
| 716 |
<<section-parameter-name-provider>>) and defaults to `arg0`, `arg1` etc. |
| 717 |
|
| 718 |
[[section-builtin-method-constraints]] |
| 719 |
=== Built-in method constraints |
| 720 |
|
| 721 |
In addition to the built-in bean and property-level constraints discussed in |
| 722 |
<<section-builtin-constraints>>, Hibernate Validator currently provides one method-level constraint, |
| 723 |
`@ParameterScriptAssert`. This is a generic cross-parameter constraint which allows to implement |
| 724 |
validation routines using any JSR 223 compatible ("Scripting for the Java^TM^ Platform") scripting |
| 725 |
language, provided an engine for this language is available on the classpath. |
| 726 |
|
| 727 |
To refer to the executable's parameters from within the expression, use their name as obtained from |
| 728 |
the active parameter name provider (see <<section-parameter-name-provider>>). |
| 729 |
<<example-parameterscriptassert>> shows how the validation logic of the `@LuggageCountMatchesPassengerCount` |
| 730 |
constraint from <<example-using-cross-parameter-constraint>> could be expressed with the help of |
| 731 |
`@ParameterScriptAssert`. |
| 732 |
|
| 733 |
[[example-parameterscriptassert]] |
| 734 |
.Using `@ParameterScriptAssert` |
| 735 |
==== |
| 736 |
[source, JAVA] |
| 737 |
---- |
| 738 |
package org.hibernate.validator.referenceguide.chapter03.parametersscriptassert; |
| 739 |
|
| 740 |
public class Car { |
| 741 |
|
| 742 |
@ParameterScriptAssert(lang = "javascript", script = "arg1.size() <= arg0.size() * 2") |
| 743 |
public void load(List<Person> passengers, List<PieceOfLuggage> luggage) { |
| 744 |
//... |
| 745 |
} |
| 746 |
} |
| 747 |
---- |
| 748 |
==== |