de.thksystems.validation.beanvalidation.OneNotEmptyValidator Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of mugwort Show documentation
Show all versions of mugwort Show documentation
Commons for persistence, hibernate, xstreams, enterprise, spring, servlets, ...
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);
}
}
}