Search in sources :

Example 1 with AnnotationReflection

use of com.shaoqunliu.reflection.AnnotationReflection in project CILManagement-Server by LiuinStein.

the class AbstractValidator method validate.

/**
 * @see com.shaoqunliu.validation.ValidationAdapter#validate(Object, Class[])
 */
@Override
public <T> T validate(T object, Class<?>... groups) throws ValidationException {
    sanityCheckGroups(groups);
    POJOReflection reflection = new POJOReflection(object);
    StringBuilder message = new StringBuilder(128);
    classFunctionMap.forEach((type, function) -> {
        if (isFailFast() && message.length() != 0) {
            return;
        }
        reflection.forEachAnnotationByFieldByType((field, annotation) -> {
            try {
                AnnotationReflection annotationReflection = new AnnotationReflection(annotation);
                Class<?>[] classes = (Class<?>[]) annotationReflection.getMember("groups");
                if ((groups.length == 0 && classes.length == 0) || Arrays.stream(classes).anyMatch(Arrays.asList(groups)::contains)) {
                    Object value = reflection.getValue(field.getName());
                    if (!function.apply(value, annotationReflection::getMember)) {
                        String annotationMessage = annotationReflection.getMember("message").toString();
                        message.append(annotationMessage.length() == 0 ? "invalid value " + value.toString() + " was given" : annotationMessage);
                    }
                }
            } catch (Exception ignored) {
            // ignored
            }
        }, type);
    });
    if (message.length() != 0) {
        throw new ValidationException(message.toString());
    }
    return object;
}
Also used : POJOReflection(com.shaoqunliu.reflection.POJOReflection) AnnotationReflection(com.shaoqunliu.reflection.AnnotationReflection) ValidationException(com.shaoqunliu.validation.exception.ValidationException) ValidationException(com.shaoqunliu.validation.exception.ValidationException)

Aggregations

AnnotationReflection (com.shaoqunliu.reflection.AnnotationReflection)1 POJOReflection (com.shaoqunliu.reflection.POJOReflection)1 ValidationException (com.shaoqunliu.validation.exception.ValidationException)1