@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");
  }
Example #2
0
  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 void assertDefaultBuilderAndFactory(Configuration configuration) {
    assertNotNull(configuration);
    assertTrue(configuration instanceof ConfigurationImpl);

    ValidatorFactory factory = configuration.buildValidatorFactory();
    assertDefaultFactory(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());
  }
  @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());
  }
  @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());
    }
  @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;
  }
  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();
  }
Example #15
0
 @Override
 public ValidatorFactory buildValidatorFactory() {
   return new OpenEJBValidatorFactory(delegate.buildValidatorFactory(), releasables);
 }
 @Override
 public NotifyingValidatorFactory buildValidatorFactory() {
   ValidatorFactory validatorFactory = configuration.buildValidatorFactory();
   return new DefaultNotifyingValidatorFactory(validatorFactory);
 }