Help

I'm pleased to be able to present this week's module spotlight which was written by Gunnar Morling, the module lead for Seam Validation. - Shane.

by Gunnar Morling

Welcome back to the Seam Module Spotlight series. In this installment we're going to discuss a relatively new Seam module, Seam Validation.

This module 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 sections.

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:

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.:

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:

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 one 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:

<?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:

@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 choose the validation groups to be used for method validation and the evaluation of standard bean constraints upon method validation.

13 comments:
 
15. Jun 2014, 08:11 CET | Link
kilsia

It may complete the aforementioned and accept the aforementioned address at a discounted amount to activate with, but you will absolutely feel afflictive if walking beside a acquaintance who owns accurate artist Replica Handbags. Not all women Louis Vuitton replica handbags accept to be actual big-ticket though. There are abounding vendors who advertise at broad prices if you can acquisition them. Do not overlook to baddest affordable Dior replica handbags accurate artist to accommodated your needs. There are abounding replicas that are actual agnate to the absolute accoutrements so it is capital to apprentice how to atom a affected so they do not end up accident your money. A lot of counterfeits are harder to analyze from the absolute accord to pay absorption to specific data is capital to actuate whether a bag is authentic.With the acceptance of Fendi Replica Handbags at a acme of all time, a lot of apish accoutrements are go alfresco and online auctions. Do not be bamboozled into affairs a Louis Vuitton Sacs bag that claims to be the absolute thing, if in actuality it is not. Sometimes it can be difficult to analyze a affected from a real, but there are several agency to analyze the aberration amid a absolute and accurate Louis Vuitton Replica Designer Handbags.As the afterward features.Louis Vuitton handbags are expensive. They are fabricated of big-ticket abstracts such as top superior leather, boa, crocodile, lamb and biscuit skin. The fakes are fabricated of bogus covering and vinyl, can feel asperous and rugged.

ReplyQuote
 
18. Jul 2014, 12:29 CET | Link
functions

REI has also devoted to increase h2o preservation across its functions by installing rainfall landscapes, swamplands and other actions to cure stormwater run-off before it reaches sources close to REI’s head office in London and its submission center in Sumner. babyscream

 
28. Aug 2014, 07:53 CET | Link
making SEO

And that’s the main reason why most of the people are now making SEO an integral part of their business, and they are also getting good return on investment too. the truth about cellulite joey atlas

 
29. Aug 2014, 06:55 CET | Link
obat herbal kanker payudara alami

I most appreciating each of it. is a great incredible and very good impart. I have to much obliged. Great employment! You all a good incredible blog, and have some extraordinary substance. Keep doing amazing obat herbal asam urat alami obat herbal kanker payudara alami

07. Oct 2014, 05:48 CET | Link
forever is to you is savory savory nyoy
http://hanifherbal.wordpress.com/2014/10/06/obat-herbal-kanker-pankreas/
http://caramengatasisyarafkejepit.wordpress.com/
08. Oct 2014, 03:04 CET | Link

information that you provide is very helpful. thank you obat darah tinggi

10. Oct 2014, 08:17 CET | Link
information complite

<a href='http://exl.me/nipm'>Obat Usus Turun</a>
11. Oct 2014, 10:04 CET | Link

I love the story you created, may be useful,,,spirit

http://keuherbalgreenworld.wordpress.com/

11. Oct 2014, 10:06 CET | Link

thank you . . forever is to you . .

http://minyakikan.web.id/

 
14. Oct 2014, 07:40 CET | Link
important source

Two fighters in desire of a thieved blade and a well known fuyarde are led to an impetuous, physically-skilled, younger nobleman's little girl, who is at a crossroads in her life. The fight, the scenery, and activity made this film well-known across the globe. important source

14. Oct 2014, 09:45 CET | Link

Click HELP for text formatting instructions. Then edit this text and check the preview.

 
16. Nov 2014, 20:28 CET | Link
your article is very informing, will be a lot of people who read it
Post Comment