@Test public void testCustomConstraintValidatorFactory() { Configuration<?> configuration = Validation.byDefaultProvider().configure(); assertDefaultBuilderAndFactory(configuration); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); Customer customer = new Customer(); customer.setFirstName("John"); Set<ConstraintViolation<Customer>> constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 1, "Wrong number of constraints"); ConstraintViolation<Customer> constraintViolation = constraintViolations.iterator().next(); assertEquals("may not be empty", constraintViolation.getMessage(), "Wrong message"); // get a new factory using a custom configuration configuration = Validation.byDefaultProvider().configure(); configuration.constraintValidatorFactory( new ConstraintValidatorFactory() { public <T extends ConstraintValidator<?, ?>> T getInstance(Class<T> key) { if (key == NotNullValidator.class) { return (T) new BadlyBehavedNotNullConstraintValidator(); } return new ConstraintValidatorFactoryImpl().getInstance(key); } }); factory = configuration.buildValidatorFactory(); validator = factory.getValidator(); constraintViolations = validator.validate(customer); assertEquals(constraintViolations.size(), 0, "Wrong number of constraints"); }
public static ValidatorFactory buildFactory( final ValidationInfo config, final ClassLoader classLoader) { ValidatorFactory factory = null; final Thread thread = Thread.currentThread(); final ClassLoader oldContextLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(classLoader); if (config == null) { factory = Validation.buildDefaultValidatorFactory(); } else { final Configuration<?> configuration = getConfig(config); try { factory = configuration.buildValidatorFactory(); } catch (final ValidationException ve) { thread.setContextClassLoader(ValidatorBuilder.class.getClassLoader()); factory = Validation.buildDefaultValidatorFactory(); thread.setContextClassLoader(classLoader); logger.warning( "Unable create validator factory with config " + config + " (" + ve.getMessage() + ")." + " Default factory will be used."); } } } finally { thread.setContextClassLoader(oldContextLoader); } return factory; }
private Validator configure(String mappingsUrl) { Configuration<?> configuration = ValidatorUtil.getConfiguration(); configuration.traversableResolver(new DummyTraversableResolver()); configuration.addMapping(InheritanceMappingsTest.class.getResourceAsStream(mappingsUrl)); ValidatorFactory validatorFactory = configuration.buildValidatorFactory(); return validatorFactory.getValidator(); }
public static void main(String[] args) { Configuration configuration = Validation.byProvider(HibernateValidator.class).configure(); ValidatorFactory factory = configuration.buildValidatorFactory(); Validator validator = factory.getValidator(); validator.validate(Object.class); // programmation constraint mappings ConstraintMapping mapping = new ConstraintMapping(); }
public static ValidatorFactory createValidatorFactory(ValidatorProvider provider) { Configuration<?> config = Validation.byDefaultProvider().configure(); config.constraintValidatorFactory( new CustomConstraintValidatorFactory( config.getDefaultConstraintValidatorFactory(), provider)); return config.buildValidatorFactory(); }
public ValidationExtension() { Configuration<?> config = Validation.byDefaultProvider().configure(); BootstrapConfiguration bootstrap = config.getBootstrapConfiguration(); globalExecutableTypes = bootstrap.getDefaultValidatedExecutableTypes(); isExecutableValidationEnabled = bootstrap.isExecutableValidationEnabled(); validatorFactory = config.buildValidatorFactory(); validator = validatorFactory.getValidator(); executableHelper = new ExecutableHelper(new TypeResolutionHelper()); }
/** @param theMessageInterpolator */ public GPI18NValidator(IGPI18NMessageInterpolator theMessageInterpolator) { Preconditions.checkArgument( theMessageInterpolator != null, "The Parameter MessageInterpoletor must " + "not be null."); this.messageInterpolator = theMessageInterpolator; Configuration<?> configuration = Validation.byDefaultProvider().configure(); this.validator = configuration .messageInterpolator(this.messageInterpolator) .buildValidatorFactory() .getValidator(); }
@Override public void validateResult( final Object resource, final Invocable resourceMethod, final Object result) { if (configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) { final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<ConstraintViolation<Object>>(); final Method handlingMethod = resourceMethod.getHandlingMethod(); final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass()); final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod( handlingMethod.getName(), handlingMethod.getParameterTypes()); final Method definitionMethod = resourceMethod.getDefinitionMethod(); if (methodDescriptor != null && methodDescriptor.hasConstrainedReturnValue() && validateOnExecutionHandler.validateMethod( resource.getClass(), definitionMethod, handlingMethod)) { constraintViolations.addAll( forExecutables().validateReturnValue(resource, handlingMethod, result)); if (result instanceof Response) { constraintViolations.addAll( forExecutables() .validateReturnValue(resource, handlingMethod, ((Response) result).getEntity())); } } if (!constraintViolations.isEmpty()) { throw new ConstraintViolationException(constraintViolations); } } }
@Override public void validateResourceAndInputParams( final Object resource, final Invocable resourceMethod, final Object[] args) { final Set<ConstraintViolation<Object>> constraintViolations = new HashSet<ConstraintViolation<Object>>(); final BeanDescriptor beanDescriptor = getConstraintsForClass(resource.getClass()); // Resource validation. if (beanDescriptor.isBeanConstrained()) { constraintViolations.addAll(validate(resource)); } if (resourceMethod != null && configuration.getBootstrapConfiguration().isExecutableValidationEnabled()) { final Method handlingMethod = resourceMethod.getHandlingMethod(); // Resource method validation - input parameters. final MethodDescriptor methodDescriptor = beanDescriptor.getConstraintsForMethod( handlingMethod.getName(), handlingMethod.getParameterTypes()); if (methodDescriptor != null && methodDescriptor.hasConstrainedParameters()) { constraintViolations.addAll( forExecutables().validateParameters(resource, handlingMethod, args)); } } if (!constraintViolations.isEmpty()) { throw new ConstraintViolationException(constraintViolations); } }
private void assertDefaultBuilderAndFactory(Configuration configuration) { assertNotNull(configuration); assertTrue(configuration instanceof ConfigurationImpl); ValidatorFactory factory = configuration.buildValidatorFactory(); assertDefaultFactory(factory); }
@Test @SpecAssertion(section = "7", id = "b") public void testXmlConfiguredValidatorConfigurationHasPrecedence() { Configuration<?> config = TestUtil.getConfigurationUnderTest(); InputStream in = getInputStreamForPath( "org/hibernate/beanvalidation/tck/tests/constraints/builtinconstraints/builtin-constraints-override.xml"); config.addMapping(in); Validator validator = config.buildValidatorFactory().getValidator(); DummyEntity dummy = new DummyEntity(); Set<ConstraintViolation<DummyEntity>> violations = validator.validate(dummy); assertCorrectNumberOfViolations(violations, 0); dummy.dummyProperty = "foobar"; violations = validator.validate(dummy); assertCorrectNumberOfViolations(violations, 1); }
public StatisticalValidationState() { ValidatorFactory factory = null; final Configuration<?> configuration = Validation.byDefaultProvider().configure(); try (InputStream mappingStream = StatisticalValidation.class.getResourceAsStream("mapping.xml")) { configuration.addMapping(mappingStream); factory = configuration.buildValidatorFactory(); assertThat(factory).isNotNull(); } catch (IOException e) { e.printStackTrace(); } validator = factory.getValidator(); entitiesUnderTest = IntStream.rangeClosed(0, NUMBER_OF_TEST_ENTITIES) .mapToObj(index -> new TestEntity(index % 10)) .collect(Collectors.toList()); }
// For tests public ValidatorFactory create() throws Exception { Configuration<?> configuration = Validation.byDefaultProvider().configure(); final Map<Locale, ResourceBundle> resourceBundles = readUserResourceBundles(); ResourceBundleLocator resourceBundleLocator = new ResourceBundleLocator() { @Override public ResourceBundle getResourceBundle(Locale locale) { if (!resourceBundles.containsKey(locale)) return resourceBundles.values().iterator().next(); return resourceBundles.get(locale); } }; MessageInterpolator messageInterpolator = new ResourceBundleMessageInterpolator(resourceBundleLocator); return configuration .messageInterpolator(new LocaleContextMessageInterpolator(messageInterpolator)) .buildValidatorFactory(); }
@Override @SuppressWarnings("unchecked") public void afterPropertiesSet() { @SuppressWarnings("rawtypes") Configuration configuration = (this.providerClass != null ? Validation.byProvider(this.providerClass).configure() : Validation.byDefaultProvider().configure()); 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); } configureParameterNameProviderIfPossible(configuration); if (this.mappingLocations != null) { for (Resource location : this.mappingLocations) { try { configuration.addMapping(location.getInputStream()); } catch (IOException ex) { throw new IllegalStateException("Cannot read mapping resource: " + location); } } } for (Map.Entry<String, String> entry : this.validationPropertyMap.entrySet()) { configuration.addProperty(entry.getKey(), entry.getValue()); } // Allow for custom post-processing before we actually build the ValidatorFactory. postProcessConfiguration(configuration); this.validatorFactory = configuration.buildValidatorFactory(); setTargetValidator(this.validatorFactory.getValidator()); }
@Override protected void configure(Configuration cfg) { super.configure(cfg); final MessageInterpolator messageInterpolator = new MessageInterpolator() { public String interpolate(String s, Context context) { return "Oops"; } public String interpolate(String s, Context context, Locale locale) { return interpolate(s, context); } }; final javax.validation.Configuration<?> configuration = Validation.byDefaultProvider().configure(); configuration.messageInterpolator(messageInterpolator); ValidatorFactory vf = configuration.buildValidatorFactory(); cfg.getProperties().put("javax.persistence.validation.factory", vf); cfg.setProperty("javax.persistence.validation.mode", "AUTO"); }
@Test @TestForIssue(jiraKey = "HV-333") public void testContextWithRightDescriptorAndValueAndRootBeanClassIsPassedToMessageInterpolator() { // use a easy mock message interpolator for verifying that the right MessageInterpolatorContext // will be passed MessageInterpolator mock = createMock(MessageInterpolator.class); Configuration<?> config = ValidatorUtil.getConfiguration().messageInterpolator(mock); Validator validator = config.buildValidatorFactory().getValidator(); BeanDescriptor beanDescriptor = validator.getConstraintsForClass(TestBean.class); PropertyDescriptor propertyDescriptor = beanDescriptor.getConstraintsForProperty("test"); Set<ConstraintDescriptor<?>> constraintDescriptors = propertyDescriptor.getConstraintDescriptors(); assertTrue(constraintDescriptors.size() == 1); // prepare the mock interpolator to expect the right interpolate call String validatedValue = "value"; expect( mock.interpolate( MESSAGE, new MessageInterpolatorContext( constraintDescriptors.iterator().next(), validatedValue, TestBean.class, Collections.<String, Object>emptyMap()))) .andReturn("invalid"); replay(mock); Set<ConstraintViolation<TestBean>> violations = validator.validate(new TestBean(validatedValue)); assertNumberOfViolations(violations, 1); // verify that the right context was passed verify(mock); }
private Validator configureValidation(HttpServletRequest req, HttpServletResponse resp) throws IOException { PrintWriter out = resp.getWriter(); GenericBootstrap bootstrap = Validation.byDefaultProvider(); Configuration config = bootstrap.configure(); InputStream mappingsXml = new ByteArrayInputStream(validationXml.getBytes()); config.addMapping(mappingsXml); ValidatorFactory factory = config.buildValidatorFactory(); ValidatorContext validatorContext = factory.usingContext(); Validator validator = validatorContext.getValidator(); if (null == validator) { factory = Validation.byDefaultProvider().configure().buildValidatorFactory(); validator = factory.getValidator(); } out.print("<p>"); out.print("Obtained ValidatorFactory: " + factory + "."); out.print("</p>"); return validator; }
@Override public T messageInterpolator(final MessageInterpolator interpolator) { return delegate.messageInterpolator(interpolator); }
@Override public ParameterNameProvider getDefaultParameterNameProvider() { return delegate.getDefaultParameterNameProvider(); }
@Override public T parameterNameProvider(ParameterNameProvider parameterNameProvider) { return delegate.parameterNameProvider(parameterNameProvider); }
@Override public ValidatorFactory buildValidatorFactory() { return new OpenEJBValidatorFactory(delegate.buildValidatorFactory(), releasables); }
@Override public ConstraintValidatorFactory getDefaultConstraintValidatorFactory() { return delegate.getDefaultConstraintValidatorFactory(); }
@Override public TraversableResolver getDefaultTraversableResolver() { return delegate.getDefaultTraversableResolver(); }
@Override public MessageInterpolator getDefaultMessageInterpolator() { return delegate.getDefaultMessageInterpolator(); }
@Override public T addProperty(final String name, final String value) { return delegate.addProperty(name, value); }
@Override public T addMapping(final InputStream stream) { return delegate.addMapping(stream); }
@Override public T constraintValidatorFactory( final ConstraintValidatorFactory constraintValidatorFactory) { return delegate.constraintValidatorFactory(constraintValidatorFactory); }
@Override public T ignoreXmlConfiguration() { return delegate.ignoreXmlConfiguration(); }
private ValidatorFactory() { Configuration<?> config = Validation.byDefaultProvider().configure(); final MessageInterpolator defaultMessageInterpolator = config.getDefaultMessageInterpolator(); config.messageInterpolator( new MessageInterpolator() { @Override public String interpolate(String messageTemplate, Context context) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } @Override public String interpolate(String messageTemplate, Context context, Locale locale) { String message; if (context.getConstraintDescriptor().getPayload() != null && context.getConstraintDescriptor().getPayload().contains(Localized.class)) { // Retrieve message from message library message = MessageUtility.getLocalizedMessage(messageTemplate, locale).getMessage(); } else { message = defaultMessageInterpolator.interpolate(messageTemplate, context); } return message; } }); // Stop validation if Entity action is DELETE config.traversableResolver( new TraversableResolver() { @Override public boolean isReachable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { if (traversableObject != null && AbstractBindingBean.class.isAssignableFrom(traversableObject.getClass())) { AbstractBindingBean bean = (AbstractBindingBean) traversableObject; if (bean.getEntityAction() != null && bean.getEntityAction() == EntityAction.DELETE) { return false; } } return true; } @Override public boolean isCascadable( Object traversableObject, Node traversableProperty, Class<?> rootBeanType, Path pathToTraversableObject, ElementType elementType) { return true; } }); javax.validation.ValidatorFactory factory = config.buildValidatorFactory(); validator = factory.getValidator(); }
@Override public T traversableResolver(final TraversableResolver resolver) { return delegate.traversableResolver(resolver); }