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

de.thksystems.validation.beanvalidation.ConditionalNotEmptyValidator Maven / Gradle / Ivy

package de.thksystems.validation.beanvalidation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import de.thksystems.exception.ServiceRuntimeException;
import de.thksystems.util.reflection.ReflectionUtils;

public class ConditionalNotEmptyValidator extends AbstractNotEmptyValidator implements ConstraintValidator {

	private String fieldname;

	private String conditionalField;

	private String conditionalValue;

	@Override
	public void initialize(ConditionalNotEmpty constraintAnnotation) {
		fieldname = constraintAnnotation.fieldname();
		conditionalField = constraintAnnotation.conditionField();
		conditionalValue = constraintAnnotation.conditionValue();
	}

	@Override
	public boolean isValid(Object container, ConstraintValidatorContext context) {
		try {
			Object currentConditionValue = ReflectionUtils.getFieldValue(container, container.getClass().getDeclaredField(conditionalField));
			if ((currentConditionValue == null && conditionalValue == null) || currentConditionValue.equals(conditionalValue)
				|| currentConditionValue.toString().equals(conditionalValue)) {
				Object fieldValue = ReflectionUtils.getFieldValue(container, container.getClass().getDeclaredField(fieldname));
				return isNotEmpty(fieldValue);
			}
			return true;
		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
			throw new ServiceRuntimeException(e.getMessage(), e);
		}
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy