001/*
002 * Licensed under the Apache License, Version 2.0 (the "License");
003 * you may not use this file except in compliance with the License.
004 * You may obtain a copy of the License at
005 *
006 *     http://www.apache.org/licenses/LICENSE-2.0
007 *
008 * Unless required by applicable law or agreed to in writing, software
009 * distributed under the License is distributed on an "AS IS" BASIS,
010 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
011 * See the License for the specific language governing permissions and
012 * limitations under the License.
013 */
014package org.gbif.api.util.validators.email;
015
016import javax.validation.ConstraintValidator;
017import javax.validation.ConstraintValidatorContext;
018
019import org.apache.commons.validator.routines.EmailValidator;
020
021/**
022 * {@link ConstraintValidator} that validates emails. Uses apache commons {@link EmailValidator}
023 * <p>
024 * Handles {@link ValidEmail} annotation which is better than default {@link javax.validation.constraints.Email}.
025 * Default one finds some values valid like: "mail@mail", "mail@mail.e", but this one not.
026 */
027public class EmailConstraintValidator implements ConstraintValidator<ValidEmail, String> {
028
029  private static final EmailValidator EMAIL_VALIDATOR = EmailValidator.getInstance();
030
031  private ValidEmail annotation;
032
033  @Override
034  public void initialize(ValidEmail constraintAnnotation) {
035    ConstraintValidator.super.initialize(constraintAnnotation);
036    this.annotation = constraintAnnotation;
037  }
038
039  @Override
040  public boolean isValid(String value, ConstraintValidatorContext context) {
041    if (!annotation.required() && value == null) {
042      return true;
043    }
044    return EMAIL_VALIDATOR.isValid(value);
045  }
046}