Search in sources :

Example 1 with ClockProvider

use of jakarta.validation.ClockProvider in project tomee by apache.

the class ValidatorBuilder method getConfig.

@SuppressWarnings("unchecked")
private static Configuration<?> getConfig(final ValidationInfo info) {
    Configuration<?> target = null;
    final Thread thread = Thread.currentThread();
    final ClassLoader classLoader = thread.getContextClassLoader();
    String providerClassName = info.providerClassName;
    if (providerClassName == null) {
        providerClassName = SystemInstance.get().getOptions().get(VALIDATION_PROVIDER_KEY, (String) null);
    }
    if (providerClassName != null) {
        try {
            @SuppressWarnings({ "unchecked", "rawtypes" }) final Class clazz = classLoader.loadClass(providerClassName);
            target = Validation.byProvider(clazz).configure();
            logger.info("Using " + providerClassName + " as validation provider.");
        } catch (final ClassNotFoundException e) {
            logger.warning("Unable to load provider class " + providerClassName, e);
        } catch (final ValidationException ve) {
            logger.warning("Unable create validator factory with provider " + providerClassName + " (" + ve.getMessage() + ")." + " Default one will be used.");
        }
    }
    if (target == null) {
        // force to use container provider to ignore any conflicting configuration
        thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader());
        target = Validation.byDefaultProvider().configure();
        thread.setContextClassLoader(classLoader);
    }
    final Set<ExecutableType> types = EnumSet.noneOf(ExecutableType.class);
    for (final String type : info.validatedTypes) {
        types.add(ExecutableType.valueOf(type));
    }
    final Map<String, String> props = new HashMap<>();
    for (final Map.Entry<Object, Object> entry : info.propertyTypes.entrySet()) {
        final PropertyType property = new PropertyType();
        property.setName((String) entry.getKey());
        property.setValue((String) entry.getValue());
        props.put(property.getName(), property.getValue());
        if (logger.isDebugEnabled()) {
            logger.debug("Found property '" + property.getName() + "' with value '" + property.getValue());
        }
        target.addProperty(property.getName(), property.getValue());
    }
    final OpenEjbBootstrapConfig bootstrapConfig = new OpenEjbBootstrapConfig(providerClassName, info.constraintFactoryClass, info.messageInterpolatorClass, info.traversableResolverClass, info.parameterNameProviderClass, new LinkedHashSet<>(info.constraintMappings), info.executableValidationEnabled, types, props, info.clockProviderClassName, info.valueExtractorClassNames == null ? null : new LinkedHashSet<>(info.valueExtractorClassNames));
    final OpenEjbConfig config = new OpenEjbConfig(bootstrapConfig, target);
    try {
        target.ignoreXmlConfiguration();
        logger.info("Ignoring XML Configuration for validator " + target.getClass().getName());
    } catch (final Exception e) {
        logger.warning("Unable to ignore XML Configuration for validator " + target.getClass().getName(), e);
    }
    final String messageInterpolatorClass = info.messageInterpolatorClass;
    if (messageInterpolatorClass != null) {
        try {
            @SuppressWarnings("unchecked") final Class<MessageInterpolator> clazz = (Class<MessageInterpolator>) classLoader.loadClass(messageInterpolatorClass);
            target.messageInterpolator(newInstance(config, clazz));
            logger.info("Using " + messageInterpolatorClass + " as message interpolator.");
        } catch (final Exception e) {
            logger.warning("Unable to set " + messageInterpolatorClass + " as message interpolator.", e);
        }
    }
    final String traversableResolverClass = info.traversableResolverClass;
    if (traversableResolverClass != null) {
        try {
            @SuppressWarnings("unchecked") final Class<TraversableResolver> clazz = (Class<TraversableResolver>) classLoader.loadClass(traversableResolverClass);
            target.traversableResolver(newInstance(config, clazz));
            logger.info("Using " + traversableResolverClass + " as traversable resolver.");
        } catch (final Exception e) {
            logger.warning("Unable to set " + traversableResolverClass + " as traversable resolver.", e);
        }
    }
    final String constraintFactoryClass = info.constraintFactoryClass;
    if (constraintFactoryClass != null) {
        try {
            @SuppressWarnings("unchecked") final Class<ConstraintValidatorFactory> clazz = (Class<ConstraintValidatorFactory>) classLoader.loadClass(constraintFactoryClass);
            target.constraintValidatorFactory(newInstance(config, clazz));
        } catch (final Exception e) {
            logger.warning("Unable to set " + constraintFactoryClass + " as constraint factory.", e);
        }
        logger.info("Using " + constraintFactoryClass + " as constraint factory.");
    }
    for (final String mappingFileName : info.constraintMappings) {
        if (logger.isDebugEnabled()) {
            logger.debug("Opening input stream for " + mappingFileName);
        }
        final InputStream in = classLoader.getResourceAsStream(mappingFileName);
        if (in == null) {
            logger.warning("Unable to open input stream for mapping file " + mappingFileName + ". It will be ignored");
        } else {
            target.addMapping(in);
        }
    }
    if (info.parameterNameProviderClass != null) {
        try {
            final Class<ParameterNameProvider> clazz = (Class<ParameterNameProvider>) classLoader.loadClass(info.parameterNameProviderClass);
            target.parameterNameProvider(newInstance(config, clazz));
            logger.info("Using " + info.parameterNameProviderClass + " as parameter name provider.");
        } catch (final Exception e) {
            logger.warning("Unable to set " + info.parameterNameProviderClass + " as parameter name provider.", e);
        }
    }
    if (info.valueExtractorClassNames != null) {
        try {
            info.valueExtractorClassNames.stream().map(it -> {
                try {
                    return (ValueExtractor<?>) newInstance(config, classLoader.loadClass(it));
                } catch (final Exception e) {
                    logger.warning("Unable to load " + it, e);
                    return null;
                }
            }).filter(Objects::nonNull).forEach(target::addValueExtractor);
            logger.info("Using " + info.valueExtractorClassNames + " value extractors.");
        } catch (final Exception e) {
            logger.warning("Unable to set " + info.valueExtractorClassNames + " as parameter name provider.", e);
        }
    }
    if (info.clockProviderClassName != null) {
        try {
            final Class<ClockProvider> clazz = (Class<ClockProvider>) classLoader.loadClass(info.clockProviderClassName);
            target.clockProvider(newInstance(config, clazz));
            logger.info("Using " + info.clockProviderClassName + " as clock provider.");
        } catch (final Exception e) {
            logger.warning("Unable to set " + info.clockProviderClassName + " as clock provider.", e);
        }
    }
    return config;
}
Also used : ExecutableType(jakarta.validation.executable.ExecutableType) LinkedHashSet(java.util.LinkedHashSet) ValidationException(jakarta.validation.ValidationException) HashMap(java.util.HashMap) ConstraintValidatorFactory(jakarta.validation.ConstraintValidatorFactory) PropertyType(org.apache.openejb.jee.bval.PropertyType) ClockProvider(jakarta.validation.ClockProvider) InputStream(java.io.InputStream) ValueExtractor(jakarta.validation.valueextraction.ValueExtractor) NamingException(javax.naming.NamingException) ValidationException(jakarta.validation.ValidationException) TraversableResolver(jakarta.validation.TraversableResolver) ParameterNameProvider(jakarta.validation.ParameterNameProvider) HashMap(java.util.HashMap) Map(java.util.Map) MessageInterpolator(jakarta.validation.MessageInterpolator)

Example 2 with ClockProvider

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

the class ValidatorFactoryBean method createClockProvider.

private ClockProvider createClockProvider(Configuration<?> config) {
    BootstrapConfiguration bootstrapConfiguration = config.getBootstrapConfiguration();
    String clockProviderFqcn = bootstrapConfiguration.getClockProviderClassName();
    if (clockProviderFqcn == null) {
        return config.getDefaultClockProvider();
    }
    @SuppressWarnings("unchecked") Class<? extends ClockProvider> clockProviderClass = (Class<? extends ClockProvider>) run(LoadClass.action(clockProviderFqcn, null));
    return createInstance(clockProviderClass);
}
Also used : BootstrapConfiguration(jakarta.validation.BootstrapConfiguration) LoadClass(org.hibernate.validator.internal.util.privilegedactions.LoadClass) ClockProvider(jakarta.validation.ClockProvider)

Example 3 with ClockProvider

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

the class ConstraintValidatorManagerTest method testValidatorsAreCachedPerConstraintAndAnnotationMembersAndClockProvider.

@Test
@TestForIssue(jiraKey = "HV-1589")
public void testValidatorsAreCachedPerConstraintAndAnnotationMembersAndClockProvider() {
    Validator validator = getConfiguration().addMapping(ConstraintValidatorManagerTest.class.getResourceAsStream("hv-1589-mapping.xml")).buildValidatorFactory().getValidator();
    ConstraintDescriptorImpl<?> sizeOnMiddleNameDescriptor = getSingleConstraintDescriptorForProperty(validator, User.class, "middleName");
    ConstraintDescriptorImpl<?> sizeOnAddress1Descriptor = getSingleConstraintDescriptorForProperty(validator, User.class, "address1");
    ConstraintDescriptorImpl<?> sizeOnAddress2Descriptor = getSingleConstraintDescriptorForProperty(validator, User.class, "address2");
    ScriptEvaluatorFactory scriptEvaluatorFactory = new DefaultScriptEvaluatorFactory(null);
    ClockProvider clockProvider1 = new ClockProvider() {

        @Override
        public Clock getClock() {
            return null;
        }
    };
    ClockProvider clockProvider2 = new ClockProvider() {

        @Override
        public Clock getClock() {
            return null;
        }
    };
    HibernateConstraintValidatorInitializationContext initializationContext1 = getConstraintValidatorInitializationContext(scriptEvaluatorFactory, clockProvider1, Duration.ZERO);
    HibernateConstraintValidatorInitializationContext initializationContext2 = getConstraintValidatorInitializationContext(scriptEvaluatorFactory, clockProvider2, Duration.ZERO);
    ConstraintValidator<?, ?> sizeValidatorForMiddleNameCtx1 = constraintValidatorManager.getInitializedValidator(String.class, sizeOnMiddleNameDescriptor, constraintValidatorFactory, initializationContext1);
    ConstraintValidator<?, ?> sizeValidatorForAddress1Ctx1 = constraintValidatorManager.getInitializedValidator(String.class, sizeOnAddress1Descriptor, constraintValidatorFactory, initializationContext1);
    ConstraintValidator<?, ?> sizeValidatorForAddress2Ctx1 = constraintValidatorManager.getInitializedValidator(String.class, sizeOnAddress2Descriptor, constraintValidatorFactory, initializationContext1);
    ConstraintValidator<?, ?> sizeValidatorForAddress2Ctx2 = constraintValidatorManager.getInitializedValidator(String.class, sizeOnAddress2Descriptor, constraintValidatorFactory, initializationContext2);
    ConstraintValidator<?, ?> sizeValidatorForAddress1Ctx2 = constraintValidatorManager.getInitializedValidator(String.class, sizeOnAddress1Descriptor, constraintValidatorFactory, initializationContext2);
    assertThat(sizeValidatorForMiddleNameCtx1).isNotSameAs(sizeValidatorForAddress1Ctx1);
    assertThat(sizeValidatorForAddress1Ctx1).isSameAs(sizeValidatorForAddress2Ctx1);
    assertThat(sizeValidatorForAddress1Ctx1).isNotSameAs(sizeValidatorForAddress2Ctx2);
    assertThat(sizeValidatorForAddress2Ctx2).isSameAs(sizeValidatorForAddress1Ctx2);
}
Also used : DefaultScriptEvaluatorFactory(org.hibernate.validator.internal.engine.scripting.DefaultScriptEvaluatorFactory) HibernateConstraintValidatorInitializationContext(org.hibernate.validator.constraintvalidation.HibernateConstraintValidatorInitializationContext) ClockProvider(jakarta.validation.ClockProvider) DefaultClockProvider(org.hibernate.validator.internal.engine.DefaultClockProvider) DefaultScriptEvaluatorFactory(org.hibernate.validator.internal.engine.scripting.DefaultScriptEvaluatorFactory) ScriptEvaluatorFactory(org.hibernate.validator.spi.scripting.ScriptEvaluatorFactory) 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 4 with ClockProvider

use of jakarta.validation.ClockProvider in project beanvalidation-tck by eclipse-ee4j.

the class ManagedObjectsTest method testClockProviderIsSubjectToDependencyInjection.

@Test
@SpecAssertion(section = Sections.INTEGRATION_GENERAL_OBJECTSLIFECYCLE, id = "d")
@SpecAssertion(section = Sections.INTEGRATION_DEPENDENCYINJECTION_CUSTOMCONFIGURATION, id = "a")
@SpecAssertion(section = Sections.INTEGRATION_DEPENDENCYINJECTION, id = "a")
public void testClockProviderIsSubjectToDependencyInjection() {
    assertNotNull(defaultValidatorFactory);
    ClockProvider clockProvider = defaultValidatorFactory.getClockProvider();
    assertEquals(clockProvider.getClock().getZone(), Greeter.ZONE_ID);
}
Also used : ClockProvider(jakarta.validation.ClockProvider) AbstractTCKTest(org.hibernate.beanvalidation.tck.tests.AbstractTCKTest) Test(org.testng.annotations.Test) IntegrationTest(org.hibernate.beanvalidation.tck.util.IntegrationTest) SpecAssertion(org.jboss.test.audit.annotations.SpecAssertion)

Aggregations

ClockProvider (jakarta.validation.ClockProvider)4 Test (org.testng.annotations.Test)2 BootstrapConfiguration (jakarta.validation.BootstrapConfiguration)1 ConstraintValidator (jakarta.validation.ConstraintValidator)1 ConstraintValidatorFactory (jakarta.validation.ConstraintValidatorFactory)1 MessageInterpolator (jakarta.validation.MessageInterpolator)1 ParameterNameProvider (jakarta.validation.ParameterNameProvider)1 TraversableResolver (jakarta.validation.TraversableResolver)1 ValidationException (jakarta.validation.ValidationException)1 Validator (jakarta.validation.Validator)1 ExecutableType (jakarta.validation.executable.ExecutableType)1 ValueExtractor (jakarta.validation.valueextraction.ValueExtractor)1 InputStream (java.io.InputStream)1 HashMap (java.util.HashMap)1 LinkedHashSet (java.util.LinkedHashSet)1 Map (java.util.Map)1 NamingException (javax.naming.NamingException)1 PropertyType (org.apache.openejb.jee.bval.PropertyType)1 AbstractTCKTest (org.hibernate.beanvalidation.tck.tests.AbstractTCKTest)1 IntegrationTest (org.hibernate.beanvalidation.tck.util.IntegrationTest)1