Icon

Software Engineering, Architecture, Web Development and beyond…

Bean Validation (JSR-303) and validating Cron Expressions, extending constraints

To validate cron expressions using bean validation stuff, the best practice is to write your own custom validators and to use quartz framework’s cron expression facilities.
To write your custom validator, you need to implement

ConstraintValidator<A extends java.lang.annotation.Annotation,T>

from javax.validation.* package.

public class CronExpressionValidator implements
        ConstraintValidator<CronExpression, String> {
 
    public void initialize(CronExpression cronExpression) {
        //To change body of implemented methods use File | Settings | File Templates.
    }
 
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        return org.quartz.CronExpression.isValidExpression(s);
    }
}

To validate cron expressions in isValid() method, the isValidExpression() static method is used from Quartz Framework. To add Quartz to our maven project add the following dependency into your pom:

        <dependency>
            <groupId>org.opensymphony.quartz</groupId>
            <artifactId>quartz</artifactId>
            <version>1.6.5</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>

CronExpression defined as parameterized type is the annotation class that we will use for cron constraints and seems like following;

@Documented
@Constraint(validatedBy = CronExpressionValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface CronExpression {
    String message() default "Cron expression is not valid!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

@Documented indicates that annotations with a type are to be documented by javadoc and similar tools by default.
@Constraint(validatedBy=CronExpressionValidator.class) defines validator class.
@Target defines that this annotation is applicable to methods, fields, annotation types, constructors and parameters.
@Retention defines that the annotation is a runtime annotation not a compile time annotation like @SupressWarnings, @Override etc.

We are now ready to annotate our fields, parameters etc. with our new constraint just like this:

class MyCronBean {
    @NotNull
    @CronExpression
    private String cronExpression;
    /** setters and getters */
}

erhan

Author


Hello, I'm Erhan Bagdemir and this is my blog. I talk about Java, J2EE, Frameworks, web application development, OOAD and various other topics often related to programming.

Erhan Bagdemir  Profil von Erhan Bagdemir auf LinkedIn anzeigen

ebagdemir on Stackoverflow

ebagdemir on Twitter

    Hamburg

    Slideshow