org.hibernate.validator.HibernateValidator Java Examples

The following examples show how to use org.hibernate.validator.HibernateValidator. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}

	Validator nativeValidator = validator.unwrap(Validator.class);
	assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate"));
	assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory);
	assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory);

	validator.destroy();
}
 
Example #2
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}

	Validator nativeValidator = validator.unwrap(Validator.class);
	assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate"));
	assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory);
	assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory);

	validator.destroy();
}
 
Example #3
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}

	Validator nativeValidator = validator.unwrap(Validator.class);
	assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate"));
	assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory);
	assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory);

	validator.destroy();
}
 
Example #4
Source File: ValidatedConfiguration.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
private List<String> validate(final DivolteConfiguration divolteConfiguration) {
    final Validator validator = Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .buildValidatorFactory()
            .getValidator();

    final Set<ConstraintViolation<DivolteConfiguration>> validationErrors = validator.validate(divolteConfiguration);

    return validationErrors
            .stream()
            .map(
                    (e) -> String.format(
                            "Property '%s' %s. Found: '%s'.",
                            DOT_JOINER.join("divolte", e.getPropertyPath()),
                            e.getMessage(),
                            e.getInvalidValue()))
            .collect(Collectors.toList());
}
 
Example #5
Source File: ValidationTest.java    From rest.vertx with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void start() {

    before();

    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure();

    Validator validator = configuration.buildValidatorFactory()
            .getValidator();


    Router router = new RestBuilder(vertx)
            .register(TestValidRest.class)
            .validateWith(validator)
            .build();

    vertx.createHttpServer()
            .requestHandler(router)
            .listen(PORT, vertxTestContext.completing());
}
 
Example #6
Source File: ValidationInterceptor.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
public Object invoke(final MethodInvocation mi) throws Throwable {
  checkNotNull(methodValidator);

  final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(HibernateValidator.class.getClassLoader());
    final Validate validate = mi.getMethod().getAnnotation(Validate.class);

    validateParameters(mi.getThis(), mi.getMethod(), mi.getArguments(), validate.groups());

    final Object result = mi.proceed();

    validateReturnValue(mi.getThis(), mi.getMethod(), result, validate.groups());

    return result;
  }
  finally {
    Thread.currentThread().setContextClassLoader(tccl);
  }
}
 
Example #7
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}

	Validator nativeValidator = validator.unwrap(Validator.class);
	assertTrue(nativeValidator.getClass().getName().startsWith("org.hibernate"));
	assertTrue(validator.unwrap(ValidatorFactory.class) instanceof HibernateValidatorFactory);
	assertTrue(validator.unwrap(HibernateValidatorFactory.class) instanceof HibernateValidatorFactory);

	validator.destroy();
}
 
Example #8
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();
	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}
	validator.destroy();
}
 
Example #9
Source File: BeanValidationImpl.java    From cuba with Apache License 2.0 6 votes vote down vote up
protected HibernateValidatorConfiguration getValidatorFactoryConfiguration(Locale locale) {
    HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class)
            .configure()
            .clockProvider(new CubaValidationTimeProvider(timeSource))
            .traversableResolver(new CubaValidationTraversableResolver(metadata, entityStates))
            .messageInterpolator(new CubaValidationMessagesInterpolator(messages, locale));

    ConstraintMapping constraintMapping = configuration.createConstraintMapping();

    //Hibernate validators doesn't support java.sql.Date.
    //Replace standard validators for java.util.Date with support java.sql.Date
    registerPastValidators(constraintMapping.constraintDefinition(Past.class));
    registerPastOrPresentValidators(constraintMapping.constraintDefinition(PastOrPresent.class));
    registerFutureValidators(constraintMapping.constraintDefinition(Future.class));
    registerFutureOrPresentValidators(constraintMapping.constraintDefinition(FutureOrPresent.class));

    configuration.addMapping(constraintMapping);

    return configuration;
}
 
Example #10
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleValidationWithCustomProvider() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.setProviderClass(HibernateValidator.class);
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(2, result.size());
	for (ConstraintViolation<ValidPerson> cv : result) {
		String path = cv.getPropertyPath().toString();
		if ("name".equals(path) || "address.street".equals(path)) {
			assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NotNull);
		}
		else {
			fail("Invalid constraint violation with path '" + path + "'");
		}
	}
	validator.destroy();
}
 
Example #11
Source File: GraphiteConfigurationTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  validator.setProviderClass(HibernateValidator.class);
  validator.afterPropertiesSet();

  graphiteConfiguration.setPort(100);
  graphiteConfiguration.setHost("host");
  graphiteConfiguration.setPrefix("prefix");
  graphiteConfiguration.setPollInterval(100);
  graphiteConfiguration.setPollIntervalTimeUnit(TimeUnit.MICROSECONDS);
  graphiteConfiguration.init();
}
 
Example #12
Source File: HibernateValidation.java    From validator-web with Apache License 2.0 5 votes vote down vote up
@Override
public void initialize(ValidationContext context) {
    context.setValidatorDelegate(this);
    
    HibernateValidatorConfiguration configure = javax.validation.Validation.byProvider(HibernateValidator.class).configure();
    if (context instanceof ValidationContext.Accessor) {
        configure.failFast(((ValidationContext.Accessor) context).isFailFast());
    }
    ValidatorFactory factory = configure.buildValidatorFactory();
    validator = factory.getValidator();
}
 
Example #13
Source File: AbstractMetaStoreTest.java    From waggle-dance with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
  validator.setProviderClass(HibernateValidator.class);
  validator.afterPropertiesSet();

  metaStore.setRemoteMetaStoreUris(remoteMetaStoreUri);
  metaStore.setName(name);
}
 
Example #14
Source File: InputValidation.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public InputValidation() {

    HibernateValidatorConfiguration config = Validation.byProvider(HibernateValidator.class).configure();
    this.validator = config
        .addMapping(configureTransforms(config.createConstraintMapping()))
        .buildValidatorFactory()
        .getValidator();
  }
 
Example #15
Source File: EmailValidatorTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected Validator createValidator() {
    return Validation
            .byProvider(HibernateValidator.class)
            .configure()
            .buildValidatorFactory()
            .getValidator();
}
 
Example #16
Source File: ValidationModule.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Provides
@Singleton
ValidatorFactory validatorFactory(ConstraintValidatorFactory constraintValidatorFactory) {
  ClassLoader tccl = Thread.currentThread().getContextClassLoader();
  try {
    Thread.currentThread().setContextClassLoader(HibernateValidator.class.getClassLoader());

    ValidatorFactory factory = Validation.byDefaultProvider().configure()
        .constraintValidatorFactory(constraintValidatorFactory)
        .parameterNameProvider(new AopAwareParanamerParameterNameProvider())
        .traversableResolver(new AlwaysTraversableResolver())
        .messageInterpolator(new ParameterMessageInterpolator())
        .buildValidatorFactory();

    // FIXME: Install custom MessageInterpolator that can properly find/merge ValidationMessages.properties for bundles

    // exercise interpolator to preload elements (avoids issues later when TCCL might be different)
    factory.getValidator().validate(new Object()
    {
      // minimal token message
      @NotNull(message = "{org.sonatype.nexus.validation.constraint.notnull}")
      String empty;
    });

    return factory;
  }
  finally {
    Thread.currentThread().setContextClassLoader(tccl);
  }
}
 
Example #17
Source File: CloudWatchReporterFactoryTest.java    From dropwizard-metrics-cloudwatch with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyConfigurable() throws Exception {
    ObjectMapper mapper = Jackson.newObjectMapper();

    // dropwizard 0.9.1 changed the validation wiring a bit..
    Class<ValidatedValueUnwrapper> optValidatorClazz = (Class<ValidatedValueUnwrapper>) Class
            .forName("io.dropwizard.validation.valuehandling.OptionalValidatedValueUnwrapper");

    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    if (optValidatorClazz != null) {
        validator = Validation.byProvider(HibernateValidator.class).configure()
                .addValidatedValueHandler(optValidatorClazz.newInstance())
                .buildValidatorFactory().getValidator();
    }

    ConfigurationFactory<CloudWatchReporterFactory> configFactory =
            new ConfigurationFactory<>(CloudWatchReporterFactory.class,
                    validator, mapper, "dw");
    CloudWatchReporterFactory f = configFactory.build(new File(Resources.getResource("cw.yml").getFile()));

    assertEquals("[env=default]", f.getGlobalDimensions().toString());
    assertEquals("us-east-1", f.getAwsRegion());
    assertEquals("a.b", f.getNamespace());
    assertEquals("XXXXX", f.getAwsSecretKey());
    assertEquals("11111", f.getAwsAccessKeyId());
    assertEquals("p.neustar.biz", f.getAwsClientConfiguration().getProxyHost());
    assertNull(f.getAwsClientConfiguration().getProxyUsername());
}
 
Example #18
Source File: ServiceMain.java    From helios with Apache License 2.0 5 votes vote down vote up
protected static Environment createEnvironment(final String name) {
  final Validator validator = Validation
      .byProvider(HibernateValidator.class)
      .configure()
      .addValidatedValueHandler(new OptionalValidatedValueUnwrapper())
      .buildValidatorFactory()
      .getValidator();
  return new Environment(name,
      Jackson.newObjectMapper(),
      validator,
      new MetricRegistry(),
      Thread.currentThread().getContextClassLoader());
}
 
Example #19
Source File: ClusterV4RequestTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    underTest = new ClusterV4Request();
    localValidatorFactory = new LocalValidatorFactoryBean();
    localValidatorFactory.setProviderClass(HibernateValidator.class);
    localValidatorFactory.afterPropertiesSet();
}
 
Example #20
Source File: BlueprintRequestTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    underTest = new BlueprintV4Request();
    localValidatorFactory = new LocalValidatorFactoryBean();
    localValidatorFactory.setProviderClass(HibernateValidator.class);
    localValidatorFactory.afterPropertiesSet();
}
 
Example #21
Source File: HibernateValidatorPro.java    From spring-boot-start-current with Apache License 2.0 5 votes vote down vote up
/**
 * 线程安全的
 *
 * @return {@link Validator}
 */
public static Validator getHibernateValidator () {
    return Validation.byProvider( HibernateValidator.class )
		 .configure()
		 .buildValidatorFactory()
		 .getValidator();
}
 
Example #22
Source File: NoBootTest.java    From zuihou-admin-boot with Apache License 2.0 5 votes vote down vote up
public Validator getValidator() {
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            //快速失败返回模式
            .addProperty("hibernate.validator.fail_fast", "false")
            .buildValidatorFactory();
    return validatorFactory.getValidator();
}
 
Example #23
Source File: ValidatorConfig.java    From spring-boot-vue-admin with Apache License 2.0 5 votes vote down vote up
@Bean
public Validator validatorFailFast() {
  final ValidatorFactory validatorFactory =
      Validation.byProvider(HibernateValidator.class)
          .configure()
          .addProperty("hibernate.validator.fail_fast", "true")
          .buildValidatorFactory();
  return validatorFactory.getValidator();
}
 
Example #24
Source File: TarocoCommonAutoConfig.java    From Taroco with Apache License 2.0 5 votes vote down vote up
/**
 * 定义 Validator bean
 * 一个校验失败就立即返回
 */
@Bean
public Validator validator() {
    return Validation.byProvider(HibernateValidator.class)
            .configure()
            .failFast(true)
            .buildValidatorFactory()
            .getValidator();
}
 
Example #25
Source File: HibernateValidateConfig.java    From spring-boot-api-project-seed with Apache License 2.0 5 votes vote down vote up
@Bean
public LocalValidatorFactoryBean validator() {
    LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
    localValidatorFactoryBean.setProviderClass(HibernateValidator.class);
    localValidatorFactoryBean.setValidationMessageSource(messageSource());
    return localValidatorFactoryBean;
}
 
Example #26
Source File: NoBootTest.java    From zuihou-admin-cloud with Apache License 2.0 5 votes vote down vote up
public Validator getValidator() {
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
            .configure()
            //快速失败返回模式
            .addProperty("hibernate.validator.fail_fast", "false")
            .buildValidatorFactory();
    return validatorFactory.getValidator();
}
 
Example #27
Source File: ValidationUtil.java    From BlogManagePlatform with Apache License 2.0 5 votes vote down vote up
@PostConstruct
private void init() {
	ValidatorProperties properties = ContextUtil.bean(ValidatorProperties.class);
	HibernateValidatorConfiguration configuration = Validation.byProvider(HibernateValidator.class).configure();
	//配置hibernate-validator消息插值源
	MessageInterpolator interpolator = new ResourceBundleMessageInterpolator(new PlatformResourceBundleLocator(properties
		.getMessageConfigPath()));
	configuration.messageInterpolator(interpolator);
	//配置快速失败
	configuration.failFast(properties.getFailFast());
	failFast = properties.getFailFast();
	engine = configuration.buildValidatorFactory().getValidator();
}
 
Example #28
Source File: ParameterValidatorFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public ParameterValidatorFilter() {
  ValidatorFactory factory =
      Validation.byProvider(HibernateValidator.class)
          .configure()
          .propertyNodeNameProvider(new JacksonPropertyNodeNameProvider())
          .messageInterpolator(messageInterpolator())
          .buildValidatorFactory();
  validator = factory.getValidator().forExecutables();
}
 
Example #29
Source File: NoDuplicateValidatorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public NoDuplicateValidatorTest() {
    final JavaBeanHelper javaBeanHelper = new JavaBeanHelper(new DefaultGetterPropertySelectionStrategy(), new DefaultPropertyNodeNameProvider());
    final DefaultConstraintMapping mapping = new DefaultConstraintMapping(javaBeanHelper);
    mapping.constraintDefinition(NoDuplicateExtension.class).validatedBy(NoDuplicateExtensionValidator.class);
    mapping.constraintDefinition(NoDuplicateIntegration.class).validatedBy(NoDuplicateIntegrationValidator.class);

    final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
        .constraintValidatorFactory(constraintValidatorFactory)
        .addMapping(mapping).buildValidatorFactory();

    validator = validatorFactory.getValidator();

}
 
Example #30
Source File: IntegrationTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public IntegrationTest() {
    final JavaBeanHelper javaBeanHelper = new JavaBeanHelper(new DefaultGetterPropertySelectionStrategy(), new DefaultPropertyNodeNameProvider());
    final DefaultConstraintMapping mapping = new DefaultConstraintMapping(javaBeanHelper);

    mapping.constraintDefinition(NoDuplicateIntegration.class).validatedBy(UniqnenessValidator.class);
    final ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
        .addMapping(mapping).buildValidatorFactory();

    validator = validatorFactory.getValidator();
}