Showing posts with label Bean Validation. Show all posts
Showing posts with label Bean Validation. Show all posts

Wednesday, August 29, 2012

Bookmark and Share

Note: This post originally appeared on beanvalidation.org. Please post any feedback over there.

Now that everybody is returning from their summer holidays, also the Bean Validation team is getting back to their desks in order to work with full steam towards revision 1.1.

As you know, the largest new feature will be method validation, that is the validation of method parameters and return values using constraint annotations. Bean Validation 1.1 early draft 1 lays the ground for this, and right now we're tackling some advanced questions still open in that area (btw. if you haven't yet tried out the reference implementation of ED1, this is the perfect time to do so and give us your feedback).

The problem

One question the EG currently is discussing is whether and, if so, how a refinement of method constraints should be allowed in sub-types. That is, if a class implements a method of an interface or overrides a method from a super class, should the sub-type be allowed to place any additional constraints?

The current draft defines the following rules for such cases (see the draft document for all the gory details):

  • No parameter constraints may be specified in addition to those constraints defined on the method in the interface or super class.
  • Return value constraints may be added in sub-types.

The rationale

The rationale behind this is the principle of behavioral sub-typing, which demands that wherever a given type T is used, it should be possible to replace T with a sub-type S of T. This means that a sub-type must not strengthen a method's preconditions (by adding parameter constraints), as this might cause client code working correctly against T to fail when working against S. A sub-type may also not weaken a method's postconditions. However, a sub-type may strengthen the method's postconditions (by adding return value constraints), as client code working against T still will work against S.

Can you show me some code, please?

To give you an example, the following shows a constraint declaration considered illegal as of the current draft, as parameter constraints are added to the placeOrder() method in a sub-class of OrderService:

1
2
3
4
5
6
7
8
9
10
11
12
public class OrderService {
    void placeOrder(@NotNull String customerCode, @NotNull Item item, int quantity) { ... }
}

public class SimpleOrderService extends OrderService {

    @Override
    public void placeOrder(
        @Size(min=3, max=20) String customerCode,
        Item item,
        @Min(1) int quantity) { ... }
}

Alternatives

While this approach works, follows principles of clean OO design and also is employed by other Programming by Contract solutions, some voices in the EG expressed doubts whether the handling of parameter constraints isn't too restrictive and thus may limit innovation in that area. In particular with respect to legacy code, the question was raised whether it shouldn't be allowed to add parameter constraints in sub-types.

One example may be a legacy interface, which technically has no constraints (that is, no parameter constraints are placed on its methods), but comes with a verbal description of preconditions in its documentation. In this case an implementor of that interface might wish to implement this contract by placing corresponding constraint annotations on the implementation.

An open question in this situation is what should the behavior be if the interface is being constrained afterwards?

Give use your feedback!

So what do you think, should such a refinement of parameter constraints be allowed or not? Possible alternatives:

  • allow such a refinement by default
  • have some sort of switch controlling the behavior (either standardized or provider-specific)

As there are pro's and con's of either approach, we'd very interested in user feedback on this.

Let us know what you think by posting a comment directly to this blog, shooting a message to the mailing list or participating in this Doodle vote. Which use cases you have encountered come to mind where the possibility to refine parameter constraints may help you?

Monday, August 1, 2011

Bookmark and Share

Maybe you know it already: last week JSR 349 successfully passed the review ballot, meaning that the work on a new release of the Bean Validation API has officially started.

I'm really excited about this, because I've got the pleasure to be part of the JSR 349 expert group. I haven't been member of such a comitee before, so I guess this will be exciting times and I'll surely learn a whole lot of new things during the work on the specification.

What's most important right now is your feedback: what new features would you like to see included in Bean Validation 1.1, what problems did you face when working with BV 1.0 which you think should be addressed in the next release?

Your input and feedback is highly welcome at several places:

  • The Bean Validation feedback forum is a good platform for discussing ideas, requests for clarifications etc.
  • For concrete feature requests or bug reports you can open an issue at the Bean Validation issue tracker

As a starting point you might want to check out these two blog posts by Emmanuel Bernard (the Bean Validation spec. lead), where a lot of possible features are discussed.

Finally I'd like to point your attention to http://beanvalidation.org/, the JSR's official web site. There you'll find everything related, e.g. a news section, the road map and also the Bean Validation 1.0 spec. document for reference.

Now it's up to you – tell us what would YOU like to see included in Bean Validation 1.1.

Sunday, May 8, 2011

Bookmark and Share

Note: This article originally appeared on in.relation.to as part of the Seam Module Spotlight series. In order to spread the word on Seam Validation I thought it might be a good idea to post it in this blog, too.

Seam Validation is a relatively new Seam module which provides an integration between Hibernate Validator which is the reference implementation of the Bean Validation standard (JSR 303) and CDI. The module's functionality falls into two areas:

  • Enhanced dependency injection services for validators, validator factories and constraint validators
  • Automatic validation of method parameters and return values based on Hibernate Validator's method validation API

Let's take a closer look at these features in the following.

Dependency injection services

The Bean Validation API is an integral part of the Java EE platform. So when running on a Java EE 6 compatible application server such as JBoss AS 6 you can easily retrieve Validator and ValidatorFactory instances via dependency injection.

Unfortunately this is not working out of the box when running in non-EE environments such as plain servlet containers. But don't worry, Seam Validation comes to the rescue. By adding the module as dependency to your project, validators and validator factories can be obtained using @Inject:

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Foo {

    @Inject
    private Validator validator;

    public void doSomething() {

        Bar bar = new Bar();

        Set<ConstraintViolation<Bar>> constraintViolations = validator.validate(bar);
        //examine the violations ...
    }
}

But Seam Validation goes one step further and enables dependency injection also within constraint validator implementations. For instance we might have a custom constraint @ValidLicensePlate which is used to ensure that a car has a license plate which is properly registered, still valid etc.:

1
2
3
4
5
6
7
public class Car {

    @ValidLicensePlate
    private String licensePlate;

    //constructor, getter, setter etc.
}

In order to perform the required checks the constraint's validator invokes some sort of registration service (note: accessing external services can potentially be an expensive operation, so it may be a good idea to put the constraint into a separate validation group, but that's out of scope for this article). The Seam Validation module allows to inject this service into the validator as into any other CDI bean:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class ValidLicensePlateValidator implements ConstraintValidator<ValidLicensePlate, String> {

    @Inject
    private RegistrationService registrationService;

    @Override
    public void initialize(ValidLicensePlate constraintAnnotation) {
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {

        if (value == null) {
            return true;
        }

        //delegate to registration service
        return registrationService.isValid(value);
    }
}

There is just on more step required before the @ValidLicensePlate constraint can be used: We have to register Seam Validation's constraint validator factory with the Bean Validation provider. This happens by putting a file named validation.xml with the following content into the META-INF folder of the application:

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="UTF-8"?>
<validation-config 
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd">

    <constraint-validator-factory>
        org.jboss.seam.validation.InjectingConstraintValidatorFactory
    </constraint-validator-factory>
</validation-config>

Method validation

The other main feature of Seam Validation besides dependency injection is the automatic validation of method parameters and return values based on the API for method validation introduced with Hibernate Validator 4.2 (note: at the time of writing Hibernate Validator 4.2 is released as Beta version, but no major changes are expected until the final release).

This API provides an easy-to-use facility for the "Programming by Contract" approach to program design based on the concepts defined by the Bean Validation API. That means that any Bean Validation constraint can be used to describe

  • the preconditions that must be met before a method may be invoked (by annotating method parameters with constraints) and
  • the postconditions that are guaranteed after a method invocation returns (by annotating methods).

Things should become clearer with an example:

1
2
3
4
5
6
7
8
9
@AutoValidating
public class RentalStation {

    @Valid
    public Car rentCar(@NotNull CustomerPK customerPK, @NotNull @Future Date startDate, @Min(1) int durationInDays) {

        //highly complex car rental business logic ...
    }
}

Here the following pre- and postconditions are applied onto the rentCar() method:

  • The customer's primary key may not be null
  • The rental start date must not be null and must be in the future
  • The rental duration must be at least one day
  • The returned object must be valid with respect to all constraints of the Car class

By annotating the class RentalStation with @AutoValidating, all these constraints are automatically validated by a method interceptor whenever the rentCar() method is invoked. If any of the constraints can't be validated successfully, a runtime exception describing the occurred constraint violation(s) is thrown.

This approach has several advantages over traditional parameter and return value checking:

  • The checks don't have to be performed by hand. This results in less boiler-plate code to write (and to read).
  • A method's pre- and postconditions are part of its API and generated documentation. It's not necessary to add comments such as "returns never null", as this information will automatically be put into the generated JavaDoc. This results in less redundancies and hence in less potential inconsistencies between implementation and documentation.

Future steps

This concludes our short tour through the Seam Validation module. If you feel like trying out the module yourself, the module home page is the right starting point. You might also be interested in the module's reference guide, and in case you found a bug or want to create a feature request the module's JIRA instance is the place to go.

Possible future developments of Seam Validation include a closer integration with other Seam 3 modules, the possibility to chose the validation groups to be used for method validation and the evaluation of standard bean constraints upon method validation.

Sunday, January 16, 2011

Bookmark and Share

Earlier this week the first beta version of Hibernate Validator 4.2 was released. Hardy's announcement on in.relation.to describes in detail what's new in this release, so be sure to check it out.

One of the new features I'm really excited about is method validation, which I therefore would like to discuss in more detail in the following.

What's it about?

Up to now constraint annotations were only supported at fields or at getter methods for property constraints and at type declarations for class-level constraints.

With HV 4.2 it is now also possible to use constraint annotations for a programming style known as "Programming by Contract". More specifically this means that any Bean Validation constraints (built-in as well as custom constraints) can be used to specify

  • any preconditions that must be met before a method invocation (by annotating method parameters with constraints) and
  • any postconditions that are guaranteed after a method invocation (by annotating methods)

As example let's consider the following class from a fictitious video rental application:

1
2
3
4
5
6
7
8
9
public class MovieRepository {

    public @NotNull Set<Movie> findMoviesByTitle( 
        @NotNull @Size(min = 3) String title) {

        //search movie in database ...
    }   

}

The following pre- and postconditions will hold here (provided the method validation is triggered automatically by some integration layer, see below):

  • The title parameter is guaranteed to be not null and at least 3 characters long
  • The return set of movies is guaranteed to be not null

Compared to traditional ways of parameter or result value checking this approach has two big advantages:

  • These checks don't have to be performed manually, which results in less code to write and maintain. You'll never again have to throw IllegalArgumentExceptions or similar by hand.
  • The pre- and postconditions of a method don't have to be expressed again in the method's JavaDoc, since any of it's annotations will automatically be included in the generated JavaDoc. This means less redundancy which reduces the chance of inconsistencies between implementation and comments.

Method validation is not restricted to constraints related to parameters or to return values themselves. Using the @Valid annotation it is also possible to recursively validate parameters or return values:

1
2
3
4
5
6
7
8
public class UserRepository {

    public void persistUser(@NotNull @Valid User user) {

        //persist user in database ...
    }   

}

In this example not only the @NotNull constraint at the user parameter would be checked, but also any constraints defined at the User type. As known from standard Bean Validation the @Valid annotation could also be applied to array-, Iterable- and Map-typed parameters or return values.

The MethodValidator interface

For the purposes of method validation Hibernate Validator defines the new interface MethodValidator (any type or method names are working titles and might change until HV 4.2 is final), which provides methods for parameter and return value validation:

1
2
3
4
5
6
7
8
9
10
11
12
13
public interface MethodValidator {

    public <T> Set<MethodConstraintViolation<T>> validateParameter(
        T object, Method method, Object parameterValue, 
        int parameterIndex, Class<?>... groups);

    public <T> Set<MethodConstraintViolation<T>> validateParameters(
        T object, Method method, Object[] parameterValues, Class<?>... groups);

    public <T> Set<MethodConstraintViolation<T>> validateReturnValue(
        T object, Method method, Object returnValue, Class<?>... groups);

}

To get hold of a method validator, unwrap an instance of HV's Validator implementation as follows:

1
2
3
4
5
MethodValidator validator = Validation.byProvider( HibernateValidator.class )
    .configure()
    .buildValidatorFactory()
    .getValidator()
    .unwrap( MethodValidator.class );

All of MethodValidator's methods return a set of MethodConstraintValidations which describe in detail any constraint violations that occurred during validation. MethodConstraintValidation extends the standard ConstraintViolation and provides additional information such as method and parameter causing a constraint violation:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public interface MethodConstraintViolation<T> extends ConstraintViolation<T> {

    public static enum Kind {

        PARAMETER,

        RETURN_VALUE
    }

    Method getMethod();

    Integer getParameterIndex();

    String getParameterName();

    Kind getKind();
}

Unfortunately the byte code of a Java program normally doesn't contain any information on parameter names, therefore getParameterName() for now returns synthetic names such as arg0 etc. For a future release we are investigating approaches for parameter naming, e.g. by leveraging JSR 330's @Named annotation. I created a JIRA issue for this, so if you have any feedback on this just add a comment to the ticket.

Triggering method validation

Hibernate Validator itself only provides the engine for method validation but it does not deal with triggering such a validation.

Instead this is typically done using frameworks/APIs which provide AOP or method interception services such as AspectJ or CDI. But also plain Java dynamic proxies can basically do the trick.

Typically such a validation interceptor does the following:

  • intercept each method call to be validated,
  • validate the invocation's parameter values,
  • proceed with the method invocation and
  • finally validate the invocation's return value.

If any of the two validation steps yields one ore more constraint violations the interceptor typically throws a MethodConstraintViolationException containing the constraint violations that have occurred.

Trying it out yourself

To see whether method validation works out as intended I started a project at GitHub called methodvalidation-integration which provides validation handlers for some interception technologies popular these days.

Currently there are implementations for CDI as well as Google Guice and an InvocationHandler which can be used with JDK dynamic proxies. I also plan to add support for Spring AOP/AspectJ when time permits.

To try method validation out yourself just get the bits from GitHub and have a look at the test in each of the sub-projects. Just give it a try and let me know how everything works.

Future steps

This post introduced the new method validation feature which will be part of Hibernate Validator 4.2. The first beta release contains the basic implementations of this, so we are more than interested in you feedback on this. Please report any bugs in HV's JIRA instance, any questions or ideas for improvement are also highly welcome in HV's forum.

For HV 4.2 Beta2 we plan to add documentation on the method validation feature to HV's reference guide which will also describe some advanced topics such as using method validation with group sequences etc. We will also add support for method level constraints to the constraint meta-data API.

Two further ideas scheduled for after 4.2 are providing the ability to specify method level constraints using XML and using the programmatic constraint configuration API.

Monday, December 27, 2010

Bookmark and Share

One of the new features introduced with version 3.0 of the Spring framework is the Spring Expression Language or short "SpEL". This language is tailored for the needs when working with Spring and can be used when creating XML/annotation based Spring bean definitions for instance.

So I thought it would be nice if it was possible to use SpEL together with Hibernate Validator's @ScriptAssert constraint which allows to express validation routines using script or expression languages.

Unfortunately this does not work since currently no SpEL language binding for JSR 223 ("Scripting for the JavaTM Platform") exists. As @ScriptAssert's validator uses JSR 223 for expression evaluation at least for now SpEL can't be used along with @ScriptAssert (there is an issue in Spring's JIRA addressing this problem).

But as shown in previous posts it is very simple to create new constraint annotations for the Bean Validation API. So the idea is to build a new constraint @SpelAssert which resembles HV's @ScriptAssert but works with SpEL instead of the JSR 223 API.

Defining the annotation type is straight-forward:

1
2
3
4
5
6

7
8
9
10
11
12
13
14
15

@Target({ TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = SpelAssertValidator.class)
@Documented
public @interface SpelAssert {


    String message() default "{de.gmorling.moapa.bvspel.SpelAssert.message}";

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


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

    String value();


}

Besides the standard attributes message(), groups() and payload() mandated by the BV specification we define one more attribute value(), which takes the SpEL expression to evaluate.

Now let's come to the validator:

1
2
3
4
5
6

7
8
9
10
11
12
13
14
15

16
17
18
19
20
21
22
23
24

25
26
27
28
29
30
31
public class SpelAssertValidator implements

ConstraintValidator<SpelAssert, Object> {

    @Inject
    private ExpressionParser parser;

    private Expression expression;


    @Override
    public void initialize(SpelAssert constraintAnnotation) {

    String rawExpression = constraintAnnotation.value();


        if (rawExpression == null) {
            throw new IllegalArgumentException("The expression specified in @"

                + SpelAssert.class.getSimpleName() + " must not be null.");
        }

        expression = parser.parseExpression(rawExpression);
    }


    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        if (value == null) {

            return true;
        }

        return Boolean.TRUE.equals(expression.getValue(value, Boolean.class));

    }
}

In initialize() we use an ExpressionParser to parse the specified SpEL expression (so this happens only once) and evaluate the given object against it in isValid().

But wait a minute, where does the ExpressionParser come from, it is not instantiated here?

Right, the cool thing is Spring comes with it's own ConstraintValidatorFactory which performs dependency injection on constraint validators. A validator relying on that feature of course is not portable, but as this validator is based on SpEL and Spring anyways this is not an issue here.

In order to have this working a parser bean must be part of the Spring application context. We just register a SpelExpressionParser:

1

2
3
4
5
6
7
8
9
10

11
12
<beans 
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="parser"
        class="org.springframework.expression.spel.standard.SpelExpressionParser"/>


    <bean id="validator"
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
</beans>

This context also shows how to provide a BV Validator for dependency injection leveraging Spring's LocalValidatorFactoryBean.

Now let's have a look at the @SpelAssert constraint in action. The following shows the canonical example of a class CalendarEvent where the start date shall always be earlier than the end date:

1

2
3
4
5
6
7
8
9
10

@SpelAssert("startDate < endDate")
public class CalendarEvent {


    private Date startDate;

    private Date endDate;


    // getters, setters etc.

}

Note how SpEL allows dates to be compared using the "<" operator and that no alias for the evaluated bean is required, as all unqualified attribute/method names are resolved against the annotated object.

Finally we should have a test showing that the validator works as expected by validating a valid and an invalid CalendarEvent instance:

1
2
3
4
5
6
7
8

9
10
11
12
13
14
15
16
17

18
19
20
21
22
23
24
25
26

27
28
29
30
31
32
33
34
35

36
37
38
39
40
41
42
43
44

45
46
47
48
49
50
@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration
public class SpelAssertTest {

    @Inject
    private Validator validator;


    private Date startDate;
    private Date endDate;

    @Before

    public void setUpDates() {

        Calendar start = Calendar.getInstance();
        start.set(2010, 13, 24);

        startDate = start.getTime();

        Calendar end = Calendar.getInstance();
        end.set(2010, 13, 26);

        endDate = end.getTime();
    }

    @Test
    public void validEvent() {


        CalendarEvent event = new CalendarEvent();
        event.setStartDate(startDate);
        event.setEndDate(endDate);

        assertTrue(validator.validate(event).isEmpty());

    }

    @Test
    public void invalidEventYieldsConstraintViolation() {

        CalendarEvent event = new CalendarEvent();

        event.setStartDate(endDate);
        event.setEndDate(startDate);

        Set<ConstraintViolation<CalendarEvent>> violations = 
            validator.validate(event);

        assertEquals(1, violations.size());

        ConstraintViolation<CalendarEvent> violation = 
            violations.iterator().next();
        assertEquals(

            "SpEL expression \"startDate < endDate\" didn't evaluate to true.",
            violation.getMessage());
    }

}

The complete sources for this post can be found at GitHub, so don't hesistate to give it a try or use it in your projects if you like. Any feedback or ideas for improvement are warmly welcome.

Monday, June 28, 2010

Bookmark and Share

I'm very proud to report that today Hibernate Validator 4.1.0 Final has been released. Besides many bug fixes this release adds also a lot of new features to the code base.

The changes fall into four areas, which I'm going to discuss in detail in the following:

  • New constraint annotations
  • ResourceBundleLocator API
  • API for programmatic constraint creation
  • Constraint annotation processor

New constraint annotations

In addition to the constraints defined in the Bean Validation spec and those custom constraints already part of HV 4.0, the new release ships with the following new constraint annotations:

  • @CreditCardNumber: Validates that a given String represents a valid credit card number using the Luhn algorithm. Useful to detect mis-entered numbers for instance.
  • @NotBlank: Validates that a given String is neither null nor empty nor contains only whitespaces.
  • @URL: Validates that a given String is a valid URL. Can be restricted to certain protocols if required: @URL(protocol = "http") private String url;
  • @ScriptAssert: Allows to use scripting or expression languages for the definition of class-level validation routines.

Let's have a closer look at the @ScriptAssert constraint, which I'm particularly excited about as I have implemented it :-).

The intention behind it is to provide a simplified way for expressing validation logic that is based on multiple attributes of a given type. Instead of having to implement dedicated class-level constraints the @ScriptAssert constraint allows to express such validation routines in an ad hoc manner using a wide range of scripting and expression languages.

In order to use this constraint an implementation of the Java Scripting API as defined by JSR 223 ("Scripting for the JavaTM Platform") must be part of the class path. This is automatically the case when running on Java 6. For older Java versions, the JSR 223 RI can be added manually to the class path.

As example let's consider a class representing calendar events. The start date of such an event shall always be earlier than the end date. Using JavaScript (for which an engine comes with Java 6) this requirement could be expressed as follows:

1
2
3
4
5
6
7
8
9
@ScriptAssert(lang = "javascript", script = "_this.startDate.before(_this.endDate)")
public class CalendarEvent {

    private Date startDate;

    private Date endDate;

    //...
}

So all you have to do is to specify a scripting expression returning true or false within the script attribute. The expression must be implemented in the language given within the language attribute. The language name must be the language's name as registered with the JSR 223 ScriptEngineManager. Within the expression the annotated element can be accessed using the alias _this by default.

The cool thing is that the @ScriptConsert constraint can be used with any other scripting language for which a JSR 223 binding exists. Let's take JEXL from the Apache Commons project for instance. Using Maven you only have to add the following dependency:

1
2
3
4
5
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-jexl</artifactId>
    <version>2.0.1</version>
</dependency>

With JEXL dates can be compared using the "<" operator. Using a shorter alias for the evaluated object the constraint from above therefore can be rewritten as follows:

1
2
3
4
5
6
7
8
9
@ScriptAssert(lang = "jexl", script = "_.startDate < _.endDate", alias = "_")
public class CalendarEvent {

    private Date startDate;

    private Date endDate;

    //...
}

Very likely one will work with only one scripting language throughout all @ScriptAssert constraints of an application. So let's leverage the power of constraint composition to create a custom constraint which allows for an even more compact notation by setting the attributes lang and alias to fixed values:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Target({ TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = {})
@Documented
@ScriptAssert(lang = "jexl", script = "", alias = "_")
public @interface JexlAssert {

    String message() default "{org.hibernate.validator.constraints.ScriptAssert.message}";

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

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

    @OverridesAttribute(constraint = ScriptAssert.class, name = "script")
    String value();
}

Note how the script attribute of the composing @ScriptAssert constraint is overridden using the @OverridesAttribute meta-annotation. Using this custom constraint the example finally reads as follows:

1
2
3
4
5
6
7
8
9
@JexlAssert("_.startDate < _.endDate")
public class CalendarEvent {

    private Date startDate;

    private Date endDate;

    //...
}

As shown the @ScriptAssert constraint allows to define class-level constraints in a very compact way.

But there is also a price to pay. As scripting languages are used, compile-time type-safety is lost. When for instance the startDate attribute is renamed the script expression would have to be adapted by hand. Also evaluation performance should be considered when validation logic is getting more complex.

So I recommend to try it out and choose what ever fits your needs best.

The ResourceBundleLocator API

The Bean Validation API defines the MessageInterpolator interface which allows to plug in custom strategies for message interpolation and resource bundle loading.

As it turned out, most users only want to customize the latter aspect (e.g. in order to load message bundles from a database) but would like to re-use the interpolation algorithm provided by Hibernate Validator.

Therefore Hibernate Validator 4.1 introduces the interface ResourceBundleLocator which is used by HV's default MessageInterpolator implementation ResourceBundleMessageInterpolator to do the actual resource bundle loading.

The interface defines only one method, in which implementations have to return the bundle for a given locale:

1
2
3
4
5
public interface ResourceBundleLocator {

    ResourceBundle getResourceBundle(Locale locale);

}

The ResourceBundleLocator to be used can be set when creating a ValidatorFactory:

1
2
3
4
5
6
7
ValidatorFactory validatorFactory = Validation
    .byProvider(HibernateValidator.class)
    .configure()
    .messageInterpolator(
        new ResourceBundleMessageInterpolator(
            new MyCustomResourceBundleLocator()))
    .buildValidatorFactory();

The default ResourceBundleLocator implementation used by Hibernate Validator is PlatformResourceBundleLocator which simply loads bundles using ResourceBundle.loadBundle(). Another implementation provided out of the box is AggregateResourceBundleLocator, which allows to retrieve message texts from multiple bundles by merging them into a single aggregate bundle. Let's look at an example:

1
2
3
4
5
6
7
8
9
10
11
HibernateValidatorConfiguration configuration = Validation
    .byProvider(HibernateValidator.class)
    .configure();

ValidatorFactory validatorFactory = configuration
    .messageInterpolator(
        new ResourceBundleMessageInterpolator(
            new AggregateResourceBundleLocator(
                Arrays.asList("foo", "bar"), 
                configuration.getDefaultResourceBundleLocator())))
    .buildValidatorFactory();

Here messages from bundles "foo" and "bar" could be used in constraints. In case the same key was contained in both bundles, the value from bundle "foo" would have precedence, as it comes first in the list. If a given key can't be found in any of the two bundles as fallback the default locator (which provides access to the ValidationMessages bundle as demanded by the JSR 303 spec) will be tried.

API for programmatic constraint creation

Using the Bean Validation API constraints can be declared using either annotations and/or XML descriptor files. Hibernate Validator 4.1 introduces a third approach by providing an API for programmatic constraint declaration.

This API can come in handy for instance in dynamic scenarios where constraints change upon runtime or for testing scenarios.

As example let's consider two classes, Customer and Order, from a web shop application for which the following constraints shall apply:

  • each customer must have a name
  • each order must have a customer
  • each order must comprise at least one order line

With help of the programmatic constraint API these constraints can be declared as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
ConstraintMapping mapping = new ConstraintMapping();

mapping
    .type(Order.class)
        .property("customer", ElementType.FIELD)
            .constraint(NotNullDef.class)
        .property("orderLines", ElementType.FIELD)
            .constraint(SizeDef.class)
                .min(1)
                .message("An order must contain at least one order line")
    .type(Customer.class)
        .property("name", ElementType.FIELD)
            .constraint(NotNullDef.class);  

As the listing shows the API is designed in a fluent style with the class ConstraintMapping as entry point. Constraints are declared by chaining method calls which specify to which property of which type which constraints should be added.

The API provides constraint definition classes such as NotNullDef etc. for all built-in constraints, which allow to access their properties (min(), message() etc.) in a type-safe way. For custom constraints you could either provide your own constraint definition class or you could make use of GenericConstraintDef which allows to identify properties by name.

Having created a constraint mapping it has to be registered with the constraint validator factory. As the programmatic API is not part of the Bean Validation spec, we must explicitely specify Hibernate Validator as the BV provider to be used:

1
2
3
4
5
6
Validator validator = Validation
    .byProvider(HibernateValidator.class)
    .configure()
    .addMapping(mapping)
    .buildValidatorFactory()
    .getValidator();

If you now use this validator to validate an Order object which has no customer set a constraint violation will occur, just as if the "customer" property was annotated with @NotNull.

Constraint annotation processor

The Hibernate Validator annotation processor might become your new favourite tool if you find yourself accidentally doing things like

  • annotating Strings with @Min to specify a minimum length (instead of using @Size)
  • annotating the setter of a JavaBean property (instead of the getter method)
  • annotating static fields/methods with constraint annotations (which is not supported)

Normally you would notice such mistakes only during run-time. The annotation processor helps in saving your valuable time by detecting these and similar errors already upon compile-time by plugging into the build process and raising compilation errors whenever constraint annotations are incorrectly used.

The processor can be used in basically every build environment (plain javac, Apache Ant, Apache Maven) as well as within all common IDEs. Just be sure to use JDK 6 or later, as the processor is based on the "Pluggable Annotation Processing API" defined by JSR 269 which was introduced with Java 6.

The HV reference guide describes in detail how to integrate the processor into the different environments, so I'll spare you the details here. As example the following screenshot shows some compilation errors raised by the processor within the Eclipse IDE (click to enlarge):

Hibernate Validator Annotation Processor in Eclipse IDE

Just for the record it should be noted that the annotation processor already works pretty well but is currently still under development and is considered as an experimental feature as of HV 4.1. If you are facing any problems please report them in JIRA. Some known issues are also discussed in the reference guide.

Summary

The focus for Hibernate Validator 4.0 was to provide a feature-complete, production-ready reference implementation of the Bean Validation spec.

While strictly staying spec-compliant, HV 4.1 goes beyond what is defined in JSR 303 and aims at generating even more user value by providing new constraints, new API functionality as well as an annotation processor for compile-time annotation checking.

In order to try out the new features yourself just download the release from SourceForge. Of course HV 4.1 can also be retrieved from the JBoss Maven repository.

If you are already using HV 4.0.x, the new release generally should work as drop-in replacement. The only exception is that we had to move the class ResourceBundleMessageInterpolator to the new package messageinterpolation. So if you're directly referencing this class, you'll have to update your imports here.

The rationale behind this relocation was to clearly separate those packages which can safely be accessed by HV users from packages intended for internal use only. The public packages are:

  • org.hibernate.validator
  • org.hibernate.validator.cfg
  • org.hibernate.validator.constraints
  • org.hibernate.validator.messageinterpolation
  • org.hibernate.validator.resourceloading

Of course we'd be very happy on any feedback. Questions and comments can be posted in the HV forum, while any issues or feature requests should be reported in JIRA.

Friday, May 14, 2010

Bookmark and Share

Amongst others the Bean Validation API defines two constraint annotations related to time: @Past and @Future. With the help of these constraints one can validate that a given element is a date either in the past or in the future.

As per the BV specification these constraints are allowed for the types java.util.Date and java.util.Calendar. But what if you are working with an alternative date/time library such as the Joda Time API? Does that mean you can't use the @Past/@Future constraints?

Luckily not, as the Bean Validation API defines a mechanism for adding new validators to existing constraints. Basically all you have to do is to implement a validator for each type to be supported and register it within a constraint mapping file.

Note that for the remainder of this post I'll focus on the @Past constraint. Doing the same for @Future is left as an exercise for the reader.

Providing a Validator

So let's start with implementing a validator. The Joda Time API provides a whole bunch of types replacing the JDK date and time types. A good introduction to these types can be found in Joda's quickstart guide.

All Joda types representing exact points on the time-line implement the interface ReadableInstant. Providing an @Past validator for that interface will allow the @Past constraint to be used for widely used ReadableInstant implementations such as DateTime or DateMidnight.

Implementing the validator is straight-forward. Obeying the contract defined by @Past the given date is simply compared to a new DateTime instance which represents the current instant in the default time zone:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class PastValidatorForReadableInstant implements
        ConstraintValidator<Past, ReadableInstant> {

    public void initialize(Past constraintAnnotation) {}

    public boolean isValid(ReadableInstant value,
            ConstraintValidatorContext constraintValidatorContext) {

        if(value == null) {
            return true;
        }

        return value.isBefore(new DateTime());
    }
}

Similar validators could also be written for other Joda types which don't implement ReadableInstant (such as LocalDate) but as this is basically the same, it is out of the scope of this post.

Registering the Validator

Having implemented the validator we need to register it within a constraint mapping file:

1
2
3
4
5
6
7
8
9
10
11
12
13
<constraint-mappings
    xmlns="http://jboss.org/xml/ns/javax/validation/mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation=
        "http://jboss.org/xml/ns/javax/validation/mapping validation-mapping-1.0.xsd">

    <constraint-definition annotation="javax.validation.constraints.Past">
        <validated-by include-existing-validators="true">
             <value>de.gmorling.moapa.joda_bv_integration.PastValidatorForReadableInstant</value>
        </validated-by>
    </constraint-definition>

</constraint-mappings>

Using the validated-by element we add our new validator to the validators for the @Past constraint. By setting include-existing-validators to true, we ensure that the @Past constraint still can be used at the JDK date types.

As demanded by the Bean Validation API we then register the constraint mapping file within the central configuration file validation.xml:

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="UTF-8"?>
<validation-config
    xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration validation-configuration-1.0.xsd">

    <constraint-mapping>META-INF/validation/custom-constraints.xml</constraint-mapping>

</validation-config>

Trying it out

Now it's time to test how that all works out. To do so, we define an examplary domain class Customer which has an attribute birthday of the Joda type DateMidnight:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Customer {

    private final String name;

    private final DateMidnight birthday;

    public Customer(String name, DateMidnight birthday) {

        this.name = name;
        this.birthday = birthday;
    }

    @NotNull
    public String getName() {
        return name;
    }

    @NotNull
    @Past
    public DateMidnight getBirthday() {
        return birthday;
    }
}

A simple test finally shows that creating a customer with a future birthday causes a constraint violation, while a customer with a birthday in the past doesn't:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class CustomerTest {

    private static Validator validator;

    @BeforeClass
    public static void setUpValidatorAndDates() {

        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();
    }

    @Test
    public void customerWithFutureBirthdayCausesConstraintViolation() {

        Customer customer = new Customer("Bob", new DateMidnight(2020, 11, 3));
        Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer);

        assertEquals(1, constraintViolations.size());
        assertEquals("must be in the past", constraintViolations.iterator().next().getMessage());
    }

    @Test
    public void customerWithPastBirthdayCausesNoConstraintViolation() {

        Customer customer = new Customer("Bob", new DateMidnight(1960, 11, 3));
        Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer);

        assertTrue(constraintViolations.isEmpty());
    }

}

The complete source code in form of a Maven project can be found in my Git repository.

So just try it out and don't hesistate to post any feedback. It is also planned to add support for the Joda types in an ucoming version of Hibernate Validator.

Friday, April 9, 2010

Bookmark and Share

Recently I gave a presentation on JSR 303 ("Bean Validation") at the Java User Group in Hamburg, Germany.

I did also some live coding during the talk and mentioned some things only verbally. Nevertheless I thought the slides (which are in German) might be of interest, so I decided to put them online.

You can also find the presentation at slideshare.

The talk went pretty well, there were many questions and people generally seemed quite interested :-) One question related to the automatic validation of constraints at JPA entities I couldn't answer immediately, though.

The question was, whether lazy properties are loaded from the database during validation of class-level constraints (for constraint validation at fields/properties lazy attributes must not be loaded, which is ensured by checking each attribute's load state using a TraversableResolver).

Actually this can happen, depending on the attributes accessed by the validator implementation for the class-level constraint. I think, generally this is alright, as the validator needs to know the values of all attributes relevant for the evaluation of the constraint. If in certain scenarios this behavior is not acceptable, one could examine the attributes' load states manually using javax.validation.PersistenceUtil and depending on that access only certain attributes.

Thursday, March 25, 2010

Bookmark and Share

When I started blogging on JSR 303 ("Bean Validation"), there was not too much information available on the web concerning the BV API, its usage and its integration with other technologies.

In between JSR 303 got approved, BV is part of Java EE 6 and as it generally gains wider adoption, more and more blog posts and other information related to Bean Validation come available.

That's why I thought it might be a good idea to collect the most interesting pieces and publish those links here every once in a while.

And there you go, here is the first couple of links related to JSR 303:

I plan to post follow-ups, whenever I gathered some interesting links, so stay tuned.

Tuesday, February 16, 2010

Bookmark and Share

One question I'm being asked pretty often when talking about the Bean Validation API (JSR 303) is, how cross-field validation can be done. The canonical example for this is a class representing a calendar event, where the end date of an event shall always be later than the start date.

This and other scenarios where validation depends on the values of multiple attributes of a given object can be realized by implementing a class-level constraint.

That basically works pretty well, nevertheless this is one part of the BV spec, I'm not too comfortable with. This is mainly for two reasons:

  • You'll probably need a dedicated constraint for every reasonably complex business object. Providing an annotation, a validator implementation and an error message for each can become pretty tedious.
  • Business objects typically know best themselves, whether they are in a consistent, valid state or not. By putting validation logic into a separate constraint validator class, objects have to expose their internal state, which otherwise might not be required.

To circumvent these problems, I suggested a while ago a generic constraint annotation, which allows the use of script expressions written in languages such as Groovy to implement validation logic directly at the validated class.

This approach frees you from the need to implement dedicated constraints for each relevant business object, but also comes at the cost of losing type-safety at compile-time.

The constraint presented in the following therefore tries to combine genericity with compile-time type safety. The basic idea is to implement validation logic within the business objects themselves and to invoke this logic from within a generic constraint class.

In order to do so let's first define an interface to be implemented by any validatable class:

1
2
3
4
public interface Validatable {

    public boolean isValid();
}

Next we define a constraint annotation, @SelfValidating, which we'll use later on to annotate Validatable implementations:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Target( { TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = SelfValidatingValidator.class)
@Documented
public @interface SelfValidating {

    String message() default "{de.gmorling.moapa.self_validating.SelfValidating.message}";

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

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

}

Of course we also need a constraint validator implementation, which is able to evaluate that constraint:

1
2
3
4
5
6
7
8
9
10
11
public class SelfValidatingValidator implements
    ConstraintValidator<SelfValidating, Validatable> {

    public void initialize(SelfValidating constraintAnnotation) {}

    public boolean isValid(Validatable value,
        ConstraintValidatorContext constraintValidatorContext) {

        return value.isValid();
    }
}

The implementation is trivial, as nothing is to do in initialize() and the isValid() method just delegates the call to the validatable object itself.

Finally we need a properties file named ValidationMessages.properties containing the default error message for the constraint:

1
de.gmorling.moapa.self_validating.SelfValidating.message=Validatable object couldn't be validated successfully.

Taking the calendar event example from the beginning, usage of the constraint might look as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@SelfValidating
public class CalendarEvent implements Validatable {

    @NotNull
    private final String title;

    private final Date startDate;

    private final Date endDate;

    public CalendarEvent(String title, Date startDate, Date endDate) {

        this.title = title;
        this.startDate = startDate;
        this.endDate = endDate;
    }

    public boolean isValid() {
        return startDate == null || endDate == null || startDate.before(endDate);
    }

    @Override
    public String toString() {
        DateFormat format = new SimpleDateFormat("dd.MM.yyyy");

        return 
            title + 
            " from " +  (startDate == null ? "-" : format.format(startDate)) + 
            " till " + (endDate == null ? "-" : format.format(endDate));
    }

}

A short unit test shows that the constraint works as expected:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
public class SelfValidatingTest {

    private static Validator validator;

    private static Date startDate;

    private static Date endDate;

    @BeforeClass
    public static void setUpValidatorAndDates() {

        ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
        validator = validatorFactory.getValidator();

        startDate = new GregorianCalendar(2009, 8, 20).getTime();
        endDate = new GregorianCalendar(2009, 8, 21).getTime();
    }

    @Test
    public void calendarEventIsValidAsEndDateIsAfterStartDate() {

        CalendarEvent testEvent = 
            new CalendarEvent("Team meeting", startDate, endDate);

        assertTrue(validator.validate(testEvent).isEmpty());
    }

    @Test
    public void calendarEventIsInvalidAsEndDateIsBeforeStartDate() {

        CalendarEvent testEvent = 
            new CalendarEvent("Team meeting", endDate, startDate);

        Set<ConstraintViolation<CalendarEvent>> constraintViolations = 
            validator.validate(testEvent);
        assertEquals(1, constraintViolations.size());

        assertEquals(
            "Object couldn't be validated successfully.",
            constraintViolations.iterator().next().getMessage());
    }
}

This works like a charm, only the error message returned by the BV runtime is not yet very expressive. This can easily be solved, as the BV API allows to override error messages within constraint annotations:

1
2
3
4
@SelfValidating(message="{de.gmorling.moapa.self_validating.CalendarEvent.message}")
public class CalendarEvent implements Validatable {
    ...
}

Again we need an entry in ValidationMessages.properties for the specified message key:

1
de.gmorling.moapa.self_validating.CalendarEvent.message=End date of event must be after start date.

Conclusion

Providing dedicated class-level constraints for all business objects that require some sort of cross-field validation logic can be quite a tedious task as you need to create an annotation type, a validator implementation and an error message text.

The @SelfValidating constraint reduces the required work by letting business objects validate themselves. That way all you have to do is implement the Validatable interface, annotate your class with @SelfValidating and optionally provide a customized error message. Furthermore business objects are not required to expose their internal state to make it accessible for an external validator implementation.

The complete source code can be found in my GitHub repository. As always I'd be happy about any feedback.