Saturday, March 5, 2011

Bookmark and Share

I need your help.

To be more concise, I need your vote for the 2011 JBoss Community Recognition Awards.

These awards are an effort of JBoss/Red Hat to honor significant contributions to the JBoss community over the last year and I'm more than proud to say that I've been nominated in the "New Features" category for my contributions to Hibernate Validator.

So if you appreciate my work on Hibernate Validator – e.g. the HV annotation processor or the method validation feature I've built for HV 4.2 – or the Validation module for Seam 3 (I'll blog on this in a separate post) I've recently started, just head over to the poll and give me your vote. The voting is open until April, 2nd.

And if you really like my work, go and tell your friends that they should vote for me, too.

Just in case you feel like you need some more information to make a profound vote you might also check out my nominee description.

Another nomination I'd like to mention is the one of my fellow developer Kevin Pollet in the "Bug Fixes" category. He has done some really awesome work for HV 4.2. Besides fixing many bugs he implemented several new features like the integration with the Joda time API or the support for dynamic default group sequence definitions.

So when you (and your friends) have voted for me, don't forget to vote for Kevin, too :)

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

This is more a note to myself, but in case someone else wonders how to specify the active Maven profile in IntelliJ IDEA for projects containing several profiles, that's the way to go:

  • Open the "Maven Projects" window by selecting "Window" - "Tool Windows" - "Maven Projects"
  • Expand the "Profiles" node and select the profile you want to use
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.

Wednesday, November 17, 2010

Bookmark and Share
At my day job we are using the SVN property "svn:keywords" to let SVN replace the string "$Id$" with author name, revision number etc. within each Java source file.

One can add this property automatically when creating new files with the help of SVN's auto props feature. But from time to time someone, e.g. a new developer not knowing about auto props, checks in files without having the "svn:keywords" property set.

So I wondered how to identify such files in the repository. SVN doesn't provide a command answering that question, you only can retrieve all files having a certain property set.

But no problem, some shell magic to the rescue:

1
comm -23 <(sort <(sed 's/\.\///g' <(find . -name "*.java"))) <(sort <(sed 's/ - Id//g' <(svn propget svn:keywords * -R)))

So what's happening here? The basic idea is to list those files with the svn:keywords property set (svn propget) and compare this to a list with all files (find).

The outputs of both commands are brought into the same format using sed, sorted and then passed as parameters to the comm command, which compares two input files to each other. The -23 parameter causes only those lines to be put out which are only contained in file1 but not in file2, which are exactly the names of those files lacking the "svn:keywords" property.

I tested the command successfully on Mac OS X, but I think it should work pretty much the same way on other Unix systems, too.