Search in sources :

Example 1 with ConstraintValidatorFactory

use of jakarta.validation.ConstraintValidatorFactory in project spring-framework by spring-projects.

the class LocalValidatorFactoryBean method afterPropertiesSet.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void afterPropertiesSet() {
    Configuration<?> configuration;
    if (this.providerClass != null) {
        ProviderSpecificBootstrap bootstrap = Validation.byProvider(this.providerClass);
        if (this.validationProviderResolver != null) {
            bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
        }
        configuration = bootstrap.configure();
    } else {
        GenericBootstrap bootstrap = Validation.byDefaultProvider();
        if (this.validationProviderResolver != null) {
            bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
        }
        configuration = bootstrap.configure();
    }
    // Try Hibernate Validator 5.2's externalClassLoader(ClassLoader) method
    if (this.applicationContext != null) {
        try {
            Method eclMethod = configuration.getClass().getMethod("externalClassLoader", ClassLoader.class);
            ReflectionUtils.invokeMethod(eclMethod, configuration, this.applicationContext.getClassLoader());
        } catch (NoSuchMethodException ex) {
        // Ignore - no Hibernate Validator 5.2+ or similar provider
        }
    }
    MessageInterpolator targetInterpolator = this.messageInterpolator;
    if (targetInterpolator == null) {
        targetInterpolator = configuration.getDefaultMessageInterpolator();
    }
    configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
    if (this.traversableResolver != null) {
        configuration.traversableResolver(this.traversableResolver);
    }
    ConstraintValidatorFactory targetConstraintValidatorFactory = this.constraintValidatorFactory;
    if (targetConstraintValidatorFactory == null && this.applicationContext != null) {
        targetConstraintValidatorFactory = new SpringConstraintValidatorFactory(this.applicationContext.getAutowireCapableBeanFactory());
    }
    if (targetConstraintValidatorFactory != null) {
        configuration.constraintValidatorFactory(targetConstraintValidatorFactory);
    }
    if (this.parameterNameDiscoverer != null) {
        configureParameterNameProvider(this.parameterNameDiscoverer, configuration);
    }
    List<InputStream> mappingStreams = null;
    if (this.mappingLocations != null) {
        mappingStreams = new ArrayList<>(this.mappingLocations.length);
        for (Resource location : this.mappingLocations) {
            try {
                InputStream stream = location.getInputStream();
                mappingStreams.add(stream);
                configuration.addMapping(stream);
            } catch (IOException ex) {
                closeMappingStreams(mappingStreams);
                throw new IllegalStateException("Cannot read mapping resource: " + location);
            }
        }
    }
    this.validationPropertyMap.forEach(configuration::addProperty);
    // Allow for custom post-processing before we actually build the ValidatorFactory.
    postProcessConfiguration(configuration);
    try {
        this.validatorFactory = configuration.buildValidatorFactory();
        setTargetValidator(this.validatorFactory.getValidator());
    } finally {
        closeMappingStreams(mappingStreams);
    }
}
Also used : ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) InputStream(java.io.InputStream) Resource(org.springframework.core.io.Resource) Method(java.lang.reflect.Method) IOException(java.io.IOException) ProviderSpecificBootstrap(jakarta.validation.bootstrap.ProviderSpecificBootstrap) GenericBootstrap(jakarta.validation.bootstrap.GenericBootstrap) ResourceBundleMessageInterpolator(org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator) MessageInterpolator(jakarta.validation.MessageInterpolator)

Example 2 with ConstraintValidatorFactory

use of jakarta.validation.ConstraintValidatorFactory in project today-framework by TAKETODAY.

the class LocalValidatorFactoryBean method afterPropertiesSet.

@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public void afterPropertiesSet() {
    Configuration<?> configuration;
    if (this.providerClass != null) {
        ProviderSpecificBootstrap bootstrap = Validation.byProvider(this.providerClass);
        if (this.validationProviderResolver != null) {
            bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
        }
        configuration = bootstrap.configure();
    } else {
        GenericBootstrap bootstrap = Validation.byDefaultProvider();
        if (this.validationProviderResolver != null) {
            bootstrap = bootstrap.providerResolver(this.validationProviderResolver);
        }
        configuration = bootstrap.configure();
    }
    // Try Hibernate Validator 5.2's externalClassLoader(ClassLoader) method
    if (this.applicationContext != null) {
        try {
            Method eclMethod = configuration.getClass().getMethod("externalClassLoader", ClassLoader.class);
            ReflectionUtils.invokeMethod(eclMethod, configuration, this.applicationContext.getClassLoader());
        } catch (NoSuchMethodException ex) {
        // Ignore - no Hibernate Validator 5.2+ or similar provider
        }
    }
    MessageInterpolator targetInterpolator = this.messageInterpolator;
    if (targetInterpolator == null) {
        targetInterpolator = configuration.getDefaultMessageInterpolator();
    }
    configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator));
    if (this.traversableResolver != null) {
        configuration.traversableResolver(this.traversableResolver);
    }
    ConstraintValidatorFactory targetConstraintValidatorFactory = this.constraintValidatorFactory;
    if (targetConstraintValidatorFactory == null && this.applicationContext != null) {
        targetConstraintValidatorFactory = new ContextConstraintValidatorFactory(this.applicationContext.getAutowireCapableBeanFactory());
    }
    if (targetConstraintValidatorFactory != null) {
        configuration.constraintValidatorFactory(targetConstraintValidatorFactory);
    }
    if (this.parameterNameDiscoverer != null) {
        configureParameterNameProvider(this.parameterNameDiscoverer, configuration);
    }
    List<InputStream> mappingStreams = null;
    if (this.mappingLocations != null) {
        mappingStreams = new ArrayList<>(this.mappingLocations.length);
        for (Resource location : this.mappingLocations) {
            try {
                InputStream stream = location.getInputStream();
                mappingStreams.add(stream);
                configuration.addMapping(stream);
            } catch (IOException ex) {
                closeMappingStreams(mappingStreams);
                throw new IllegalStateException("Cannot read mapping resource: " + location);
            }
        }
    }
    this.validationPropertyMap.forEach(configuration::addProperty);
    // Allow for custom post-processing before we actually build the ValidatorFactory.
    postProcessConfiguration(configuration);
    try {
        this.validatorFactory = configuration.buildValidatorFactory();
        setTargetValidator(this.validatorFactory.getValidator());
    } finally {
        closeMappingStreams(mappingStreams);
    }
}
Also used : ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) InputStream(java.io.InputStream) Resource(cn.taketoday.core.io.Resource) Method(java.lang.reflect.Method) IOException(java.io.IOException) ProviderSpecificBootstrap(jakarta.validation.bootstrap.ProviderSpecificBootstrap) GenericBootstrap(jakarta.validation.bootstrap.GenericBootstrap) ResourceBundleMessageInterpolator(org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator) MessageInterpolator(jakarta.validation.MessageInterpolator)

Example 3 with ConstraintValidatorFactory

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

the class ConstraintValidatorInjectionUnitIT method testSuccessfulInjectionIntoConstraintValidator.

@Test
public void testSuccessfulInjectionIntoConstraintValidator() {
    ConstraintValidatorFactory constraintValidatorFactory = validatorFactory.getConstraintValidatorFactory();
    PingableValidator validator = constraintValidatorFactory.getInstance(PingableValidator.class);
    assertThat(validator).as("Constraint Validator could not be created").isNotNull();
    assertThat(validator.getPingService()).as("The ping service did not get injected").isNotNull();
}
Also used : PingableValidator(org.hibernate.validator.integration.cdi.constraint.PingableValidator) ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) Test(org.testng.annotations.Test)

Example 4 with ConstraintValidatorFactory

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

the class ConstraintValidatorCachingTest method testConstraintValidatorInstancesAreCachedPerConstraintValidatorFactory.

@Test
@TestForIssue(jiraKey = "HV-564")
public void testConstraintValidatorInstancesAreCachedPerConstraintValidatorFactory() {
    Configuration<?> config = getConfiguration();
    OnceInstanceOnlyConstraintValidatorFactory constraintValidatorFactory1 = new OnceInstanceOnlyConstraintValidatorFactory();
    OnceInstanceOnlyConstraintValidatorFactory constraintValidatorFactory2 = new OnceInstanceOnlyConstraintValidatorFactory();
    config.constraintValidatorFactory(constraintValidatorFactory1);
    ValidatorFactory factory = config.buildValidatorFactory();
    Validator validator = factory.getValidator();
    Person john = new Person("John Doe");
    john.setAge(36);
    john.addAddress(new Address("Mysterious Lane", "Mysterious"));
    constraintValidatorFactory1.assertSize(0);
    Set<ConstraintViolation<Person>> violations = validator.validate(john);
    assertNoViolations(violations);
    constraintValidatorFactory1.assertSize(3);
    // getting a new validator with a new constraint factory
    validator = factory.usingContext().constraintValidatorFactory(constraintValidatorFactory2).getValidator();
    constraintValidatorFactory2.assertSize(0);
    violations = validator.validate(john);
    assertNoViolations(violations);
    constraintValidatorFactory2.assertSize(3);
    constraintValidatorFactory1.assertConstraintValidatorInstancesAreNotShared(constraintValidatorFactory2);
    factory.close();
    constraintValidatorFactory1.assertAllConstraintValidatorInstancesReleased();
    constraintValidatorFactory2.assertAllConstraintValidatorInstancesReleased();
}
Also used : ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) ValidatorFactory(jakarta.validation.ValidatorFactory) ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintValidator(jakarta.validation.ConstraintValidator) ValidatorUtil.getValidator(org.hibernate.validator.testutils.ValidatorUtil.getValidator) NotNullValidator(org.hibernate.validator.internal.constraintvalidators.bv.NotNullValidator) Test(org.testng.annotations.Test) TestForIssue(org.hibernate.validator.testutil.TestForIssue)

Example 5 with ConstraintValidatorFactory

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

the class ConstraintValidatorCachingTest method testConstraintValidatorInstancesAreCached.

@Test
@TestForIssue(jiraKey = "HV-564")
public void testConstraintValidatorInstancesAreCached() {
    Configuration<?> config = getConfiguration();
    OnceInstanceOnlyConstraintValidatorFactory constraintValidatorFactory = new OnceInstanceOnlyConstraintValidatorFactory();
    config.constraintValidatorFactory(constraintValidatorFactory);
    ValidatorFactory factory = config.buildValidatorFactory();
    Validator validator = factory.getValidator();
    Person john = new Person("John Doe");
    john.setAge(36);
    john.addAddress(new Address("Mysterious Lane", "Mysterious"));
    constraintValidatorFactory.assertSize(0);
    Set<ConstraintViolation<Person>> violations = validator.validate(john);
    assertNoViolations(violations);
    constraintValidatorFactory.assertSize(3);
    // need to call validate twice to let the cache kick in
    violations = validator.validate(john);
    assertNoViolations(violations);
    constraintValidatorFactory.assertSize(3);
    constraintValidatorFactory.assertKeyExists(SizeValidatorForCollection.class);
    constraintValidatorFactory.assertKeyExists(MinValidatorForInteger.class);
    constraintValidatorFactory.assertKeyExists(NotNullValidator.class);
    // getting a new validator from the same factory should have the same instances cached
    validator = factory.getValidator();
    constraintValidatorFactory.assertSize(3);
    violations = validator.validate(john);
    assertNoViolations(violations);
    constraintValidatorFactory.assertSize(3);
    factory.close();
    constraintValidatorFactory.assertAllConstraintValidatorInstancesReleased();
}
Also used : ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) ValidatorFactory(jakarta.validation.ValidatorFactory) ConstraintViolation(jakarta.validation.ConstraintViolation) Validator(jakarta.validation.Validator) ConstraintValidator(jakarta.validation.ConstraintValidator) ValidatorUtil.getValidator(org.hibernate.validator.testutils.ValidatorUtil.getValidator) NotNullValidator(org.hibernate.validator.internal.constraintvalidators.bv.NotNullValidator) Test(org.testng.annotations.Test) TestForIssue(org.hibernate.validator.testutil.TestForIssue)

Aggregations

ConstraintValidatorFactory (jakarta.validation.ConstraintValidatorFactory)10 Test (org.testng.annotations.Test)4 ConstraintValidator (jakarta.validation.ConstraintValidator)3 ConstraintViolation (jakarta.validation.ConstraintViolation)3 MessageInterpolator (jakarta.validation.MessageInterpolator)3 Validator (jakarta.validation.Validator)3 ValidatorFactory (jakarta.validation.ValidatorFactory)3 GenericBootstrap (jakarta.validation.bootstrap.GenericBootstrap)3 ProviderSpecificBootstrap (jakarta.validation.bootstrap.ProviderSpecificBootstrap)3 IOException (java.io.IOException)3 InputStream (java.io.InputStream)3 Method (java.lang.reflect.Method)3 ResourceBundleMessageInterpolator (org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator)3 StandardBeanFactory (cn.taketoday.beans.factory.support.StandardBeanFactory)2 Resource (cn.taketoday.core.io.Resource)2 NotNullValidator (org.hibernate.validator.internal.constraintvalidators.bv.NotNullValidator)2 TestForIssue (org.hibernate.validator.testutil.TestForIssue)2 ValidatorUtil.getValidator (org.hibernate.validator.testutils.ValidatorUtil.getValidator)2 Test (org.junit.jupiter.api.Test)2 BootstrapConfiguration (jakarta.validation.BootstrapConfiguration)1