Debian Codegraph @

documentation/src/main/asciidoc/ch11.asciidoc

raw
1 :sourcedir: ../../test/java
2
3 [[validator-specifics]]
4 == Hibernate Validator Specifics
5
6 In this chapter you will learn how to make use of several features provided by Hibernate Validator
7 in addition to the functionality defined by the Bean Validation specification. This includes the
8 fail fast mode, the API for programmatic constraint configuration and the boolean composition of
9 constraints.
10
11 [NOTE]
12 ====
13 Using the features described in the following sections may result in application code which is not
14 portable between Bean Validation providers.
15 ====
16
17 === Public API
18
19 Let's start, however, with a look at the public API of Hibernate Validator. <<validator-public-api>>
20 lists all packages belonging to this API and describes their purpose. Note that when a package is
21 part of the public this is not necessarily true for its sub-packages.
22
23 [[validator-public-api]]
24 .Hibernate Validator public API
25 [options="header"]
26 |===============
27 |Packages|Description
28 |`org.hibernate.validator`|Classes used by the Bean Validation bootstrap mechanism
29 (eg. validation provider, configuration class); For more details
30 see <<chapter-bootstrapping>>.
31 |`org.hibernate.validator.cfg`,
32 `org.hibernate.validator.cfg.context`,
33 `org.hibernate.validator.cfg.defs`,
34 `org.hibernate.validator.spi.cfg`|Hibernate Validator's fluent API for constraint
35 declaration; In `org.hibernate.validator.cfg` you
36 will find the `ConstraintMapping` interface,
37 in `org.hibernate.validator.cfg.defs` all
38 constraint definitions and in `org.hibernate.validator.spi.cfg` a
39 callback for using the API for configuring the default validator factory.
40 Refer to <<section-programmatic-api>> for the details.
41 |`org.hibernate.validator.constraints`,
42 `org.hibernate.validator.constraints.br`|Some useful custom constraints provided by Hibernate
43 Validator in addition to the built-in constraints defined by the
44 Bean Validation specification; The constraints are described in
45 detail in <<validator-defineconstraints-hv-constraints>>.
46 |`org.hibernate.validator.constraintvalidation`|Extended constraint validator context which allows to set
47 custom attributes for message interpolation. <<section-hibernateconstraintvalidatorcontext>> describes
48 how to make use of that feature.
49 |`org.hibernate.validator.group`,
50 `org.hibernate.validator.spi.group`|The group sequence provider feature which allows you to
51 define dynamic default group sequences in function of the
52 validated object state; The specifics can be found in <<section-default-group-class>>.
53 |`org.hibernate.validator.messageinterpolation`,
54 `org.hibernate.validator.resourceloading`,
55 `org.hibernate.validator.spi.resourceloading`|Classes related to constraint message interpolation; The
56 first package contains Hibernate Validator's default message
57 interpolator,
58 `ResourceBundleMessageInterpolator`. The
59 latter two packages provide the
60 `ResourceBundleLocator` SPI for the loading of resource
61 bundles (see <<section-resource-bundle-locator>>)
62 and its default implementation.
63 |`org.hibernate.validator.parameternameprovider`|A `ParameterNameProvider` based on the
64 ParaNamer library, see <<section-paranamer-parameternameprovider>>.
65 |`org.hibernate.validator.propertypath`|Extensions to the `javax.validation.Path` API,
66 see <<section-extensions-path-api>>.
67 |`org.hibernate.validator.spi.constraintdefinition`|An SPI for registering additional constraint validators programmatically,
68 see <<section-constraint-definition-contribution>>.
69 |`org.hibernate.validator.spi.time`|An SPI for customizing the retrieval of the current time when validating `@Future` and `@Past`,
70 see <<section-time-provider>>.
71 |`org.hibernate.validator.valuehandling`, `org.hibernate.validator.spi.valuehandling`|Classes related to the processing
72 of values prior to thei validation, see <<section-value-handling>>.
73 |===============
74
75 [NOTE]
76 ====
77 The public packages of Hibernate Validator fall into two categories: while the actual API parts are
78 intended to be _invoked_ or _used_ by clients (e.g. the API for programmatic constraint declaration
79 or the custom constraints), the SPI (service provider interface) packages contain interfaces which
80 are intended to be _implemented_ by clients (e.g. `ResourceBundleLocator`).
81 ====
82
83 Any packages not listed in that table are internal packages of Hibernate Validator and are not
84 intended to be accessed by clients. The contents of these internal packages can change from release
85 to release without notice, thus possibly breaking any client code relying on it.
86
87 [[section-fail-fast]]
88 === Fail fast mode
89
90 Using the fail fast mode, Hibernate Validator allows to return from the current validation as soon
91 as the first constraint violation occurs. This can be useful for the validation of large object
92 graphs where you are only interested in a quick check whether there is any constraint violation at
93 all.
94
95 <<example-using-fail-fast>> shows how to bootstrap and use a fail fast enabled validator.
96
97 [[example-using-fail-fast]]
98 .Using the fail fast validation mode
99 ====
100 [source, JAVA, indent=0]
101 ----
102 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/failfast/Car.java[tags=include]
103 ----
104
105 [source, JAVA, indent=0]
106 ----
107 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/failfast/FailFastTest.java[tags=include]
108 ----
109 ====
110
111 Here the validated object actually fails to satisfy both the constraints declared on the `Car` class,
112 yet the validation call yields only one `ConstraintViolation` since the fail fast mode is enabled.
113
114 [NOTE]
115 ====
116 There is no guarantee in which order the constraints are evaluated, i.e. it is not deterministic
117 whether the returned violation originates from the `@NotNull` or the `@AssertTrue` constraint. If
118 required, a deterministic evaluation order can be enforced using group sequences as described in
119 <<section-defining-group-sequences>>.
120 ====
121
122 Refer to <<section-provider-specific-settings>> to learn about the different ways of enabling the
123 fail fast mode when bootstrapping a validator.
124
125 [[section-method-validation-prerequisite-relaxation]]
126 === Relaxation of requirements for method validation in class hierarchies
127
128 The Bean Validation specification defines a set of preconditions which apply when defining
129 constraints on methods within class hierarchies. These preconditions are defined in
130 http://beanvalidation.org/1.1/spec/#constraintdeclarationvalidationprocess-methodlevelconstraints-inheritance[section 4.5.5]
131 of the Bean Validation 1.1 specification. See also <<section-method-constraints-inheritance-hierarchies>>
132 in this guide.
133
134 As per specification a Bean Validation provider is allowed to relax these preconditions.
135 With Hibernate Validator you can do this in one of two ways.
136
137 First you can use the configuration properties _hibernate.validator.allow_parameter_constraint_override_,
138 _hibernate.validator.allow_multiple_cascaded_validation_on_result_ and
139 _hibernate.validator.allow_parallel_method_parameter_constraint_ in _validation.xml_. See example
140 <<example-relaxing-method-validation-xml>>.
141
142
143 [[example-relaxing-method-validation-xml]]
144 .Configuring method validation behaviour in class hierarchies via properties
145 ====
146 [source, XML]
147 ----
148 <?xml version="1.0" encoding="UTF-8"?>
149 <validation-config
150 xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
151 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
152 xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd">
153 <default-provider>org.hibernate.validator.HibernateValidator</default-provider>
154
155 <property name="hibernate.validator.allow_parameter_constraint_override">true</property>
156 <property name="hibernate.validator.allow_multiple_cascaded_validation_on_result">true</property>
157 <property name="hibernate.validator.allow_parallel_method_parameter_constraint">true</property>
158 </validation-config>
159 ----
160 ====
161
162 Alternatively these settings can be applied during programmatic bootstrapping.
163
164 [[example-relaxing-method-validation]]
165 .Configuring method validation behaviour in class hierarchies
166 ====
167 [source, JAVA]
168 ----
169 HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
170
171 configuration.allowMultipleCascadedValidationOnReturnValues(true)
172 .allowOverridingMethodAlterParameterConstraint(true)
173 .allowParallelMethodsDefineParameterConstraints(true);
174 ----
175 ====
176
177 By default, all of these properties are false, implementing the default behavior as defined in the
178 Bean Validation specification.
179
180 [WARNING]
181 ====
182 Changing the default behaviour for method validation will result in non specification conform and non
183 portable application. Make sure to understand what you are doing and that your use case really
184 requires changes to the default behaviour.
185 ====
186
187 [[section-programmatic-api]]
188 === Programmatic constraint definition and declaration
189
190 As per the Bean Validation specification, you can define and declare constraints using Java annotations and XML
191 based constraint mappings.
192
193 In addition, Hibernate Validator provides a fluent API which allows for the programmatic
194 configuration of constraints. Use cases include the dynamic addition of constraints at runtime
195 depending on some application state or tests where you need entities with different constraints in
196 different scenarios but don't want to implement actual Java classes for each test case.
197
198 By default, constraints added via the fluent API are additive to constraints configured via the
199 standard configuration capabilities. But it is also possible to ignore annotation and XML configured
200 constraints where required.
201
202 The API is centered around the `ConstraintMapping` interface. You obtain a new mapping via
203 `HibernateValidatorConfiguration#createConstraintMapping()` which you then can configure in a fluent
204 manner as shown in <<example-constraint-mapping>>.
205
206 [[example-constraint-mapping]]
207 .Programmatic constraint declaration
208 ====
209 [source, JAVA, indent=0]
210 ----
211 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=constraintMapping]
212 ----
213 ====
214
215 Constraints can be configured on multiple classes and properties using method chaining. The
216 constraint definition classes `NotNullDef` and SizeDef are helper classes which allow to configure
217 constraint parameters in a type-safe fashion. Definition classes exist for all built-in constraints
218 in the `org.hibernate.validator.cfg.defs` package. By calling `ignoreAnnotations()` any constraints
219 configured via annotations or XML are ignored for the given element.
220
221 [NOTE]
222 ====
223 Each element (type, property, method etc.) may only be configured once within all the constraint
224 mappings used to set up one validator factory. Otherwise a `ValidationException` is raised.
225 ====
226
227 [NOTE]
228 ====
229 It is not supported to add constraints to non-overridden supertype properties and methods by
230 configuring a subtype. Instead you need to configure the supertype in this case.
231 ====
232
233 Having configured the mapping, you must add it back to the configuration object from which you then
234 can obtain a validator factory.
235
236 For custom constraints you can either create your own definition classes extending `ConstraintDef` or
237 you can use `GenericConstraintDef` as seen in <<example-generic-constraint-mapping>>.
238
239 [[example-generic-constraint-mapping]]
240 .Programmatic declaration of a custom constraint
241 ====
242 [source, JAVA, indent=0]
243 ----
244 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=genericConstraintDef]
245 ----
246 ====
247
248 By invoking `valid()` you can mark a member for cascaded validation which is equivalent to annotating
249 it with `@Valid`. Configure any group conversions to be applied during cascaded validation using the
250 `convertGroup()` method (equivalent to `@ConvertGroup`). An example can be seen in
251 <<example-cascading-constraints>>.
252
253 [[example-cascading-constraints]]
254 .Marking a property for cascaded validation
255 ====
256 [source, JAVA, indent=0]
257 ----
258 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=cascaded]
259 ----
260 ====
261
262 You can not only configure bean constraints using the fluent API but also method and constructor
263 constraints. As shown in <<example-method-constraint-mapping>> constructors are identified by their
264 parameter types and methods by their name and parameter types. Having selected a method or
265 constructor, you can mark its parameters and/or return value for cascaded validation and add
266 constraints as well as cross-parameter constraints.
267
268 [[example-method-constraint-mapping]]
269 .Programmatic declaration of method and constructor constraints
270 ====
271 [source, JAVA, indent=0]
272 ----
273 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=executableConfiguration]
274 ----
275 ====
276
277 Last but not least you can configure the default group sequence or the default group sequence
278 provider of a type as shown in the following example.
279
280 [[example-sequences]]
281 .Configuration of default group sequence and default group sequence provider
282 ====
283 [source, JAVA, indent=0]
284 ----
285 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=defaultGroupSequence]
286 ----
287 ====
288
289 [[section-programmatic-api-contributor]]
290 === Applying programmatic constraint declarations to the default validator factory
291
292 If you are not bootstrapping a validator factory manually
293 but work with the default factory as configured via _META-INF/validation.xml_
294 (see <<chapter-xml-configuration>>),
295 you can add one or more constraint mappings by creating one or several constraint mapping contributors.
296 To do so, implement the `ConstraintMappingContributor` contract:
297
298 [[example-constraint-mapping-contributor]]
299 .Custom `ConstraintMappingContributor` implementation
300 ====
301 [source, JAVA, indent=0]
302 ----
303 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/MyConstraintMappingContributor.java[tags=include]
304 ----
305 ====
306
307 You then need to specify the fully-qualified class name of the contributor implementation in _META-INF/validation.xml_,
308 using the property key `hibernate.validator.constraint_mapping_contributors`. You can specify several
309 contributors by separating them with a comma.
310
311 [[section-advanced-constraint-composition]]
312 === Advanced constraint composition features
313
314 ==== Validation target specification for purely composed constraints
315
316 In case you specify a purely composed constraint - i.e. a constraint which has no validator itself but is solely made
317 up from other, composing constraints - on a method declaration, the validation engine cannot determine whether that
318 constraint is to be applied as a return value constraint or as a cross-parameter constraint.
319
320 Hibernate Validator allows to resolve such ambiguities by specifying the `@SupportedValidationTarget` annotation on the
321 declaration of the composed constraint type as shown in <<example-purely-composed-constraint-validation-target>>.
322 The `@ValidInvoiceAmount` does not declare any validator, but it is solely composed by the `@Min` and `@NotNull`
323 constraints. The `@SupportedValidationTarget` ensures that the constraint is applied to the method return value when
324 given on a method declaration.
325
326 [[example-purely-composed-constraint-validation-target]]
327 .Specifying the validation target of a purely composed constraint
328 ====
329 [source, JAVA]
330 ----
331 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/purelycomposed/ValidInvoiceAmount.java[tags=include]
332 ----
333 ====
334
335 [[section-boolean-constraint-composition]]
336 ==== Boolean composition of constraints
337
338 Bean Validation specifies that the constraints of a composed constraint (see
339 <<section-constraint-composition>>) are all combined via a logical _AND_. This means all of the
340 composing constraints need to return true in order for an overall successful validation.
341
342 Hibernate Validator offers an extension to this and allows you to compose constraints via a logical
343 _OR_ or _NOT_. To do so you have to use the ConstraintComposition annotation and the enum
344 CompositionType with its values _AND_, _OR_ and _$$ALL_FALSE$$_.
345
346 <<example-boolean-constraint-composition>> shows how to build a composed constraint `@PatternOrSize`
347 where only one of the composing constraints needs to be valid in order to pass the validation.
348 Either the validated string is all lower-cased or it is between two and three characters long.
349
350 [[example-boolean-constraint-composition]]
351 .OR composition of constraints
352 ====
353 [source, JAVA]
354 ----
355 package org.hibernate.validator.referenceguide.chapter11.booleancomposition;
356
357 @ConstraintComposition(OR)
358 @Pattern(regexp = "[a-z]")
359 @Size(min = 2, max = 3)
360 @ReportAsSingleViolation
361 @Target({ METHOD, FIELD })
362 @Retention(RUNTIME)
363 @Constraint(validatedBy = { })
364 public @interface PatternOrSize {
365 String message() default "{org.hibernate.validator.referenceguide.chapter11." +
366 "booleancomposition.PatternOrSize.message}";
367
368 Class<?>[] groups() default { };
369
370 Class<? extends Payload>[] payload() default { };
371 }
372 ----
373 ====
374
375 [TIP]
376 ====
377 Using _$$ALL_FALSE$$_ as composition type implicitly enforces that only a single violation will get
378 reported in case validation of the constraint composition fails.
379 ====
380
381 [[section-extensions-path-api]]
382 === Extensions of the Path API
383
384 Hibernate Validator provides an extension to the `javax.validation.Path` API.
385 For nodes of `ElementKind.PROPERTY` it allows to obtain the value of the represented property.
386 To do so, narrow down a given node to the type `org.hibernate.validator.path.PropertyNode` using `Node#as()`, as shown in the following example:
387
388 [[example-property-node-get-value]]
389 .Getting the value from property nodes
390 ====
391 [source, JAVA, indent=0]
392 ----
393 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/propertypath/PropertyPathTest.java[tags=include]
394 ----
395 ====
396
397 This is specifically useful to obtain the element of `Set` properties on the property path (e.g. `apartments` in the example) which otherwise could not be identified (unlike for `Map` and `List`, there is no key nor index in this case).
398
399 [[section-dynamic-payload]]
400 === Dynamic payload as part of ConstraintViolation
401
402 In some cases automatic processing of violations can be aided, if the constraint violation provides additional
403 data - a so called dynamic payload. This dynamic payload could for example contain hints to the user on how to
404 resolve the violation.
405
406 Dynamic payloads can be set in <<validator-customconstraints,custom constraints>> using `HibernateConstraintValidatorContext`.
407 This is shown in example <<example-constraint-validator-setting-dynamic-payload>> where the
408 `javax.validation.ConstraintValidatorContext` is unwrapped to `HibernateConstraintValidatorContext` in order to call
409 `withDynamicPayload`.
410
411 [[example-constraint-validator-setting-dynamic-payload]]
412 .ConstraintValidator implementation setting a dynamic payload
413 ====
414 [source, JAVA, indent=0]
415 ----
416 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/dynamicpayload/ValidPassengerCountValidator.java[tags=include]
417 ----
418 ====
419
420 On the constraint violation processing side, a `javax.validation.ConstraintViolation` can then in turn be
421 unwrapped to `HibernateConstraintViolation` in order to retrieve the dynamic payload for further processing.
422
423 [[example-retrieving-dynamic-payload]]
424 .Retrieval of a ConstraintViolations's dynamic payload
425 ====
426 [source, JAVA, indent=0]
427 ----
428 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/dynamicpayload/DynamicPayLoadTest.java[tags=include]
429 ----
430 ====
431
432 [[non-el-message-interpolator]]
433 === `ParameterMessageInterpolator`
434
435 Hibernate Validator requires per default an implementation of the Unified EL (see
436 <<validator-gettingstarted-uel>>) to be available. This is needed to allow the interpolation
437 of constraint error messages using EL expressions as defined by Bean Validation 1.1.
438
439 For environments where you cannot or do not want to provide an EL implementation, Hibernate Validators
440 offers a non EL based message interpolator - `org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator`.
441
442 Refer to <<section-custom-message-interpolation>> to see how to plug in custom message interpolator
443 implementations.
444
445 [WARNING]
446 ====
447 Constraint messages containing EL expressions will be returned un-interpolated by
448 `org.hibernate.validator.messageinterpolation.ParameterMessageInterpolator`. This also affects
449 built-in default constraint messages which use EL expressions. At the moment `DecimalMin` and `DecimalMax` are affected.
450 ====
451
452 === `ResourceBundleLocator`
453
454 With `ResourceBundleLocator`, Hibernate Validator provides an additional SPI which allows to retrieve
455 error messages from other resource bundles than _ValidationMessages_ while still using the actual
456 interpolation algorithm as defined by the specification. Refer to
457 <<section-resource-bundle-locator>> to learn how to make use of that SPI.
458
459 === Custom contexts
460
461 The Bean Validation specification offers at several points in its API the possibility to unwrap a
462 given interface to a implementor specific subtype. In the case of constraint violation creation in
463 `ConstraintValidator` implementations as well as message interpolation in `MessageInterpolator`
464 instances, there exist `unwrap()` methods for the provided context instances -
465 `ConstraintValidatorContext` respectively `MessageInterpolatorContext`. Hibernate Validator provides
466 custom extensions for both of these interfaces.
467
468 [[section-hibernateconstraintvalidatorcontext]]
469 ==== `HibernateConstraintValidatorContext`
470
471 [[section-custom-constraint-validator-context]]
472 `HibernateConstraintValidatorContext` is a subtype of `ConstraintValidatorContext` which allows you to:
473
474 * set arbitrary parameters for interpolation via the Expression Language message interpolation
475 facility using `HibernateConstraintValidatorContext#addExpressionVariable(String, Object)`.
476 For an example refer to <<example-custom-message-parameter>>.
477 +
478 [NOTE]
479 ====
480 Note that the parameters specified via `addExpressionVariable(String, Object)` are global and apply
481 for all constraint violations created by this `isValid()` invocation. This includes the default
482 constraint violation, but also all violations created by the `ConstraintViolationBuilder`. You can,
483 however, update the parameters between invocations of
484 `ConstraintViolationBuilder#addConstraintViolation()`.
485 ====
486 * obtain the `TimeProvider` for getting the current time when validating `@Future` and `@Past` constraints
487 (see also <<section-time-provider>>).
488 +
489 This is useful if you want to customize the message of the `@Future` constraint.
490 By default the message is just "must be in the future". <<example-custom-message-parameter>> shows
491 how to include the current date in order to make the message more explicit.
492 +
493 [[example-custom-message-parameter]]
494 .Custom @Future validator with message parameters
495 ====
496 [source, JAVA]
497 ----
498 public class MyFutureValidator implements ConstraintValidator<Future, Date> {
499
500 @Override
501 public void initialize(Future constraintAnnotation) {
502 }
503
504 @Override
505 public boolean isValid(Date value, ConstraintValidatorContext context) {
506 if ( value == null ) {
507 return true;
508 }
509
510 HibernateConstraintValidatorContext hibernateContext = context.unwrap(
511 HibernateConstraintValidatorContext.class
512 );
513
514 Date now = new Date( hibernateContext.getTimeProvider().getCurrentTime() );
515
516 if ( !value.after( now ) ) {
517 hibernateContext.disableDefaultConstraintViolation();
518 hibernateContext.addExpressionVariable( "now", now )
519 .buildConstraintViolationWithTemplate( "Must be after ${now}" )
520 .addConstraintViolation();
521
522 return false;
523 }
524
525 return true;
526 }
527 }
528 ----
529 ====
530 +
531 [WARNING]
532 ====
533 This functionality is currently experimental and might change in future versions.
534 ====
535 * set an arbitrary dynamic payload - see <<section-dynamic-payload>>
536
537 ==== `HibernateMessageInterpolatorContext`
538
539 Hibernate Validator also offers a custom extension of `MessageInterpolatorContext`, namely
540 `HibernateMessageInterpolatorContext` (see <<example-custom-message-interpolator-context>>). This
541 subtype was introduced to allow a better integration of Hibernate Validator into the Glassfish. The
542 root bean type was in this case needed to determine the right classloader for the message resource
543 bundle. If you have any other usecases, let us know.
544
545 [[example-custom-message-interpolator-context]]
546 .`HibernateMessageInterpolatorContext`
547 ====
548 [source, JAVA]
549 ----
550 public interface HibernateMessageInterpolatorContext extends MessageInterpolator.Context {
551
552 /**
553 * Returns the currently validated root bean type.
554 *
555 * @return The currently validated root bean type.
556 */
557 Class<?> getRootBeanType();
558 }
559 ----
560 ====
561
562 [[section-paranamer-parameternameprovider]]
563 === ParaNamer based `ParameterNameProvider`
564
565 Hibernate Validator comes with a `ParameterNameProvider` implementation which leverages the
566 link:http://paranamer.codehaus.org/[ParaNamer] library.
567
568 This library provides several ways for obtaining parameter names at runtime, e.g. based on debug
569 symbols created by the Java compiler, constants with the parameter names woven into the bytecode in
570 a post-compile step or annotations such as the `@Named` annotation from JSR 330.
571
572 In order to use `ParanamerParameterNameProvider`, either pass an instance when bootstrapping a
573 validator as shown in <<example-using-custom-parameter-name-provider>> or specify
574 `org.hibernate.validator.parameternameprovider.ParanamerParameterNameProvider` as value for the
575 `&lt;parameter-name-provider&gt;` element in the _META-INF/validation.xml_ file.
576
577
578 [TIP]
579 ====
580 When using this parameter name provider, you need to add the ParaNamer library to your classpath. It
581 is available in the Maven Central repository with the group id `com.thoughtworks.paranamer` and the
582 artifact id `paranamer`.
583 ====
584
585 By default `ParanamerParameterNameProvider` retrieves parameter names from constants added to the byte
586 code at build time (via `DefaultParanamer`) and debug symbols (via `BytecodeReadingParanamer`).
587 Alternatively you can specify a `Paranamer` implementation of your choice when creating a
588 `ParanamerParameterNameProvider` instance.
589
590 [[section-value-handling]]
591 === Unwrapping values
592
593 Sometimes it is required to unwrap values prior to validating them. For example, in
594 <<example-using-unwrapvalidatedvalue>> a link:http://docs.oracle.com/javafx/[JavaFX] property type
595 is used to define an element of a domain model. The `@Size` constraint is meant to be applied to the
596 string value not the wrapping `Property` instance.
597
598 [[example-using-unwrapvalidatedvalue]]
599 .Applying a constraint to wrapped value of a JavaFX property
600 ====
601 [source, JAVA]
602 ----
603 @Size(min = 3)
604 private Property<String> name = new SimpleStringProperty( "Bob" );
605 ----
606 ====
607
608 [NOTE]
609 ====
610 The concept of value unwrapping is considered experimental at this time and may evolve into more
611 general means of value handling in future releases. Please let us know about your use cases for such
612 functionality.
613 ====
614
615 Bean properties in JavaFX are typically not of simple data types like `String` or `int`, but are
616 wrapped in `Property` types which allows to make them observable, use them for data binding etc. When
617 applying a constraint such as `@Size` to an element of type `Property<String>` without further
618 preparation, an exception would be raised, indicating that no suitable validator for that constraint
619 and data type can be found. Thus the validated value must be unwrapped from the containing property
620 object before looking up a validator and invoking it.
621
622 For unwrapping to occur a `ValidatedValueUnwrapper` needs to be registered for the type
623 requiring unwrapping. Example <<example-implementation-of-validatedvalueunwrapper>> shows how this
624 schematically looks for a JavaFX `PropertyValueUnwrapper`. You just need to extend the SPI class
625 `ValidatedValueUnwrapper` and implement its abstract methods.
626
627 [[example-implementation-of-validatedvalueunwrapper]]
628 .Implementing the ValidatedValueUnwrapper interface
629 ====
630 [source, JAVA]
631 ----
632 public class PropertyValueUnwrapper extends ValidatedValueUnwrapper<Property<?>> {
633
634 @Override
635 public Object handleValidatedValue(Property<?> value) {
636 //...
637 }
638
639 @Override
640 public Type getValidatedValueType(Type valueType) {
641 //...
642 }
643 }
644 ----
645 ====
646
647 The `ValidatedValueUnwrapper` needs also to be registered with the `ValidatorFactory`:
648
649 [[example-registering-validatedvalueunwrapper]]
650 .Registering a ValidatedValueUnwrapper
651 ====
652 [source, JAVA]
653 ----
654 Validator validator = Validation.byProvider( HibernateValidator.class )
655 .configure()
656 .addValidatedValueHandler( new PropertyValueUnwrapper() )
657 .buildValidatorFactory()
658 .getValidator();
659 ----
660 ====
661
662 Several unwrapper implementations can be registered. During constraint validator resolution
663 Hibernate Validator automatically checks whether a `ValidatedValueUnwrapper` exists for the validated
664 value. If so, unwrapping occurs automatically. In some cases, however, constraint validator instances
665 for a given constraint might exist for the wrapper as well as the wrapped value (`@NotNull` for example
666 applies to all objects). In this case Hibernate Validator needs to be explicitly told which value
667 to validate. This can be done via `@UnwrapValidatedValue(true)` respectively
668 `@UnwrapValidatedValue(false)`.
669
670 [NOTE]
671 ====
672 Note that it is not specified which of the unwrapper implementations is
673 chosen when more than one implementation is suitable to unwrap a given element.
674 ====
675
676 Instead of programmatically registering `ValidatedValueUnwrapper` types, the fully-qualified names
677 of one ore more unwrapper implementations can be specified
678 via the configuration property `hibernate.validator.validated_value_handlers` which can be useful when
679 configuring the default validator factory using the descriptor _META-INF/validation.xml_ (see
680 <<chapter-xml-configuration>>).
681
682 [[section-optional-unwrapper]]
683 ==== Optional unwrapper
684
685 Hibernate Validator provides built-in unwrapping for `Optional` introduced in Java 8.
686 The unwrapper is registered automatically in Java 8 environments, and no further configuration is
687 required. An example of unwrapping an `Optional` instance is shown in
688 <<example-using-unwrapvalidatedvalue-and-optional>>.
689
690 [[example-using-unwrapvalidatedvalue-and-optional]]
691 .Unwrapping `Optional` instances
692 ====
693 [source, JAVA]
694 ----
695 @Size(min = 3)
696 private Optional<String> firstName = Optional.of( "John" );
697
698 @NotNull
699 @UnwrapValidatedValue // UnwrapValidatedValue required since otherwise unclear which value to validate
700 private Optional<String> lastName = Optional.of( "Doe" );
701 ----
702 ====
703
704 [NOTE]
705 ====
706 `Optional.empty()` is treated as `null` during validation. This means that for constraints where
707 `null` is considered valid, `Optional.empty()` is similarly valid.
708 ====
709
710 [[section-javafx-unwrapper]]
711 ==== JavaFX unwrapper
712
713 Hibernate Validator also provides built-in unwrapping for JavaFX property values. The unwrapper is
714 registered automatically for environments where JavaFX is present, and no further configuration is
715 required. `ObservableValue` and its sub-types are supported.
716 An example of some of the different ways in which `JavaFX` property values can be unwrapped is
717 shown in <<example-using-unwrapvalidatedvalue-and-javafx>>.
718
719 [[example-using-unwrapvalidatedvalue-and-javafx]]
720 .Unwrapping `JavaFX` properties
721 ====
722 [source, JAVA]
723 ----
724 @Min(value = 3)
725 IntegerProperty integerProperty1 = new SimpleIntegerProperty( 4 );
726
727 @Min(value = 3)
728 Property<Number> integerProperty2 = new SimpleIntegerProperty( 4 );
729
730 @Min(value = 3)
731 ObservableValue<Number> integerProperty3 = new SimpleIntegerProperty( 4 );
732 ----
733 ====
734
735 ==== Unwrapping object graphs
736
737 Unwrapping can also be used with object graphs (cascaded validation) as shown in
738 <<example-using-unwrapvalidatedvalue-and-optional-with-valid>>.
739 When validating the object holding the `Optional<Person>`, a cascaded validation of the `Person`
740 object would be performed.
741
742 [[example-using-unwrapvalidatedvalue-and-optional-with-valid]]
743 .Unwrapping `Optional` prior to cascaded validation via `@Valid`
744 ====
745 [source, JAVA]
746 ----
747 @Valid
748 private Optional<Person> person = Optional.of( new Person() );
749 ----
750 [source, JAVA]
751 ----
752 public class Person {
753 @Size(min =3)
754 private String name = "Bob";
755 }
756 ----
757 ====
758
759 [[section-constraint-definition-contribution]]
760 === Providing constraint definitions
761
762 Bean Validation allows to (re-)define constraint definitions via XML in its constraint mapping
763 files. See <<section-mapping-xml-constraints>> for more information and <<example-constraints-car>>
764 for an example. While this approach is sufficient for many use cases, it has it shortcomings
765 in others. Imagine for example a constraint library wanting to contribute constraint
766 definitions for custom types. This library could provide a mapping file with their library, but this
767 file still would need to be referenced by the user of the library. Luckily there are better ways.
768
769 [NOTE]
770 ====
771 The following concepts are considered experimental at this time. Let us know whether you find them
772 useful and whether they meet your needs.
773 ====
774
775 ==== Constraint definitions via `ServiceLoader`
776
777 Hibernate Validator allows to utilize Java's
778 link:http://docs.oracle.com/javase/8/docs/api/java/util/ServiceLoader.html/[ServiceLoader]
779 mechanism to register additional constraint definitions. All you have to do is to add the file
780 _javax.validation.ConstraintValidator_ to _META-INF/services_. In this service file you list the
781 fully qualified classnames of your constraint validator classes (one per line). Hibernate Validator
782 will automatically infer the constraint types they apply to.
783 See <<example-using-service-file-for-constraint-definitions,Constraint definition via service file>>
784 for an example.
785
786 [[example-using-service-file-for-constraint-definitions]]
787 ._META-INF/services/javax.validation.ConstraintValidator_
788
789 ====
790 [source]
791 ----
792 # Assuming a custom constraint annotation @org.mycompany.CheckCase
793 org.mycompany.CheckCaseValidator
794 ----
795 ====
796
797 To contribute default messages for your custom constraints, place a file _ContributorValidationMessages.properties_
798 and/or its locale-specific specializations at the root your JAR. Hibernate Validator will consider the
799 entries from all the bundles with this name found on the classpath in addition to those given in _ValidationMessages.properties_.
800
801 This mechanism is also helpful when creating large multi-module applications: Instead of putting all the constraint
802 messages into one single bundle, you can have one resource bundle per module containing only those messages of that module.
803
804 [[section-programmatic-constraint-definition]]
805 ==== Adding constraint definitions programmatically
806
807 While the service loader approach works in many scenarios, but not in all (think for example
808 OSGi where service files are not visible), there is yet another way of contributing constraint
809 definitions. You can use the programmatic constraint declaration API - see
810 <<example-using-constraint-definition-api>>.
811
812 [[example-using-constraint-definition-api]]
813 .Adding constraint definitions through the programmatic API
814 ====
815 [source, JAVA, indent=0]
816 ----
817 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=constraintDefinition]
818 ----
819 ====
820
821 Instead of directly adding a constraint mapping to the configuration object, you may use a `ConstraintMappingContributor`
822 as detailed in <<section-programmatic-api-contributor>>. This can be useful when
823 configuring the default validator factory using _META-INF/validation.xml_ (see
824 <<chapter-xml-configuration>>).
825
826 [TIP]
827 ====
828 One use case for registering constraint definitions through the programmatic API is the ability to specify an alternative
829 constraint validator for the `@URL` constraint. Historically, Hibernate Validator's default constraint
830 validator for this constraint uses the `java.net.URL` constructor to validate an URL.
831 However, there is also a purely regular expression based version available which can be configured using
832 a `ConstraintDefinitionContributor`:
833
834 .Using the programmatic constraint declaration API to register a regular expression based constraint definition for `@URL`
835 [source, JAVA, indent=0]
836 ----
837 include::{sourcedir}/org/hibernate/validator/referenceguide/chapter11/constraintapi/ConstraintApiTest.java[tags=urlValidationOverride]
838 ----
839 ====
840
841 [[section-constraint-customizing-class-loading]]
842 === Customizing class-loading
843
844 There are several cases in which Hibernate Validator needs to load resources or classes given by name:
845
846 * XML descriptors (_META-INF/validation.xml_ as well as XML constraint mappings)
847 * classes specified by name in XML descriptors (e.g. custom message interpolators etc.)
848 * the _ValidationMessages_ resource bundle
849 * the `ExpressionFactory` implementation used for expression based message interpolation
850
851 By default Hibernate Validator tries to load these resources via the current thread context classloader.
852 If that's not successful, Hibernate Validator's own classloader will be tried as a fallback.
853
854 For cases where this strategy is not appropriate (e.g. modularized environments such as OSGi),
855 you may provide a specific classloader for loading these resources when bootstrapping the validator factory:
856
857 [[example-using-external-class-loader]]
858 .Providing a classloader for loading external resources and classes
859 ====
860 [source, JAVA]
861 ----
862 ClassLoader classLoader = ...;
863
864 Validator validator = Validation.byProvider( HibernateValidator.class )
865 .configure()
866 .externalClassLoader( classLoader )
867 .buildValidatorFactory()
868 .getValidator();
869 ----
870 ====
871
872 In the case of OSGi, you could e.g. pass the loader of a class from the bundle bootstrapping Hibernate Validator
873 or a custom classloader implementation which delegates to `Bundle#loadClass()` etc.
874
875 [NOTE]
876 ====
877 Call `ValidatorFactory#close()` if a given validator factory instance is not needed any longer.
878 Failure to do so may result in a classloader leak in cases where applications/bundles are re-deployed and a non-closed
879 validator factory still is referenced by application code.
880 ====
881
882 [[section-time-provider]]
883 === Time providers for @Future and @Past
884
885 By default the current system time is used when validating the `@Future` and `@Past` constraints.
886 In some cases it can be necessary though to work with another "logical" date rather than the system time,
887 e.g. for testing purposes or in the context of batch applications which may require to run with
888 yesterday's date when re-running a failed job execution.
889
890 To address such scenarios, Hibernate Validator provides a custom contract for obtaining the current time, `TimeProvider`.
891 <<example-using-time-provider>> shows an implementation of this contract and its registration when bootstrapping a validator factory.
892
893 [[example-using-time-provider]]
894 .Using a custom `TimeProvider`
895 ====
896 [source, JAVA]
897 ----
898 public class CustomTimeProvider implements TimeProvider {
899
900 @Override
901 public long getCurrentTime() {
902 Calendar now = ...;
903 return now.getTimeInMillis();
904 }
905 }
906 ----
907 [source, JAVA]
908 ----
909 ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
910 .configure()
911 .timeProvider( timeProvider )
912 .buildValidatorFactory();
913 ----
914 ====
915
916 Alternatively, you can specify the fully-qualified classname of a `TimeProvider` implementation using the property
917 `hibernate.validator.time_provider` when configuring the default validator factory via _META-INF/validation.xml_
918 (see <<chapter-xml-configuration>>).