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

com.aeontronix.commons.validation.AnnotationBasedValidatorJSR303Impl Maven / Gradle / Ivy

The newest version!
/*
 * Copyright (c) 2014 Kloudtek Ltd
 */

package com.aeontronix.commons.validation;

import com.aeontronix.commons.exception.ExceptionUtils;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;

import java.util.Set;

/**
 * Annotation based validator that uses a JSR 303 implementation
 */
public class AnnotationBasedValidatorJSR303Impl implements AnnotationBasedValidator {
    private final Validator validator;
    private final Exception validatorFailException;

    public AnnotationBasedValidatorJSR303Impl() {
        Validator validatorImpl = null;
        Exception fail = null;
        try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) {
            validatorImpl = factory.getValidator();
        } catch (Exception e) {
            fail = e;
        }
        validator = validatorImpl;
        validatorFailException = fail;
    }

    @Override
    @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"})
    public  void validate(Object object, Class exceptionClass, Class... validationGroups) throws E {
        if (validator == null) {
            throw new RuntimeException("No validator available: " + validatorFailException.getMessage(), validatorFailException);
        }
        Set> violations = validator.validate(object, validationGroups);
        if (!violations.isEmpty()) {
            ConstraintViolation violation = violations.iterator().next();
            String errorMsg = violation.getPropertyPath().toString() + ": " + violation.getMessage();
            ExceptionUtils.throwException(exceptionClass, errorMsg);
        }
    }
}