org.springframework.validation.beanvalidation.LocalValidatorFactoryBean Java Examples

The following examples show how to use org.springframework.validation.beanvalidation.LocalValidatorFactoryBean. 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 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 #2
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithClassLevel() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
}
 
Example #3
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithAutowiredValidator() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
Example #4
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithErrorInListElement() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.getAddressList().add(new ValidAddress());
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(3, result.getErrorCount());
	FieldError fieldError = result.getFieldError("name");
	assertEquals("name", fieldError.getField());
	fieldError = result.getFieldError("address.street");
	assertEquals("address.street", fieldError.getField());
	fieldError = result.getFieldError("addressList[0].street");
	assertEquals("addressList[0].street", fieldError.getField());
}
 
Example #5
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithErrorInSetElement() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.getAddressSet().add(new ValidAddress());
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(3, result.getErrorCount());
	FieldError fieldError = result.getFieldError("name");
	assertEquals("name", fieldError.getField());
	fieldError = result.getFieldError("address.street");
	assertEquals("address.street", fieldError.getField());
	fieldError = result.getFieldError("addressSet[].street");
	assertEquals("addressSet[].street", fieldError.getField());
}
 
Example #6
Source File: ValidatorFactoryTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testListValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ListContainer listContainer = new ListContainer();
	listContainer.addString("A");
	listContainer.addString("X");

	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(listContainer, "listContainer");
	errors.initConversion(new DefaultConversionService());
	validator.validate(listContainer, errors);

	FieldError fieldError = errors.getFieldError("list[1]");
	assertNotNull(fieldError);
	assertEquals("X", fieldError.getRejectedValue());
	assertEquals("X", errors.getFieldValue("list[1]"));
}
 
Example #7
Source File: DelegatingWebMvcConfigurationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	delegatingConfig.setConfigurers(Collections.singletonList(webMvcConfigurer));
	RequestMappingHandlerAdapter adapter = this.delegatingConfig.requestMappingHandlerAdapter(
			this.delegatingConfig.mvcContentNegotiationManager(), this.delegatingConfig.mvcConversionService(),
			this.delegatingConfig.mvcValidator());

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();

	verify(webMvcConfigurer).configureMessageConverters(converters.capture());
	verify(webMvcConfigurer).configureContentNegotiation(contentNegotiationConfigurer.capture());
	verify(webMvcConfigurer).addFormatters(conversionService.capture());
	verify(webMvcConfigurer).addArgumentResolvers(resolvers.capture());
	verify(webMvcConfigurer).addReturnValueHandlers(handlers.capture());
	verify(webMvcConfigurer).configureAsyncSupport(asyncConfigurer.capture());

	assertNotNull(initializer);
	assertSame(conversionService.getValue(), initializer.getConversionService());
	assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
	assertEquals(0, resolvers.getValue().size());
	assertEquals(0, handlers.getValue().size());
	assertEquals(converters.getValue(), adapter.getMessageConverters());
	assertNotNull(asyncConfigurer);
}
 
Example #8
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringValidationWithAutowiredValidator() throws Exception {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
Example #9
Source File: CustomMessageSourceConfiguration.java    From tutorials with MIT License 6 votes vote down vote up
@Bean
public LocalValidatorFactoryBean getValidator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());
    return bean;
}
 
Example #10
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimpleValidation() throws Exception {
	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.destroy();
}
 
Example #11
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithAutowiredValidator() {
	ConfigurableApplicationContext ctx = new AnnotationConfigApplicationContext(
			LocalValidatorFactoryBean.class);
	LocalValidatorFactoryBean validator = ctx.getBean(LocalValidatorFactoryBean.class);

	ValidPerson person = new ValidPerson();
	person.expectsAutowiredValidator = true;
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
	ctx.close();
}
 
Example #12
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithErrorInListElement() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.getAddressList().add(new ValidAddress());
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(3, result.getErrorCount());
	FieldError fieldError = result.getFieldError("name");
	assertEquals("name", fieldError.getField());
	fieldError = result.getFieldError("address.street");
	assertEquals("address.street", fieldError.getField());
	fieldError = result.getFieldError("addressList[0].street");
	assertEquals("addressList[0].street", fieldError.getField());
}
 
Example #13
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testSpringValidationWithErrorInSetElement() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.getAddressSet().add(new ValidAddress());
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(3, result.getErrorCount());
	FieldError fieldError = result.getFieldError("name");
	assertEquals("name", fieldError.getField());
	fieldError = result.getFieldError("address.street");
	assertEquals("address.street", fieldError.getField());
	fieldError = result.getFieldError("addressSet[].street");
	assertEquals("addressSet[].street", fieldError.getField());
}
 
Example #14
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringValidationWithClassLevel() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, result);
	assertEquals(1, result.getErrorCount());
	ObjectError globalError = result.getGlobalError();
	List<String> errorCodes = Arrays.asList(globalError.getCodes());
	assertEquals(2, errorCodes.size());
	assertTrue(errorCodes.contains("NameAddressValid.person"));
	assertTrue(errorCodes.contains("NameAddressValid"));
}
 
Example #15
Source File: ServletConfiguration.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Validator getValidator() {
    // need to get constraint violation message codes translated
    LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(ms);
    return factory;
}
 
Example #16
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public void initBinder(WebDataBinder binder) {
	LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean();
	vf.afterPropertiesSet();
	binder.setValidator(vf);
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	dateFormat.setLenient(false);
	binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
 
Example #17
Source File: WebMvcConfigurationSupportTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(12, converters.size());
	converters.stream()
			.filter(converter -> converter instanceof AbstractJackson2HttpMessageConverter)
			.forEach(converter -> {
				ObjectMapper mapper = ((AbstractJackson2HttpMessageConverter) converter).getObjectMapper();
				assertFalse(mapper.getDeserializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getSerializationConfig().isEnabled(DEFAULT_VIEW_INCLUSION));
				assertFalse(mapper.getDeserializationConfig().isEnabled(FAIL_ON_UNKNOWN_PROPERTIES));
				if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
					assertEquals(XmlMapper.class, mapper.getClass());
				}
			});

	ConfigurableWebBindingInitializer initializer =
			(ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer();
	assertNotNull(initializer);

	ConversionService conversionService = initializer.getConversionService();
	assertNotNull(conversionService);
	assertTrue(conversionService instanceof FormattingConversionService);

	Validator validator = initializer.getValidator();
	assertNotNull(validator);
	assertTrue(validator instanceof LocalValidatorFactoryBean);

	DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter);
	@SuppressWarnings("unchecked")
	List<Object> bodyAdvice = (List<Object>) fieldAccessor.getPropertyValue("requestResponseBodyAdvice");
	assertEquals(2, bodyAdvice.size());
	assertEquals(JsonViewRequestBodyAdvice.class, bodyAdvice.get(0).getClass());
	assertEquals(JsonViewResponseBodyAdvice.class, bodyAdvice.get(1).getClass());
}
 
Example #18
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testSimpleValidationWithClassLevel() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Juergen");
	person.getAddress().setStreet("Juergen's Street");
	Set<ConstraintViolation<ValidPerson>> result = validator.validate(person);
	assertEquals(1, result.size());
	Iterator<ConstraintViolation<ValidPerson>> iterator = result.iterator();
	ConstraintViolation<?> cv = iterator.next();
	assertEquals("", cv.getPropertyPath().toString());
	assertTrue(cv.getConstraintDescriptor().getAnnotation() instanceof NameAddressValid);
}
 
Example #19
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@InitBinder
public void initBinder(WebDataBinder binder) {
	binder.initDirectFieldAccess();
	binder.setConversionService(new DefaultFormattingConversionService());
	LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean();
	vf.afterPropertiesSet();
	binder.setValidator(vf);
}
 
Example #20
Source File: ServletAnnotationControllerHandlerMethodTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@InitBinder({"myCommand", "date"})
public void initBinder(WebDataBinder binder, String date, @RequestParam("date") String[] date2) {
	LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean();
	vf.afterPropertiesSet();
	binder.setValidator(vf);
	assertEquals("2007-10-02", date);
	assertEquals(1, date2.length);
	assertEquals("2007-10-02", date2[0]);
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	dateFormat.setLenient(false);
	binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
 
Example #21
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testSpringValidationFieldType() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Phil");
	person.getAddress().setStreet("Phil's Street");
	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, errors);
	assertEquals(1, errors.getErrorCount());
	assertThat("Field/Value type mismatch", errors.getFieldError("address").getRejectedValue(),
			instanceOf(ValidAddress.class));
}
 
Example #22
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testInnerBeanValidation() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	MainBean mainBean = new MainBean();
	Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean");
	validator.validate(mainBean, errors);
	Object rejected = errors.getFieldValue("inner.value");
	assertNull(rejected);
}
 
Example #23
Source File: ValidatorFactoryTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testValidationWithOptionalField() {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	MainBeanWithOptional mainBean = new MainBeanWithOptional();
	Errors errors = new BeanPropertyBindingResult(mainBean, "mainBean");
	validator.validate(mainBean, errors);
	Object rejected = errors.getFieldValue("inner.value");
	assertNull(rejected);
}
 
Example #24
Source File: ApplicationConfig.java    From ddd-java with MIT License 5 votes vote down vote up
/** BeanValidationメッセージのUTF-8に対応したValidator。 */
@Bean
public LocalValidatorFactoryBean defaultValidator(MessageSource message) {
    LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(message);
    return factory;
}
 
Example #25
Source File: SpringDataDynamoDemoConfig.java    From spring-data-dynamodb-demo with Apache License 2.0 5 votes vote down vote up
/** The following validation-related beans are optional - only
 * required if JSR 303 validation is desired.  For validation to 
 * work, the @EnableDynamoDBRepositories must be configured with
 * a reference to DynamoDBOperations bean, rather than with
 * reference to AmazonDynamoDB client
 * */

@Bean 
public LocalValidatorFactoryBean validator()
{
	return new LocalValidatorFactoryBean();
}
 
Example #26
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 #27
Source File: RequestResponseBodyMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public WebDataBinder createBinder(NativeWebRequest request, @Nullable Object target, String objectName) {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();
	WebDataBinder dataBinder = new WebDataBinder(target, objectName);
	dataBinder.setValidator(validator);
	return dataBinder;
}
 
Example #28
Source File: HttpEntityMethodProcessorTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public WebDataBinder createBinder(NativeWebRequest webRequest, @Nullable Object target, String objectName) {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();
	WebDataBinder dataBinder = new WebDataBinder(target, objectName);
	dataBinder.setValidator(validator);
	return dataBinder;
}
 
Example #29
Source File: RequestResponseBodyMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();
	WebDataBinder dataBinder = new WebDataBinder(target, objectName);
	dataBinder.setValidator(validator);
	return dataBinder;
}
 
Example #30
Source File: ValidatorFactoryTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpringValidationFieldType() throws Exception {
	LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
	validator.afterPropertiesSet();

	ValidPerson person = new ValidPerson();
	person.setName("Phil");
	person.getAddress().setStreet("Phil's Street");
	BeanPropertyBindingResult errors = new BeanPropertyBindingResult(person, "person");
	validator.validate(person, errors);
	assertEquals(1, errors.getErrorCount());
	assertThat("Field/Value type mismatch", errors.getFieldError("address").getRejectedValue(),
			instanceOf(ValidAddress.class));
}