Search in sources :

Example 6 with ValidationException

use of jakarta.validation.ValidationException 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 7 with ValidationException

use of jakarta.validation.ValidationException 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 8 with ValidationException

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

the class CachedTraversableResolverTest method testCacheDisabled.

@Test
@TestForIssue(jiraKey = "HV-1487")
public void testCacheDisabled() {
    Configuration<?> config = Validation.byProvider(HibernateValidator.class).configure().traversableResolver(new AskOnceTR()).enableTraversableResolverResultCache(false);
    ValidatorFactory factory = config.buildValidatorFactory();
    Suit suit = createSuit();
    // Cache disabled at the factory level
    Validator v = factory.getValidator();
    try {
        v.validate(suit, Default.class, Cloth.class);
        fail("TraversableResolver calls are apparently cached and shouldn't be");
    } catch (ValidationException e) {
    }
    // Cache disabled at the factory level but enabled in the context
    v = ((HibernateValidatorContext) factory.usingContext()).traversableResolver(new AskOnceTR()).enableTraversableResolverResultCache(true).getValidator();
    try {
        v.validate(suit, Default.class, Cloth.class);
    } catch (ValidationException e) {
        fail("TraversableResolver called several times for a given object", e);
    }
    // Cache enabled at the factory level
    config = Validation.byProvider(HibernateValidator.class).configure().traversableResolver(new AskOnceTR());
    factory = config.buildValidatorFactory();
    v = factory.getValidator();
    try {
        v.validate(suit, Default.class, Cloth.class);
    } catch (ValidationException e) {
        fail("TraversableResolver called several times for a given object", e);
    }
    // Cache enabled at the factory level but disabled in the context
    v = ((HibernateValidatorContext) factory.usingContext()).traversableResolver(new AskOnceTR()).enableTraversableResolverResultCache(false).getValidator();
    v = factory.getValidator();
    try {
        v.validate(suit, Default.class, Cloth.class);
        fail("TraversableResolver calls are apparently cached and shouldn't be");
    } catch (ValidationException e) {
    }
}
Also used : HibernateValidator(org.hibernate.validator.HibernateValidator) ValidationException(jakarta.validation.ValidationException) ValidatorFactory(jakarta.validation.ValidatorFactory) Validator(jakarta.validation.Validator) HibernateValidator(org.hibernate.validator.HibernateValidator) Test(org.testng.annotations.Test) TestForIssue(org.hibernate.validator.testutil.TestForIssue)

Example 9 with ValidationException

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

the class JAXBBeanValidator method initValidator.

/**
 * PUBLIC:
 *
 * Initializes validator if not already initialized.
 * If mode is BeanValidationMode.AUTO, then after an unsuccessful try to
 * initialize a Validator, property {@code stopSearchingForValidator} will be set to true.
 *
 * NOTE: Property {@code stopSearchingForValidator} can be reset only by triggering
 * {@link #changeInternalState}.
 *
 * @return {@code true} if validator initialization succeeded, otherwise {@code false}.
 * @throws BeanValidationException
 *              throws {@link org.eclipse.persistence.exceptions.BeanValidationException#PROVIDER_NOT_FOUND}
 */
private boolean initValidator() throws BeanValidationException {
    if (validator == null && !stopSearchingForValidator) {
        try {
            ValidatorFactory factory = getValidatorFactory();
            validator = factory.getValidator();
            printValidatorInfo();
        } catch (ValidationException ve) {
            if (beanValidationMode == BeanValidationMode.CALLBACK) {
                /* The following line ensures that changeInternalState() will be the
                     triggered on next (un)marshalling trials if mode is still CALLBACK.
                      That will ensure searching for Validator implementation again. */
                beanValidationMode = BeanValidationMode.AUTO;
                throw BeanValidationException.providerNotFound(prefix, ve);
            } else {
                // mode AUTO
                // Will not try to initialize validator on next tries.
                stopSearchingForValidator = true;
            }
        }
    }
    return validator != null;
}
Also used : ValidationException(jakarta.validation.ValidationException) BeanValidationException(org.eclipse.persistence.exceptions.BeanValidationException) ValidatorFactory(jakarta.validation.ValidatorFactory)

Example 10 with ValidationException

use of jakarta.validation.ValidationException in project spring-boot by spring-projects.

the class ValidatorAdapter method create.

private static Validator create(MessageSource messageSource) {
    OptionalValidatorFactoryBean validator = new OptionalValidatorFactoryBean();
    try {
        MessageInterpolatorFactory factory = new MessageInterpolatorFactory(messageSource);
        validator.setMessageInterpolator(factory.getObject());
    } catch (ValidationException ex) {
    // Ignore
    }
    return wrap(validator, false);
}
Also used : ValidationException(jakarta.validation.ValidationException) OptionalValidatorFactoryBean(org.springframework.validation.beanvalidation.OptionalValidatorFactoryBean) MessageInterpolatorFactory(org.springframework.boot.validation.MessageInterpolatorFactory)

Aggregations

ValidationException (jakarta.validation.ValidationException)18 ValidatorFactory (jakarta.validation.ValidatorFactory)6 Test (org.testng.annotations.Test)5 Validator (jakarta.validation.Validator)3 NotNull (jakarta.validation.constraints.NotNull)3 ValidationExtension (dev.morphia.validation.ValidationExtension)2 FacesException (jakarta.faces.FacesException)2 Constraint (jakarta.validation.Constraint)2 TraversableResolver (jakarta.validation.TraversableResolver)2 ExecutableType (jakarta.validation.executable.ExecutableType)2 HibernateValidator (org.hibernate.validator.HibernateValidator)2 LoadClass (org.hibernate.validator.internal.util.privilegedactions.LoadClass)2 BranchContext (cd.go.contrib.plugins.configrepo.groovy.dsl.BranchContext)1 BootstrapConfiguration (jakarta.validation.BootstrapConfiguration)1 ConstraintDeclarationException (jakarta.validation.ConstraintDeclarationException)1 ConstraintDefinitionException (jakarta.validation.ConstraintDefinitionException)1 GroupDefinitionException (jakarta.validation.GroupDefinitionException)1 Payload (jakarta.validation.Payload)1 Validation.buildDefaultValidatorFactory (jakarta.validation.Validation.buildDefaultValidatorFactory)1 AssertFalse (jakarta.validation.constraints.AssertFalse)1