Java Code Examples for javax.validation.ValidatorFactory

The following examples show how to use javax.validation.ValidatorFactory. These examples are extracted from open source projects. 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 Project: lams   Source File: TypeSafeActivator.java    License: GNU General Public License v2.0 6 votes vote down vote up
@SuppressWarnings("UnusedDeclaration")
public static void activate(ActivationContext activationContext) {
	final ValidatorFactory factory;
	try {
		factory = getValidatorFactory( activationContext );
	}
	catch (IntegrationException e) {
		if ( activationContext.getValidationModes().contains( ValidationMode.CALLBACK ) ) {
			throw new IntegrationException( "Bean Validation provider was not available, but 'callback' validation was requested", e );
		}
		if ( activationContext.getValidationModes().contains( ValidationMode.DDL ) ) {
			throw new IntegrationException( "Bean Validation provider was not available, but 'ddl' validation was requested", e );
		}

		LOG.debug( "Unable to acquire Bean Validation ValidatorFactory, skipping activation" );
		return;
	}

	applyRelationalConstraints( factory, activationContext );

	applyCallbackListeners( factory, activationContext );
}
 
Example 2
Source Project: lams   Source File: TypeSafeActivator.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static ValidatorFactory resolveProvidedFactory(SessionFactoryOptions options) {
	final Object validatorFactoryReference = options.getValidatorFactoryReference();

	if ( validatorFactoryReference == null ) {
		return null;
	}

	try {
		return ValidatorFactory.class.cast( validatorFactoryReference );
	}
	catch ( ClassCastException e ) {
		throw new IntegrationException(
				String.format(
						Locale.ENGLISH,
						"ValidatorFactory reference (provided via %s) was not castable to %s : %s",
						SessionFactoryOptions.class.getName(),
						ValidatorFactory.class.getName(),
						validatorFactoryReference.getClass().getName()
				)
		);
	}
}
 
Example 3
Source Project: ozark   Source File: BeanValidationProducer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * We should be able to get a ValidatorFactory from the container in an Java EE environment.
 * However, if we don't get the factory, we will will use a default one. This is especially
 * useful for non Java EE environments and in the CDI tests
 */
@PostConstruct
public void init() {

    // Prefer the ValidatorFactory provided by the container
    Iterator<ValidatorFactory> iterator = validatorFactoryInstance.iterator();
    if (iterator.hasNext()) {
        this.validatorFactory = iterator.next();
    }

    // create a default factory if we didn't get one
    else {
        log.warning("Creating a ValidatorFactory because the container didn't provide one!");
        this.validatorFactory = Validation.buildDefaultValidatorFactory();
    }

}
 
Example 4
Source Project: spring-analysis-note   Source File: ValidatorFactoryTests.java    License: 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 5
Source Project: java-technology-stack   Source File: ValidatorFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testSimpleValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	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 6
Source Project: java-technology-stack   Source File: ValidatorFactoryTests.java    License: 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 7
Source Project: java-technology-stack   Source File: ValidatorFactoryTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testSimpleValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	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 Project: xlsmapper   Source File: EntityDefinitionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setupBefore() {

    // BeanValidatorの式言語の実装を独自のものにする。
    ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
    Validator validator = validatorFactory.usingContext()
            .messageInterpolator(new MessageInterpolatorAdapter(
                    // メッセージリソースの取得方法を切り替える
                    new ResourceBundleMessageResolver(),

                    // EL式の処理を切り替える
                    new MessageInterpolator(new ExpressionLanguageJEXLImpl())))
            .getValidator();

    // BeanValidationのValidatorを渡す
    this.sheetBeanValidator = new SheetBeanValidator(validator);

    this.errorFormatter = new SheetErrorFormatter();

}
 
Example 9
Source Project: ueboot   Source File: ValidatorTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    ReqBody reqBody = new ReqBody();
    Set<ConstraintViolation<Object>> validRetval = validator.validate(reqBody);
    StringBuilder sb = new StringBuilder();
    // 校验失败
    if (!validRetval.isEmpty()) {
        for (ConstraintViolation<Object> t : validRetval) {
            sb.append(t.getPropertyPath()).append(t.getMessage()).append(",");
        }
    }
    String checkError = sb.toString();
    System.out.println(checkError);
}
 
Example 10
Source Project: conductor   Source File: EventHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testWorkflowTaskName() {
    EventHandler taskDef = new EventHandler();//name is null

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Object>> result = validator.validate(taskDef);
    assertEquals(3, result.size());

    List<String> validationErrors = new ArrayList<>();
    result.forEach(e -> validationErrors.add(e.getMessage()));

    assertTrue(validationErrors.contains("Missing event handler name"));
    assertTrue(validationErrors.contains("Missing event location"));
    assertTrue(validationErrors.contains("No actions specified. Please specify at-least one action"));
}
 
Example 11
public static String validate(Object obj) {
	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();
	Set<ConstraintViolation<Object>> violations = validator.validate(obj);

	String error = "";
	if (!violations.isEmpty()) {

		boolean firstIteration = true;
		for (ConstraintViolation<Object> violation : violations) {
			if (firstIteration)
				firstIteration = false;
			else
				error += ", ";

			error += violation.getPropertyPath().toString() + " " + violation.getMessage();
		}

		return error;
	}

	return null;
}
 
Example 12
Source Project: guice-validator   Source File: ValidationModule.java    License: MIT License 6 votes vote down vote up
@Override
protected void configure() {
    final GuiceConstraintValidatorFactory constraintValidatorFactory = new GuiceConstraintValidatorFactory();
    requestInjection(constraintValidatorFactory);

    /* Overriding just constraints factory to allow them use guice injections */
    final Validator validator = factory.usingContext()
            .constraintValidatorFactory(constraintValidatorFactory)
            .getValidator();

    bind(Validator.class).toInstance(validator);
    bind(ExecutableValidator.class).toInstance(validator.forExecutables());
    // NOTE bound factory is not aware of guice! because it use default ConstraintValidatorFactory
    bind(ValidatorFactory.class).toInstance(factory);
    bind(ValidationContext.class);

    bindConstant().annotatedWith(Names.named("guice.validator.addDefaultGroup")).to(addDefaultGroup);
    final ValidationGroupInterceptor groupInterceptor = new ValidationGroupInterceptor();
    requestInjection(groupInterceptor);
    configureGroupsAop(groupInterceptor);

    final ValidationMethodInterceptor interceptor = new ValidationMethodInterceptor();
    requestInjection(interceptor);
    configureAop(interceptor);
}
 
Example 13
Source Project: pay-publicapi   Source File: CardFirstSixDigitsValidatorTest.java    License: MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();

    builder
            .withAmount(1200)
            .withDescription("Some description")
            .withReference("Some reference")
            .withProcessorId("1PROC")
            .withProviderId("1PROV")
            .withCardExpiry("01/99")
            .withCardType("visa")
            .withLastFourDigits("1234")
            .withPaymentOutcome(new PaymentOutcome("success"));
}
 
Example 14
Source Project: pay-publicapi   Source File: CardExpiryValidatorTest.java    License: MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpValidator() {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    validator = factory.getValidator();

    builder
            .withAmount(1200)
            .withDescription("Some description")
            .withReference("Some reference")
            .withProcessorId("1PROC")
            .withProviderId("1PROV")
            .withLastFourDigits("1234")
            .withFirstSixDigits("123456")
            .withCardType("visa")
            .withPaymentOutcome(new PaymentOutcome("success"));
}
 
Example 15
Source Project: seed   Source File: ValidationModule.java    License: Mozilla Public License 2.0 6 votes vote down vote up
@Override
protected void configure() {
    install(new PrivateModule() {
        @Override
        protected void configure() {
            // Validator factory
            bind(ValidatorFactory.class).toProvider(ValidatorFactoryProvider.class).in(Scopes.SINGLETON);
            expose(ValidatorFactory.class);

            // Validator
            bind(Validator.class).toProvider(ValidatorProvider.class).in(Scopes.SINGLETON);
            expose(Validator.class);

            // Detected constraint validators
            constraintValidators.forEach(this::bind);
        }
    });

    // Validation on injection / method call
    enableValidationOnInjectionPoints();
    if (isDynamicValidationSupported()) {
        configureDynamicValidation();
    }
}
 
Example 16
Source Project: crnk-framework   Source File: ValidationEndToEndTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testMapElementAttributeNotNull() {
	ProjectData data = new ProjectData();
	data.setValue(null); // violation

	Project project = new Project();
	project.setId(1L);
	project.setName("test");
	project.setDataMap(new LinkedHashMap());
	project.getDataMap().put("someKey", data);

	ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
	Validator validator = factory.getValidator();

	try {
		projectRepo.create(project);
	} catch (ConstraintViolationException e) {
		Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
		Assert.assertEquals(1, violations.size());
		ConstraintViolationImpl violation = (ConstraintViolationImpl) violations.iterator().next();
		Assert.assertEquals("{javax.validation.constraints.NotNull.message}", violation.getMessageTemplate());
		Assert.assertEquals("dataMap[someKey].value", violation.getPropertyPath().toString());
		Assert.assertNotNull(violation.getMessage());
		Assert.assertEquals("/data/attributes/data-map/someKey/value", violation.getErrorData().getSourcePointer());
	}
}
 
Example 17
@SuppressWarnings("Duplicates")
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    T212Map t212Map = T212Map.createDataLevel(map);

    Set<ConstraintViolation<T212Map>> e0 = validator.validate(t212Map,
            Default.class);
    assertEquals(e0.size(),0);

    t212Map.clear();
    map.put("QN","20180101123010123-");
    Set<ConstraintViolation<T212Map>> e1 = validator.validate(t212Map,
            Default.class);
    assertEquals(e1.size(),1);

}
 
Example 18
Source Project: seed   Source File: ValidationPlugin.java    License: Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void stop() {
    if (isValidationEnabled() && isValidation11Supported()) {
        try {
            injector.getInstance(ValidatorFactory.class).close();
        } catch (Exception e) {
            LOGGER.warn("Unable to close ValidatorFactory", e);
        }
    }
}
 
Example 19
private DefaultValidationContext() {
    Configuration<?> validationConfig = Validation.byDefaultProvider().configure();
    if (new DefaultSejdaContext().isIgnoreXmlConfiguration()) {
        validationConfig.ignoreXmlConfiguration();
    }
    ValidatorFactory factory = validationConfig.buildValidatorFactory();
    validator = factory.getValidator();
}
 
Example 20
Source Project: zuihou-admin-boot   Source File: NoBootTest.java    License: 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 21
Source Project: micronaut-sql   Source File: JpaConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return The JPA properties
 */
public Map<String, Object> getProperties() {
    ValidatorFactory validatorFactory;
    if (applicationContext.containsBean(ValidatorFactory.class)) {
        validatorFactory = applicationContext.getBean(ValidatorFactory.class);
    } else {
        validatorFactory = null;
    }

    if (validatorFactory != null) {
        jpaProperties.put(org.hibernate.cfg.AvailableSettings.JPA_VALIDATION_FACTORY, validatorFactory);
    }
    return jpaProperties;
}
 
Example 22
@BeforeClass
public static void beforeClass() {
    ValidatorFactory validatorFactory = Validation.byDefaultProvider()
      .configure()
      .messageInterpolator(new ParameterMessageInterpolator())
      .buildValidatorFactory();

    validator = validatorFactory.getValidator();
}
 
Example 23
Source Project: tomee   Source File: BuiltInEnvironmentEntries.java    License: Apache License 2.0 5 votes vote down vote up
private void add(final JndiConsumer jndi, final DeploymentModule module, final DeploymentModule app, final boolean defaults) {

        // Standard names
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:module/ModuleName").value(module.getModuleId()).type(String.class));
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:app/AppName").value(app.getModuleId()).type(String.class));

        // Standard References to built-in objects
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/BeanManager").type(BeanManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/Validator").type(Validator.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/ValidatorFactory").type(ValidatorFactory.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionManager").type(TransactionManager.class));
        add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/TransactionSynchronizationRegistry").type(TransactionSynchronizationRegistry.class));

        if (defaults) {
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedExecutorService").type(ManagedExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedScheduledExecutorService").type(ManagedScheduledExecutorService.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultManagedThreadFactory").type(ManagedThreadFactory.class));
            add(jndi.getResourceEnvRefMap(), new ResourceEnvRef().name("java:comp/DefaultContextService").type(ContextService.class));
            try {
                final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
                contextClassLoader.loadClass("org.apache.activemq.ActiveMQSslConnectionFactory");
                final ResourceEnvRef ref = new ResourceEnvRef().name("java:comp/DefaultJMSConnectionFactory")
                    .type(contextClassLoader.loadClass("javax.jms.ConnectionFactory"));
                add(jndi.getResourceEnvRefMap(), ref);
            } catch (final ClassNotFoundException | NoClassDefFoundError notThere) {
                // no-op
            }
        }


        // OpenEJB specific feature
        add(jndi.getEnvEntryMap(), new EnvEntry().name("java:comp/ComponentName").value(jndi.getJndiConsumerName()).type(String.class));

    }
 
Example 24
Source Project: spring-boot-vue-admin   Source File: ValidatorConfig.java    License: 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 25
Source Project: tomee   Source File: SingleValidatorFactoryWrapper.java    License: Apache License 2.0 5 votes vote down vote up
private ValidatorFactory factory() {
    if (factory == null) {
        synchronized (this) {
            if (factory == null) {
                try {
                    factory = ValidatorUtil.lookupFactory();
                } catch (final NamingException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
    return factory;
}
 
Example 26
Source Project: openapi-generator   Source File: OpenAPIUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static <T> void validate(T obj) {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<T>> constraintViolations = validator.validate(obj);
    if (constraintViolations.size() > 0) {
        StringBuilder errors = new StringBuilder();
        for (ConstraintViolation<T> contraintes : constraintViolations) {
            errors.append(String.format("%s.%s %s\n",
            contraintes.getRootBeanClass().getSimpleName(),
            contraintes.getPropertyPath(),
            contraintes.getMessage()));
        }
        throw new RuntimeException("Bean validation : " + errors);
    }
}
 
Example 27
Source Project: tomee   Source File: LazyValidator.java    License: Apache License 2.0 5 votes vote down vote up
private ValidatorFactory findFactory() {
    try {
        return ValidatorUtil.lookupFactory();
    } catch (final NamingException ne) {
        return Validation.buildDefaultValidatorFactory();
    }
}
 
Example 28
private Validator getValidator(){
    if(this.validator!=null){
        return this.validator;
    }
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    this.validator = factory.getValidator();
    return this.validator;
}
 
Example 29
Source Project: zuihou-admin-cloud   Source File: NoBootTest.java    License: 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 30
Source Project: cloud-config   Source File: SimpleResourceConfigFactoryBeanTest.java    License: MIT License 5 votes vote down vote up
private BoneCPDataSourceConfig createBean() throws Exception {
    SimpleResourceConfigFactoryBean<BoneCPDataSourceConfig> factoryBean = new SimpleResourceConfigFactoryBean<>();
    factoryBean.setClient(zkRootClient);
    factoryBean.setPath("/database/bcp");
    factoryBean.setResourceType(BoneCPDataSourceConfig.class);
    factoryBean.setAutoReload(true);

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    factoryBean.setValidator(validator);

    factoryBean.afterPropertiesSet();
    return factoryBean.getObject();
}