All Downloads are FREE. Search and download functionalities are using the official Maven repository.

javax.validation.CompareToValidator Maven / Gradle / Ivy

The newest version!
package javax.validation;

import java.lang.reflect.Field;

import javax.validation.constraints.CompareTo;

import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;

public class CompareToValidator implements ConstraintValidator {
  private String sourceFieldName;
  private String destinationFieldName;
  private String targetFieldName;
  private boolean equals;
  private String message;

  @Override
  public void initialize(CompareTo constraintAnnotation) {
    this.sourceFieldName = constraintAnnotation.source();
    this.destinationFieldName = constraintAnnotation.destination();
    this.targetFieldName = constraintAnnotation.target();
    this.equals = constraintAnnotation.equals();
    this.message = constraintAnnotation.message();
  }

  /**
   * @see ReflectionUtils#findField(Class, String)
   * @see ReflectionUtils#makeAccessible(Field)
   */
  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {
    Object source = getField(value, this.sourceFieldName);
    Object destination = getField(value, this.destinationFieldName);

    if (source instanceof Comparable && destination instanceof Comparable) {
      @SuppressWarnings("unchecked")
      int compareTo = ((Comparable) source).compareTo(destination);
      if (!(this.equals ? compareTo == 0 || compareTo == -1 : compareTo == -1)) {
        if (StringUtils.hasText(this.targetFieldName)) {
          context.buildConstraintViolationWithTemplate(this.message).addPropertyNode(this.targetFieldName).addConstraintViolation();
        }
        else {
          context.buildConstraintViolationWithTemplate(this.message).addPropertyNode(this.sourceFieldName).addConstraintViolation();
          context.buildConstraintViolationWithTemplate(this.message).addPropertyNode(this.destinationFieldName).addConstraintViolation();
        }
        return false;
      }
    }
    return true;
  }

  private Object getField(Object value, String fieldName) {
    Field field = ReflectionUtils.findField(value.getClass(), fieldName);
    if (field == null) {
      return null;
    }
    ReflectionUtils.makeAccessible(field);
    return ReflectionUtils.getField(field, value);
  }
}