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

javax.validation.EqualsValidator Maven / Gradle / Ivy

package javax.validation;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.validation.ConstraintValidatorContext.ConstraintViolationBuilder;
import javax.validation.constraints.Equals;

import org.springframework.util.ObjectUtils;
import org.springframework.util.ReflectionUtils;

public class EqualsValidator implements ConstraintValidator {
  private String sourceFieldName;
  private String targetFieldName;
  private List fieldNames;
  private String message;

  @Override
  public void initialize(Equals constraintAnnotation) {
    this.fieldNames = Arrays.asList(constraintAnnotation.value());
    this.sourceFieldName = constraintAnnotation.source();
    this.targetFieldName = constraintAnnotation.target();
    this.message = constraintAnnotation.message();
  }

  @Override
  public boolean isValid(Object value, ConstraintValidatorContext context) {
    boolean result = isValid(value);
    if (!result) {
      ConstraintViolationBuilder builder = context.buildConstraintViolationWithTemplate(this.message);
      for (String fieldName : this.fieldNames) {
        builder.addPropertyNode(fieldName).addConstraintViolation();
      }
    }
    return result;
  }

  private boolean isValid(Object value) {
    if (ObjectUtils.isEmpty(this.fieldNames)) {
      return true;
    }
//    List objects = getObjects(value);
//    int objectsSize = objects.size();
//    for (int a = 0, b = 1; a < objectsSize - 1; b = a + 1, a++) {
//
//    }
//    Object field = getField(value, this.fieldNames.iterator().next());
//    for (String fieldName : this.fieldNames) {
//      field = getField(value, fieldName);
//    }
    Object source = getField(value, this.sourceFieldName);
    Object target = getField(value, this.targetFieldName);
    return source == null || target == null || source.equals(target);
  }

  private List getObjects(Object value) {
    List list = new ArrayList();
    for (String fieldName : this.fieldNames) {
      list.add(getField(value, fieldName));
    }
    return list;
  }

  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);
  }
}