Constraint declarations

The bean validation specification has built-in constraints that cover the common constraints that a developer will encounter, albeit for basic validation.

Elements of a constraint

An annotated constraint in bean validation is declared through the key annotation @javax.validation.contraints.Constraint and three other properties.

Message property

The message property specifies the text and/or the Expression Language statement that the validation engine will use or evaluate when the constraint is violated.

String message() default  "{je7hb.beanvalidation.essentials.PostalCode.message}";

The annotation property message defines a default resource in order to look up the validation error message. For internationalization purposes, validation error messages are read by the class java.util.ResourceBundle through language specific property files.

Groups property

The groups property specifies the group of violation that this constraint belongs to. This is set by the developer, to control and configure partial validations and groups of validations, applied to value objects.

Class<?>[] groups() default {};

Groups are defined by Java class references and the default value is an empty array. This annotation property group allows validation constraints to be collected together in a named association. In this case, there is no group specified.

Payload property

The payload property defines the object instances, which are associated with the constraint. The payload is an advanced concept, which allows the validation client to associate metadata information with the constraint declaration. Payloads are not portable to different validators, usually.

Class<? extends Payload>[] payload() default {};

The default value is an empty array. The Payload instance is an empty marker interface to some custom opaque object instance and thus illustrates perfectly the non-portability of this annotation property.

List of built-in constraints

Let us look now at the default built-in constraints for Bean Validation 1.1:

Constraint name

Description

Allowed types

@Null

Specifies the element must be a null reference pointer.

Any

@NotNull

Specifies the element must not be a null reference pointer.

Any

@AssertTrue

Specifies the element must be true

Boolean and boolean

@AssertFalse

Specifies the element must be false

Boolean and boolean

@Min

Specifies the element must be a number value that is greater than or equal to the minimum value supplied. Because of floating arithmetic rounding errors float and double are not supported.

BigDecimal, BigInteger, byte, short, int, and long

@Max

Specifies the element must be a number value that is less than or equal to the minimum value supplied. Because of floating arithmetic rounding errors float and double are not supported.

BigDecimal, BigInteger, byte, short, int, and long

@DecimalMin

Similar to @Min but adds the ability to set the value as String parameter. The number value must be greater than or equal to the supplied value. FP restriction also applies here.

BigDecimal, BigInteger,

CharSequence, byte, short, int, and long

@DecimalMax

Similar to @Max but adds the ability to set the value as String parameter. The number value must be less than or equal to the supplied value. FP restriction also applies here.

BigDecimal, BigInteger,

CharSequence, byte, short, int, and long

@Size

The element's size must be inside the supplied inclusive boundary limits.

CharSequence, Collection, Map and primitive array

@Digits

The element is a number within an accepted range that defines the maximum digits for the integer portion of the number and the maximum digits for the fraction portion of the number.

BigDecimal, BigInteger,

CharSequence, byte, short, int, and long

@Past

The element must be dated in the past according to the current time of the Java Virtual Machine.

java.util.Date and java.util.Calendar

@Future

The element must be dated in the future according to the current time of the Java Virtual Machine.

java.util.Date and java.util.Calendar

@Pattern

The element must match against a supplied regular expression pattern that conforms to the Java convention.

CharSequence

The annotations @DecimalMin and @DecimalMax both have an inclusive parameter that is by default set to true.

Many constraint annotations now also accept a CharSequence instance and therefore an application can also validate on StringBuilder.

In the quick example, we already saw some of these constraints @NotNull, @Min and @Max in action. All of the default constraints are runtime annotations. They can be applied to Java constructors, fields, methods, method parameters, and other annotation types.

Hibernate Validator built-in constraints

The reference implementation, Hibernate Validator, also has built-in constraints that are part of the specification 1.1.

Constraint Name

Description

Allowed Types

@CreditCardNumber

Specifies the element must be a match for standard credit card account number.

CharSequence

@Email

Specifies the element must be a valid well-formed email address.

CharSequence

@Length

Specifies the string length is between a minimum and maximum inclusive.

CharSequence

@NotBlank

Specifies the string is not blank or null.

CharSequence

@NotEmpty

Specifies the element collection or string is not empty.

CharSequence, Collection, Map and primitive array

@Range

Specifies the element must be the range between minimum and maximum inclusive values.

BigDecimal, BigInteger,

CharSequence, byte, short, int, and long

@SafeHtml

Specifies the element text is an HTML without script elements or malicious code.

CharSequence

@URL

Specifies the element test is a valid well-formed URL.

CharSequence

These annotations are found under the Java package org.hibernate.validator.constraints.

Constraint violations

The method validate() on the Validator class returns a set collection of ConstraintViolation instances. Constraints are designed to be declared just once and allow the client to execute them anywhere in the application code.

The standardized ConstraintViolation looks like this:

package javax.validation;
import javax.validation.metadata.ConstraintDescriptor;

public interface ConstraintViolation<T> {
  String getMessage();
  String getMessageTemplate();
  T getRootBean();
  Class<T> getRootBeanClass();
  Object getLeafBean();

  // Since 1.1
  Object[] getExecutableParameters();
  // Since 1.1
  Object getExecutableReturnValue();

  Path getPropertyPath();
  Object getInvalidValue();
  ConstraintDescriptor<?> getConstraintDescriptor();

  // Since 1.1
  <U> U unwrap(Class<U> type);
}

The violation can be interrogated for the tokenized message getMessage() and the raw text getMessageTemplate() before post processing for internationalization and formatting. The method getRootBean() informs the application which bean is ultimately the container or common master of the violation. The getLeafBean() returns the bean that contains the failure.

The application can retrieve the actual value that caused the violation with getInvalidValue(). The getPropertyPath() method retrieves the node path of the navigation properties to get from the root bean (value object) to the leaf bean (dependent value object). The Path is a Java interface that represents the navigation path from one object to another in an object graph. The data structure is based on the chain of individual node elements.

As Bean Validation 1.1, it is possible to retrieve the execution parameters and return through the calls getExecutableParameter() and getExecutableReturnValue(). These calls were introduced to support method validation.

There is a special method called unwrap() that allows applications to gain access to opaque specific provider data and additional proprietary API. Of course, the use of this means that your resultant code is not portable from, say, Hibernate Validator to another implementation. On the other hand, the specification permits providers to add custom behavior.

Finally, it is possible to retrieve the meta-data around the constraint descriptor associated with this constraint with a call to getConstraintDescriptor(). This call is designed to help the developer write custom validator annotations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.177.86