Search in sources :

Example 1 with TraversableResolver

use of jakarta.validation.TraversableResolver in project hibernate-orm by hibernate.

the class BeanValidationEventListener method validate.

private <T> void validate(T object, RepresentationMode mode, EntityPersister persister, SessionFactoryImplementor sessionFactory, GroupsPerOperation.Operation operation) {
    if (object == null || mode != RepresentationMode.POJO) {
        return;
    }
    TraversableResolver tr = new HibernateTraversableResolver(persister, associationsPerEntityPersister, sessionFactory);
    Validator validator = factory.usingContext().traversableResolver(tr).getValidator();
    final Class<?>[] groups = groupsPerOperation.get(operation);
    if (groups.length > 0) {
        final Set<ConstraintViolation<T>> constraintViolations = validator.validate(object, groups);
        if (constraintViolations.size() > 0) {
            Set<ConstraintViolation<?>> propagatedViolations = CollectionHelper.setOfSize(constraintViolations.size());
            Set<String> classNames = new HashSet<>();
            for (ConstraintViolation<?> violation : constraintViolations) {
                LOG.trace(violation);
                propagatedViolations.add(violation);
                classNames.add(violation.getLeafBean().getClass().getName());
            }
            StringBuilder builder = new StringBuilder();
            builder.append("Validation failed for classes ");
            builder.append(classNames);
            builder.append(" during ");
            builder.append(operation.getName());
            builder.append(" time for groups ");
            builder.append(toString(groups));
            builder.append("\nList of constraint violations:[\n");
            for (ConstraintViolation<?> violation : constraintViolations) {
                builder.append("\t").append(violation.toString()).append("\n");
            }
            builder.append("]");
            throw new ConstraintViolationException(builder.toString(), propagatedViolations);
        }
    }
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) Validator(jakarta.validation.Validator) HashSet(java.util.HashSet)

Example 2 with TraversableResolver

use of jakarta.validation.TraversableResolver in project hibernate-validator by hibernate.

the class TraversableResolvers method getDefault.

/**
 * Initializes and returns the default {@link TraversableResolver} depending on the environment.
 * <p>
 * If JPA 2 is present in the classpath, a {@link JPATraversableResolver} instance is returned.
 * <p>
 * Otherwise, it returns an instance of the default {@link TraverseAllTraversableResolver}.
 */
public static TraversableResolver getDefault() {
    // check whether we have Persistence on the classpath
    Class<?> persistenceClass;
    try {
        persistenceClass = run(LoadClass.action(PERSISTENCE_CLASS_NAME, TraversableResolvers.class.getClassLoader()));
    } catch (ValidationException e) {
        LOG.debugf("Cannot find %s on classpath. Assuming non JPA 2 environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME);
        return getTraverseAllTraversableResolver();
    }
    // check whether Persistence contains getPersistenceUtil
    Method persistenceUtilGetter = run(GetMethod.action(persistenceClass, PERSISTENCE_UTIL_METHOD));
    if (persistenceUtilGetter == null) {
        LOG.debugf("Found %s on classpath, but no method '%s'. Assuming JPA 1 environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD);
        return getTraverseAllTraversableResolver();
    }
    // unfortunately there are several incomplete implementations out there (see HV-374)
    try {
        Object persistence = run(NewInstance.action(persistenceClass, "persistence provider"));
        ReflectionHelper.getValue(persistenceUtilGetter, persistence);
    } catch (Exception e) {
        LOG.debugf("Unable to invoke %s.%s. Inconsistent JPA environment. All properties will per default be traversable.", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD);
        return getTraverseAllTraversableResolver();
    }
    LOG.debugf("Found %s on classpath containing '%s'. Assuming JPA 2 environment. Trying to instantiate JPA aware TraversableResolver", PERSISTENCE_CLASS_NAME, PERSISTENCE_UTIL_METHOD);
    try {
        @SuppressWarnings("unchecked") Class<? extends TraversableResolver> jpaAwareResolverClass = (Class<? extends TraversableResolver>) run(LoadClass.action(JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME, TraversableResolvers.class.getClassLoader()));
        LOG.debugf("Instantiated JPA aware TraversableResolver of type %s.", JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME);
        return run(NewInstance.action(jpaAwareResolverClass, ""));
    } catch (ValidationException e) {
        LOG.logUnableToLoadOrInstantiateJPAAwareResolver(JPA_AWARE_TRAVERSABLE_RESOLVER_CLASS_NAME);
        return getTraverseAllTraversableResolver();
    }
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) ValidationException(jakarta.validation.ValidationException) LoadClass(org.hibernate.validator.internal.util.privilegedactions.LoadClass) GetMethod(org.hibernate.validator.internal.util.privilegedactions.GetMethod) Method(java.lang.reflect.Method) ValidationException(jakarta.validation.ValidationException)

Example 3 with TraversableResolver

use of jakarta.validation.TraversableResolver in project hibernate-validator by hibernate.

the class CachedTraversableResolverTest method testCache.

@Test
public void testCache() {
    TraversableResolver resolver = new AskOnceTR();
    Configuration<?> config = Validation.byDefaultProvider().configure().traversableResolver(resolver);
    ValidatorFactory factory = config.buildValidatorFactory();
    Suit suit = createSuit();
    Validator v = factory.getValidator();
    try {
        v.validate(suit, Default.class, Cloth.class);
    } catch (ValidationException e) {
        fail("TraversableResolver called several times for a given object", e);
    }
    v = factory.usingContext().traversableResolver(new AskOnceTR()).getValidator();
    try {
        v.validateProperty(suit, "size", Default.class, Cloth.class);
    } catch (ValidationException e) {
        fail("TraversableResolver called several times for a given object", e);
    }
    v = factory.usingContext().traversableResolver(new AskOnceTR()).getValidator();
    try {
        v.validateValue(Suit.class, "size", 2, Default.class, Cloth.class);
    } catch (ValidationException e) {
        fail("TraversableResolver called several times for a given object", e);
    }
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) ValidationException(jakarta.validation.ValidationException) ValidatorFactory(jakarta.validation.ValidatorFactory) Validator(jakarta.validation.Validator) HibernateValidator(org.hibernate.validator.HibernateValidator) Test(org.testng.annotations.Test)

Example 4 with TraversableResolver

use of jakarta.validation.TraversableResolver in project eclipselink by eclipse-ee4j.

the class BeanValidationListener method getValidator.

private Validator getValidator(DescriptorEvent event) {
    ClassDescriptor descriptor = event.getDescriptor();
    Validator res = validatorMap.get(descriptor);
    if (res == null) {
        TraversableResolver traversableResolver = new AutomaticLifeCycleValidationTraversableResolver(descriptor);
        res = validatorFactory.usingContext().traversableResolver(traversableResolver).getValidator();
        Validator t = validatorMap.put(descriptor, res);
        if (t != null) {
            // Threading collision, use existing
            res = t;
        }
    }
    return res;
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) ClassDescriptor(org.eclipse.persistence.descriptors.ClassDescriptor) Validator(jakarta.validation.Validator)

Example 5 with TraversableResolver

use of jakarta.validation.TraversableResolver in project hibernate-validator by hibernate.

the class ValidatorFactoryBean method createTraversableResolver.

private TraversableResolver createTraversableResolver(Configuration<?> config) {
    BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    String traversableResolverFqcn = bootstrapConfiguration.getTraversableResolverClassName();
    if (traversableResolverFqcn == null) {
        return config.getDefaultTraversableResolver();
    }
    @SuppressWarnings("unchecked") Class<? extends TraversableResolver> traversableResolverClass = (Class<? extends TraversableResolver>) run(LoadClass.action(traversableResolverFqcn, null));
    return createInstance(traversableResolverClass);
}
Also used : TraversableResolver(jakarta.validation.TraversableResolver) BootstrapConfiguration(jakarta.validation.BootstrapConfiguration) LoadClass(org.hibernate.validator.internal.util.privilegedactions.LoadClass)

Aggregations

TraversableResolver (jakarta.validation.TraversableResolver)5 Validator (jakarta.validation.Validator)3 ValidationException (jakarta.validation.ValidationException)2 LoadClass (org.hibernate.validator.internal.util.privilegedactions.LoadClass)2 BootstrapConfiguration (jakarta.validation.BootstrapConfiguration)1 ConstraintViolation (jakarta.validation.ConstraintViolation)1 ConstraintViolationException (jakarta.validation.ConstraintViolationException)1 ValidatorFactory (jakarta.validation.ValidatorFactory)1 Method (java.lang.reflect.Method)1 HashSet (java.util.HashSet)1 ClassDescriptor (org.eclipse.persistence.descriptors.ClassDescriptor)1 HibernateValidator (org.hibernate.validator.HibernateValidator)1 GetMethod (org.hibernate.validator.internal.util.privilegedactions.GetMethod)1 Test (org.testng.annotations.Test)1