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

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

Go to download

Commons for persistence, hibernate, xstreams, enterprise, spring, servlets, ...

There is a newer version: 3.9.0
Show newest version
package de.thksystems.validation.beanvalidation;

import java.lang.reflect.Array;
import java.util.Collection;

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

import org.apache.commons.lang3.StringUtils;

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

public class OneNotEmptyValidator implements ConstraintValidator {

	private String[] fieldnames;

	@Override
	public void initialize(OneNotEmpty constraintAnnotation) {
		fieldnames = constraintAnnotation.fieldnames();
	}

	@Override
	public boolean isValid(Object container, ConstraintValidatorContext context) {
		try {
			for (String fieldname : fieldnames) {
				Object fieldValue = ReflectionUtils.getFieldValue(container, container.getClass().getDeclaredField(fieldname));
				// Null -> Next
				if (fieldValue == null) {
					continue;
				}
				// Check for empty String
				if (fieldValue instanceof CharSequence) {
					if (StringUtils.isNotEmpty((String) fieldValue)) {
						return true;
					} else {
						continue;
					}
				}
				// Check for empty collection
				if (fieldValue instanceof Collection) {
					if (!((Collection) fieldValue).isEmpty()) {
						return true;
					} else {
						continue;
					}
				}
				// Check for empty array
				if (fieldValue.getClass().isArray()) {
					if (Array.getLength(fieldValue) > 0) {
						return true;
					} else {
						continue;
					}
				}
				// Any other object that is not null
				return true;
			}
			// Default
			return false;
		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
			throw new ServiceRuntimeException(e.getMessage(), e);
		}
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy