Custom constraints with Bean Validation

Posted: February 28th, 2011 | Author: | No Comments »

One of the more interesting components that Java EE 6 brings us is Bean Validation JSR-303, which helps you to define constraints on your model making possible to divide the model validation and the business logic. Besides, this component can be used in any layer you are working, for instance, JSF uses Bean Validation to validate the data in a web forms and JPA uses to validate data before storing the entity in the database.

The specification comes with some validations that you can use directly by using their annotations: @NotNull, @Min, @Max, @Pattern, etc. Despite these annotations are very useful, they don’t cover all your model constraints and sometimes it’s necessary to define custom constraints according to real world.

Creating custom constraints

Imagine you are developing a typical product order where you have two customer types (normal and premium) and two product types (normal and exclusive) and your model has the following constraint:

“Normal customer can buy two exclusive products in his order. On the other hand, premium customer doesn’t have any limitation about this.”

First of all, you have these entities of your model:

public class Product {

    public Product () { }

    public Product(String name, Integer cost, ProductType type) {
        this.name = name;
        this.cost = cost;
        this.type = type;
    }

    private String name;

    private Integer cost;

    private ProductType type;

    public enum ProductType { NORMAL, EXCLUSIVE };

    // Getters and Setters

}

public class Order {

    public Order() { }

    public Order(Customer customer) {
        this.customer = customer;
    }

    private List<OrderLine> lines = new LinkedList<OrderLine>();

    private Customer customer;

    // Getters and Setters

}

public class OrderLine {

    public OrderLine() { }

    public OrderLine (Product product, Integer quantity){
        this.product = product;
        this.quantity = quantity;
    }

    private Product product;

    private Integer quantity;

    // Getters and Setters

}

Customer class will be defined soon. The next step is to create the annotation and put in the correct place. The annotation have to have the form:

@Retention(RUNTIME)
@Target({TYPE, FIELD, METHOD})
@Constraint(validatedBy = ExclusiveProductsValidator.class)
public @interface ExclusiveProducts {

    String message() default "Exclusive products constraint has been violated";

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

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

    int max() default 0;
}

The meaning of attributes are:

  • message – Indicates what is the message returned if the bean doesn’t satisfied the constraint. You can also use bundle JSF message here.
  • groups – Array of groups to filter the validating according a criteria.
  • payload – Indicates the severity of validation.
  • max – This attribute indicates the maximun quantity of exclusive products a customer can order, in this example, the value will be two.

It just need to know where to put this annotation. As you can think, constraint is associated to list of OrderLine in Order class, so this class would be as follows:

public class Order {

    // ...

    @ExclusiveProducts(max = 2)
    private List<OrderLine> lines = new LinkedList<OrderLine>();

    // ...
}

At this moment you are thinking “ok, I’ve created the annotation and I’ve put it in the bean, but where is the validation code?”. As you can see in the definition of annotation, it uses another annotation to declare what class should validate the bean, in this case this class is ExclusiveProductValidator. The code of this class is:

public class ExclusiveProductsValidator implements ConstraintValidator<ExclusiveProducts, List<OrderLine>> {

    int max;

    @Override
    public void initialize(ExclusiveProducts constraintAnnotation) {
        max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(List<OrderLine> value, ConstraintValidatorContext context) {
        int count = 0;
        for (OrderLine ol : value) {
            if (ol.getProduct().getType().equals(ProductType.EXCLUSIVE)) {
                count += ol.getQuantity();
            }
        }

        if (count > max) {
            return false;
        }

        return true;
    }
}

This code is easy, the methodinitialize simply stores the max value in an internal attribute and then with isValid validates the OrderLine list by returning false if the quantity of exclusive products is more than the value, otherwise returns true.

Validation groups

So far, the validation doesn’t distinguish between any kind of customer, and our requirement says that this restriction is only applied to normal customer. To this end, we need to create validation groups. Groups allow us to categorize beans to apply a kind of validation or another one, or apply a validation with different values depending the groups. To create a group, you need to declare an interface that extends Default and different subtypes.

public interface CustomerType extends Default { }

public interface NormalCustomer extends CustomerType { }

public interface PremiumCustomer extends CustomerType { }

At this point, the definition of Customer is very clear, this entity will have its own attributes (username, email, etc) and it have to indicate what kind of customer it is. An example of Customer is:

public class Customer {

    public Customer () { }

    public Customer(String username, Class<? extends CustomerType> type) {
        this.username = username;
        this.type = type;
    }

    private String username;

    private Class<? extends CustomerType> type;

    // Getters and Setters

}

And we have to rewrite the validation to use this feature:

public class Order {

    // ...

    @ExclusiveProducts(max = 2, groups = NormalCustomer.class)
    private List<OrderLine> lines = new LinkedList<OrderLine>();

    // ...
}

With this clause we are saying to Bean Validation that this constraints is just applied to order of normal customers.

Testing the constraint

The custom constraint is created and what you need is to know how to test this behaviour and how to validate beans. I’m going to use a simple test case by using JUnit like that:

public class ExclusiveProductValidationTest {

    private static Validator validator;
    private static Customer normalCustomer;
    private static Customer premiumCustomer;
    private static Product normalProduct;
    private static Product exclusiveProduct;

    @BeforeClass
    public static void setUpClass() throws Exception {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();

        premiumCustomer = new Customer("usertest", PremiumCustomer.class);
        normalCustomer = new Customer("usertest", NormalCustomer.class);

        normalProduct = new Product("Normal product", 12, ProductType.NORMAL);
        exclusiveProduct = new Product("Exclusive product", 25, ProductType.EXCLUSIVE);
    }

    /**
     * Creating some order lines with 2 normal products and 2 exclusive products for
     * a normal customer. Validator shouldn't indicate any constraint violation.
     */
    @Test
    public void testWithTwoExclusiveProductsAndNormalCustomer() {

        OrderLine ol1 = new OrderLine(normalProduct, 2);
        OrderLine ol2 = new OrderLine(exclusiveProduct, 2);

        Order order = new Order(normalCustomer);
        order.getLines().add(ol1);
        order.getLines().add(ol2);

        Set<ConstraintViolation<Order>> violations = validator.validate(order, order.getCustomer().getType());
        assertEquals("It shouldn't have any violation in this case", 0, violations.size());

    }

    /**
     * Creating some order lines with 2 normal products and 3 exclusive products for
     * a normal customer. Validator should indicate the constraint violation.
     */
    @Test
    public void testWithThreeExclusiveProductsAndNormalCustomer() {

        OrderLine ol1 = new OrderLine(normalProduct, 2);
        OrderLine ol2 = new OrderLine(exclusiveProduct, 3);

        Order order = new Order(normalCustomer);
        order.getLines().add(ol1);
        order.getLines().add(ol2);

        Set<ConstraintViolation<Order>> violations = validator.validate(order, order.getCustomer().getType());
        assertEquals("It should have one violation in this case", 1, violations.size());
    }

    /**
     * Creating an order lines with 5 exclusive products for a premium customer.
     * Validator shouldn't indicate any constraint violation.
     */
    @Test
    public void testWithFewExclusiveProductsAndPremiumCustomer() {

        OrderLine ol = new OrderLine(exclusiveProduct, 5);

        Order order = new Order(premiumCustomer);
        order.getLines().add(ol);

        Set<ConstraintViolation<Order>> violations = validator.validate(order, order.getCustomer().getType());
        assertEquals("It shouldn't have any violation in this case", 0, violations.size());

    }
}

In setUpClass we create a validator through of ValidatorFactory, and we use this validator in each test. Remember that if you use Bean Validation in a JSF or JPA environment, the validation of your beans will be automatic and you won’t need an explicit validator (althought you can deactivate it and so, to have more control).


Tags: , ,

Leave a Reply