Time travelling with Bean Validation 2.0 and Java EE 8

With Java EE 8 and Bean Validation 2.0 JSR-380 you can time travel by passing an adjusted java.time.Clock instance to the clockProvider method:

import java.time.Clock;
import java.time.Duration;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

public class BeanValidationTest {

private Validator validator;

public void init() {
    ValidatorFactory factory = Validation
    this.validator = factory.getValidator();

Clock configureClockWithFutureTime() {
    return Clock.offset(Clock.systemDefaultZone(), Duration.ofSeconds(10));

Now you can configure whether your vacations are already over:

import java.util.Date;
import javax.validation.constraints.PastOrPresent;

public class Vacations {

    private Date date;

    public Vacations() {
        this.date = new Date();

public void vacationsAreOver() {
    Set<ConstraintViolation<Vacations>> violations = this.validator.validate(new Vacations());

...or whether you have to work again:

import java.util.Date;
import javax.validation.constraints.Future;

public class Development {

    private Date date;
    public Development() {
        this.date = new Date();
public void weAreWorkingNow() {
    Set<ConstraintViolation<Development>> violations = this.validator.validate(new Development());
    boolean rightMessage = violations.stream().
            map(violation -> violation.getMessage()).
            allMatch(message -> "must be a future date".equalsIgnoreCase(message));


To run the bean validation as a JUnit test, you will need the following dependencies:


See you at Java EE 8 on Java 9, at Munich Airport, Terminal 2

NEW online workshop: Web Components training (online)

Airport MUC workshops: Java EE 8, Java 9: Bootstrap, Effective, Architectures, Single Page Apps, Progressive Web Apps, HTML 5, ES 6, CSS 3 and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments