javax.validation.ValidatorFactory Java Examples

The following examples show how to use javax.validation.ValidatorFactory. 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: T212MapValidDateValidatorTest.java    From hj-t212-parser with Apache License 2.0 6 votes vote down vote up
@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 #2
Source File: ValidatorFactoryTests.java    From java-technology-stack with 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 #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: ValidatorFactoryTests.java    From java-technology-stack with 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 #5
Source File: ValidationModule.java    From seed with 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 #6
Source File: CardExpiryValidatorTest.java    From pay-publicapi with 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 #7
Source File: CardFirstSixDigitsValidatorTest.java    From pay-publicapi with 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 #8
Source File: ValidationModule.java    From guice-validator with 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 #9
Source File: ObjectValidator.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #10
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 #11
Source File: BeanValidationProducer.java    From ozark with 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 #12
Source File: EventHandlerTest.java    From conductor with 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 #13
Source File: ValidatorTest.java    From ueboot with 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 #14
Source File: TypeSafeActivator.java    From lams with 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 #15
Source File: TypeSafeActivator.java    From lams with 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 #16
Source File: ValidatorUtil.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static ValidatorFactory validatorFactory() {
    try {
        return lookupFactory();
    } catch (final NamingException e) {
        return tryJndiLaterFactory();
    }
}
 
Example #17
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 #18
Source File: TypeSafeActivator.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static ValidatorFactory getValidatorFactory(ActivationContext activationContext) {
	// IMPL NOTE : We can either be provided a ValidatorFactory or make one.  We can be provided
	// a ValidatorFactory in 2 different ways.  So here we "get" a ValidatorFactory in the following order:
	//		1) Look into SessionFactoryOptions.getValidatorFactoryReference()
	//		2) Look into ConfigurationService
	//		3) build a new ValidatorFactory

	// 1 - look in SessionFactoryOptions.getValidatorFactoryReference()
	ValidatorFactory factory = resolveProvidedFactory( activationContext.getSessionFactory().getSessionFactoryOptions() );
	if ( factory != null ) {
		return factory;
	}

	// 2 - look in ConfigurationService
	factory = resolveProvidedFactory( activationContext.getServiceRegistry().getService( ConfigurationService.class ) );
	if ( factory != null ) {
		return factory;
	}

	// 3 - build our own
	try {
		return Validation.buildDefaultValidatorFactory();
	}
	catch ( Exception e ) {
		throw new IntegrationException( "Unable to build the default ValidatorFactory", e );
	}
}
 
Example #19
Source File: ResponseFactory.java    From dpCms with Apache License 2.0 5 votes vote down vote up
private static void initValidator() {
	if (validator == null) {
		WebApplicationContext wac = ContextLoader
				.getCurrentWebApplicationContext();
		ValidatorFactory validatorFactory = (ValidatorFactory) wac
				.getBean("validator");
		validator = validatorFactory.getValidator();
	}
}
 
Example #20
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 #21
Source File: ValidationInterceptor.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
public ValidationInterceptor() {
    super(Phase.PRE_INVOKE);
    ValidatorFactory defaultFactory = Validation.buildDefaultValidatorFactory();
    validator = defaultFactory.getValidator();
    if (validator == null) {
        log.warn("Bean Validation provider could not be found, no validation will be performed");
    } else {
        log.debug("Validation In-Interceptor initialized successfully");
    }
}
 
Example #22
Source File: BeanValidator.java    From Guice-configuration with Apache License 2.0 5 votes vote down vote up
public BeanValidator() {
    ValidatorFactory f = null;
    try {
        f = Validation.buildDefaultValidatorFactory();
        log.debug("Validation factory builder found");
    } catch (ValidationException e) {
        log.debug("No validation factory found in classpath");
    } finally {
        factory = f;
    }
}
 
Example #23
Source File: T212MapVerifyTest.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@Test
public void testCPDataLevelFalse(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Map data = cpDataLevel.entrySet()
            .stream()
            .filter(kv -> !kv.getKey().equals("CP"))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    kv -> kv.getValue() + "---------------"
            ));
    Map<String,String> cp1 = (Map) cpDataLevel.get("CP");
    Map cp = cp1.entrySet()
            .stream()
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    kv -> kv.getValue() + "---------------"
            ));
    data.put("CP",cp);

    T212Map t212Map = T212Map.createCpDataLevel(data);

    Set<ConstraintViolation<T212Map>> e2005 = validator.validate(t212Map,Default.class,
            VersionGroup.V2005.class);
    assertTrue(e2005.size() > 0);
    Set<ConstraintViolation<T212Map>> e2017 = validator.validate(t212Map,Default.class,
            VersionGroup.V2017.class);
    assertTrue(e2017.size() > 0);
}
 
Example #24
Source File: T212MapNValidatorTest.java    From hj-t212-parser with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("Duplicates")
@Test
public void test(){
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    T212Map t212Map = T212Map.createDataLevel(map);

    Set<ConstraintViolation<T212Map>> e1 = validator.validate(t212Map,
            Default.class, ModeGroup.UseSubPacket.class);
    assertEquals(e1.size(),1);
}
 
Example #25
Source File: JValidator.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
public JValidator(URL url) {
    this.clazz = ReflectUtils.forName(url.getServiceInterface());
    String jvalidation = url.getParameter("jvalidation");
    ValidatorFactory factory;
    if (jvalidation != null && jvalidation.length() > 0) {
        factory = Validation.byProvider((Class)ReflectUtils.forName(jvalidation)).configure().buildValidatorFactory();
    } else {
        factory = Validation.buildDefaultValidatorFactory();
    }
    this.validator = factory.getValidator();
}
 
Example #26
Source File: WorkflowDefConstraintTest.java    From conductor with Apache License 2.0 5 votes vote down vote up
@Test
public void testWorkflowTaskName() {
    TaskDef taskDef = new TaskDef();//name is null
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    Set<ConstraintViolation<Object>> result = validator.validate(taskDef);
    assertEquals(2, result.size());
}
 
Example #27
Source File: Log4jFastJsonHttpMessageConverter.java    From ueboot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private Validator getValidator(){
    if(this.validator!=null){
        return this.validator;
    }
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    this.validator = factory.getValidator();
    return this.validator;
}
 
Example #28
Source File: BeanValidation.java    From open-Autoscaler with Apache License 2.0 5 votes vote down vote up
public static JsonNode parsePolicy(String jsonString, Map<String, String> service_info, HttpServletRequest httpServletRequest) throws JsonParseException, JsonMappingException, IOException{
	 List<String> violation_message = new ArrayList<String>();
	 ObjectNode result = new_mapper.createObjectNode();
	 result.put("valid", false);
	 logger.info("received policy : " + jsonString); //debug
	 new_mapper.readValue(jsonString, Policy.class); //for syntax error check
	 String transfered_json = TransferedPolicy.packServiceInfo(jsonString, service_info);
	 logger.info("transfered policy after update with service_information : " + transfered_json); //debug
	 TransferedPolicy policy = new_mapper.readValue(transfered_json, TransferedPolicy.class);
	 logger.info("we get policy as " + (Obj2Map(policy)).toString());//debug
	 //additional data manipulation and check again
	 policy = policy.setMaxInstCount();
	 HibernateValidatorConfiguration config = BeanValidation.getPolicyRange();
	 ValidatorFactory vf = config.buildValidatorFactory();
	 Locale locale = LocaleUtil.getLocale(httpServletRequest);
	 MessageInterpolator interpolator = new LocaleSpecificMessageInterpolator(vf.getMessageInterpolator(), locale);
	 Validator validator = vf.usingContext().messageInterpolator(interpolator).getValidator();
	 Set<ConstraintViolation<TransferedPolicy>> set = validator.validate(policy);
	 if (set.size() > 0 ){
		 for (ConstraintViolation<TransferedPolicy> constraintViolation : set) {
			 violation_message.add(constraintViolation.getMessage());
		 }
		 result.set("violation_message", new_mapper.valueToTree(violation_message));
		 return result;
	 }

	 String new_json = policy.transformInput();
	 logger.info("policy before trigger back : " + new_json); //debug
	 new_json = TransferedPolicy.unpackServiceInfo(new_json, service_info);
	 result.put("valid", true);
	 logger.info("send out policy: " + new_json); //debug
	 result.put("new_json", new_json);
	 return result;
}
 
Example #29
Source File: SingleValidatorFactoryWrapper.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void close() {
    final ValidatorFactory factory = this.factory;
    if (factory != null) {
        factory.close();
    }
}
 
Example #30
Source File: SimpleResourceConfigFactoryBeanTest.java    From cloud-config with 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();
}