001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: AbstractValidator.java 274 2012-02-13 21:28:59Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.validation;
009    
010    import java.lang.annotation.Annotation;
011    import java.util.Collection;
012    
013    import javax.validation.ConstraintValidator;
014    import javax.validation.ConstraintValidatorContext;
015    
016    /**
017     * Support superclass for validators.
018     */
019    public abstract class AbstractValidator<C extends Annotation, T> implements ConstraintValidator<C, T> {
020    
021        /**
022         * The constraint being checked by this instance.
023         */
024        protected C annotation;
025    
026        @Override
027        public void initialize(@SuppressWarnings("hiding") C annotation) {
028            this.annotation = annotation;
029        }
030    
031        /**
032         * Convenience method to add a constraint violation described by {@code message} and disable the default violation.
033         */
034        protected void setViolation(ConstraintValidatorContext context, String message) {
035            context.disableDefaultConstraintViolation();
036            context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
037        }
038    
039        /**
040         * Apply this constraint to all values in a collection. This is a convenience method for validators
041         * that want to work with both simple properties and collection properties.
042         */
043        protected boolean isCollectionValid(Collection<? extends T> collection, ConstraintValidatorContext context) {
044            boolean result = true;
045            for (T value : collection) {
046                if (!this.isValid(value, context))
047                    result = false;
048            }
049            return result;
050        }
051    }
052