Java Code Examples for org.springframework.validation.Validator

The following examples show how to use org.springframework.validation.Validator. 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
@Test
public void customValidation() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	instance.setValidator(new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if ("failure".equals(value)) {
				errors.reject("not a valid value");
			}
		}
	});
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "payloadValidation", String.class);
	assertThatExceptionOfType(MethodArgumentNotValidException.class).isThrownBy(() ->
			invocableHandlerMethod.invoke(MessageBuilder.withPayload("failure").build()));
}
 
Example 2
@Test
public void customValidation() throws Exception {
	DefaultMessageHandlerMethodFactory instance = createInstance();
	instance.setValidator(new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if ("failure".equals(value)) {
				errors.reject("not a valid value");
			}
		}
	});
	instance.afterPropertiesSet();

	InvocableHandlerMethod invocableHandlerMethod =
			createInvocableHandlerMethod(instance, "payloadValidation", String.class);
	thrown.expect(MethodArgumentNotValidException.class);
	invocableHandlerMethod.invoke(MessageBuilder.withPayload("failure").build());
}
 
Example 3
@Test
public void requestMappingHandlerAdapter() throws Exception {
	delegatingConfig.setConfigurers(Collections.singletonList(webFluxConfigurer));
	ReactiveAdapterRegistry reactiveAdapterRegistry = delegatingConfig.webFluxAdapterRegistry();
	ServerCodecConfigurer serverCodecConfigurer = delegatingConfig.serverCodecConfigurer();
	FormattingConversionService formattingConversionService = delegatingConfig.webFluxConversionService();
	Validator validator = delegatingConfig.webFluxValidator();

	ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer)
			this.delegatingConfig.requestMappingHandlerAdapter(reactiveAdapterRegistry, serverCodecConfigurer,
					formattingConversionService, validator).getWebBindingInitializer();

	verify(webFluxConfigurer).configureHttpMessageCodecs(codecsConfigurer.capture());
	verify(webFluxConfigurer).getValidator();
	verify(webFluxConfigurer).getMessageCodesResolver();
	verify(webFluxConfigurer).addFormatters(formatterRegistry.capture());
	verify(webFluxConfigurer).configureArgumentResolvers(any());

	assertNotNull(initializer);
	assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean);
	assertSame(formatterRegistry.getValue(), initializer.getConversionService());
	assertEquals(13, codecsConfigurer.getValue().getReaders().size());
}
 
Example 4
@Override
public Validator getValidator() {
    // need to get constraint violation message codes translated
    LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean();
    factory.setValidationMessageSource(ms);
    return factory;
}
 
Example 5
Source Project: spring-cloud-gateway   Source File: ConfigurationService.java    License: Apache License 2.0 5 votes vote down vote up
public ConfigurationService(BeanFactory beanFactory,
		Supplier<ConversionService> conversionService,
		Supplier<Validator> validator) {
	this.beanFactory = beanFactory;
	this.conversionService = conversionService;
	this.validator = validator;
}
 
Example 6
@Test
public void simpValidatorInjected() {
	SimpAnnotationMethodMessageHandler messageHandler =
			this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class);

	assertThat(messageHandler.getValidator(), Matchers.notNullValue(Validator.class));
}
 
Example 7
public Validator getValidator() {
	if (this.validator == null) {
		GrailsDomainClassValidator gdcv = new GrailsDomainClassValidator();
		gdcv.setDomainClass(this);
		MessageSource messageSource = this.application.getMainContext().getBean(MessageSource.class);
		gdcv.setMessageSource(messageSource);
		this.validator = gdcv;
	}
	return this.validator;
}
 
Example 8
private Validator testValidator() {
	return new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if ("invalidValue".equals(value)) {
				errors.reject("invalid value");
			}
		}
	};
}
 
Example 9
@Test
public void simpValidatorCustom() {
	final Validator validator = mock(Validator.class);
	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {
		@Override
		public Validator getValidator() {
			return validator;
		}
	};

	assertSame(validator, config.simpValidator());
}
 
Example 10
Source Project: maven-framework-project   Source File: ProductValidator.java    License: MIT License 5 votes vote down vote up
public void validate(Object target, Errors errors) {
	Set<ConstraintViolation<Object>> constraintViolations = beanValidator.validate(target);
	
	for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
		String propertyPath = constraintViolation.getPropertyPath().toString();
		String message = constraintViolation.getMessage();
		errors.rejectValue(propertyPath, "", message);
	}
	
	for(Validator validator: springValidators) {
		validator.validate(target, errors);
	}
}
 
Example 11
Source Project: spring-analysis-note   Source File: WebFluxConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Return the {@link ConfigurableWebBindingInitializer} to use for
 * initializing all {@link WebDataBinder} instances.
 */
protected ConfigurableWebBindingInitializer getConfigurableWebBindingInitializer(
		FormattingConversionService webFluxConversionService,
		Validator webFluxValidator) {
	ConfigurableWebBindingInitializer initializer = new ConfigurableWebBindingInitializer();
	initializer.setConversionService(webFluxConversionService);
	initializer.setValidator(webFluxValidator);
	MessageCodesResolver messageCodesResolver = getMessageCodesResolver();
	if (messageCodesResolver != null) {
		initializer.setMessageCodesResolver(messageCodesResolver);
	}
	return initializer;
}
 
Example 12
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = loadConfig(WebFluxConfig.class);

	String name = "requestMappingHandlerAdapter";
	RequestMappingHandlerAdapter adapter = context.getBean(name, RequestMappingHandlerAdapter.class);
	assertNotNull(adapter);

	List<HttpMessageReader<?>> readers = adapter.getMessageReaders();
	assertEquals(13, readers.size());

	ResolvableType multiValueMapType = forClassWithGenerics(MultiValueMap.class, String.class, String.class);

	assertHasMessageReader(readers, forClass(byte[].class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(ByteBuffer.class), APPLICATION_OCTET_STREAM);
	assertHasMessageReader(readers, forClass(String.class), TEXT_PLAIN);
	assertHasMessageReader(readers, forClass(Resource.class), IMAGE_PNG);
	assertHasMessageReader(readers, forClass(Message.class), new MediaType("application", "x-protobuf"));
	assertHasMessageReader(readers, multiValueMapType, APPLICATION_FORM_URLENCODED);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_XML);
	assertHasMessageReader(readers, forClass(TestBean.class), APPLICATION_JSON);
	assertHasMessageReader(readers, forClass(TestBean.class), new MediaType("application", "x-jackson-smile"));
	assertHasMessageReader(readers, forClass(TestBean.class), null);

	WebBindingInitializer bindingInitializer = adapter.getWebBindingInitializer();
	assertNotNull(bindingInitializer);
	WebExchangeDataBinder binder = new WebExchangeDataBinder(new Object());
	bindingInitializer.initBinder(binder);

	name = "webFluxConversionService";
	ConversionService service = context.getBean(name, ConversionService.class);
	assertSame(service, binder.getConversionService());

	name = "webFluxValidator";
	Validator validator = context.getBean(name, Validator.class);
	assertSame(validator, binder.getValidator());
}
 
Example 13
Source Project: spring-analysis-note   Source File: ModelInitializerTests.java    License: MIT License 5 votes vote down vote up
@Test
public void initBinderMethod() {
	Validator validator = mock(Validator.class);

	TestController controller = new TestController();
	controller.setValidator(validator);
	InitBinderBindingContext context = getBindingContext(controller);

	Method method = ResolvableMethod.on(TestController.class).annotPresent(GetMapping.class).resolveMethod();
	HandlerMethod handlerMethod = new HandlerMethod(controller, method);
	this.modelInitializer.initModel(handlerMethod, context, this.exchange).block(Duration.ofMillis(5000));

	WebExchangeDataBinder binder = context.createDataBinder(this.exchange, "name");
	assertEquals(Collections.singletonList(validator), binder.getValidators());
}
 
Example 14
Source Project: spring-analysis-note   Source File: ControllerAdviceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void initBinderAdvice() throws Exception {
	ApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
	RequestMappingHandlerAdapter adapter = createAdapter(context);
	TestController controller = context.getBean(TestController.class);

	Validator validator = mock(Validator.class);
	controller.setValidator(validator);

	BindingContext bindingContext = handle(adapter, controller, "handle").getBindingContext();

	WebExchangeDataBinder binder = bindingContext.createDataBinder(this.exchange, "name");
	assertEquals(Collections.singletonList(validator), binder.getValidators());
}
 
Example 15
Source Project: spring-analysis-note   Source File: WebMvcConfigurationSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a {@link RequestMappingHandlerAdapter} for processing requests
 * through annotated controller methods. Consider overriding one of these
 * other more fine-grained methods:
 * <ul>
 * <li>{@link #addArgumentResolvers} for adding custom argument resolvers.
 * <li>{@link #addReturnValueHandlers} for adding custom return value handlers.
 * <li>{@link #configureMessageConverters} for adding custom message converters.
 * </ul>
 */
@Bean
public RequestMappingHandlerAdapter requestMappingHandlerAdapter(
		ContentNegotiationManager mvcContentNegotiationManager,
		FormattingConversionService mvcConversionService,
		Validator mvcValidator) {
	RequestMappingHandlerAdapter adapter = createRequestMappingHandlerAdapter();
	adapter.setContentNegotiationManager(mvcContentNegotiationManager);
	adapter.setMessageConverters(getMessageConverters());
	adapter.setWebBindingInitializer(getConfigurableWebBindingInitializer(mvcConversionService, mvcValidator));
	adapter.setCustomArgumentResolvers(getArgumentResolvers());
	adapter.setCustomReturnValueHandlers(getReturnValueHandlers());

	if (jackson2Present) {
		adapter.setRequestBodyAdvice(Collections.singletonList(new JsonViewRequestBodyAdvice()));
		adapter.setResponseBodyAdvice(Collections.singletonList(new JsonViewResponseBodyAdvice()));
	}

	AsyncSupportConfigurer configurer = new AsyncSupportConfigurer();
	configureAsyncSupport(configurer);
	if (configurer.getTaskExecutor() != null) {
		adapter.setTaskExecutor(configurer.getTaskExecutor());
	}
	if (configurer.getTimeout() != null) {
		adapter.setAsyncRequestTimeout(configurer.getTimeout());
	}
	adapter.setCallableInterceptors(configurer.getCallableInterceptors());
	adapter.setDeferredResultInterceptors(configurer.getDeferredResultInterceptors());

	return adapter;
}
 
Example 16
@Override
public Validator getValidator() {
	return new Validator() {
		@Override
		public void validate(@Nullable Object target, Errors errors) {
			errors.reject("invalid");
		}

		@Override
		public boolean supports(Class<?> clazz) {
			return true;
		}
	};
}
 
Example 17
@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
@Test
public void customChannels() {
	loadBeanDefinitions("websocket-config-broker-customchannels.xml");

	SimpAnnotationMethodMessageHandler annotationMethodMessageHandler =
			this.appContext.getBean(SimpAnnotationMethodMessageHandler.class);

	Validator validator = annotationMethodMessageHandler.getValidator();
	assertNotNull(validator);
	assertSame(this.appContext.getBean("myValidator"), validator);
	assertThat(validator, Matchers.instanceOf(TestValidator.class));

	List<Class<? extends MessageHandler>> subscriberTypes = Arrays.asList(SimpAnnotationMethodMessageHandler.class,
			UserDestinationMessageHandler.class, SimpleBrokerMessageHandler.class);

	testChannel("clientInboundChannel", subscriberTypes, 3);
	testExecutor("clientInboundChannel", 100, 200, 600);

	subscriberTypes = Collections.singletonList(SubProtocolWebSocketHandler.class);

	testChannel("clientOutboundChannel", subscriberTypes, 3);
	testExecutor("clientOutboundChannel", 101, 201, 601);

	subscriberTypes = Arrays.asList(SimpleBrokerMessageHandler.class, UserDestinationMessageHandler.class);

	testChannel("brokerChannel", subscriberTypes, 1);
	testExecutor("brokerChannel", 102, 202, 602);
}
 
Example 19
/**
 * Register custom serialization and deserialization modules.
 * 
 * @param conversionService
 * @param validator
 */
@Autowired
public ConversionServiceObjectMapper(
        final ConversionService conversionService, final Validator validator) {

    // Register a module to add provider for custom bean deserializer
    registerModule(new ConversionServiceModule(conversionService));

    // Register a module to add provider for custom bean serializer
    registerModule(new DataBinderModule());
}
 
Example 20
Source Project: maven-framework-project   Source File: ProductValidator.java    License: MIT License 5 votes vote down vote up
public void validate(Object target, Errors errors) {
	Set<ConstraintViolation<Object>> constraintViolations = beanValidator.validate(target);
	
	for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
		String propertyPath = constraintViolation.getPropertyPath().toString();
		String message = constraintViolation.getMessage();
		errors.rejectValue(propertyPath, "", message);
	}
	
	for(Validator validator: springValidators) {
		validator.validate(target, errors);
	}
}
 
Example 21
@Test
public void requestMappingHandlerAdapter() throws Exception {
	ApplicationContext context = initContext(WebConfig.class);
	RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
	List<HttpMessageConverter<?>> converters = adapter.getMessageConverters();
	assertEquals(9, converters.size());
	for(HttpMessageConverter<?> converter : converters) {
		if (converter instanceof AbstractJackson2HttpMessageConverter) {
			ObjectMapper objectMapper = ((AbstractJackson2HttpMessageConverter)converter).getObjectMapper();
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
			assertFalse(objectMapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
			if (converter instanceof MappingJackson2XmlHttpMessageConverter) {
				assertEquals(XmlMapper.class, objectMapper.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 22
Source Project: maven-framework-project   Source File: ProductValidator.java    License: MIT License 5 votes vote down vote up
public void validate(Object target, Errors errors) {
	Set<ConstraintViolation<Object>> constraintViolations = beanValidator.validate(target);
	
	for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
		String propertyPath = constraintViolation.getPropertyPath().toString();
		String message = constraintViolation.getMessage();
		errors.rejectValue(propertyPath, "", message);
	}
	
	for(Validator validator: springValidators) {
		validator.validate(target, errors);
	}
}
 
Example 23
public void bind(Bindable<?> target) {
    ConfigurationProperties annotation = target
            .getAnnotation(ConfigurationProperties.class);
    Assert.state(annotation != null,
            "Missing @ConfigurationProperties on " + target);
    List<Validator> validators = getValidators(target);
    BindHandler bindHandler = getBindHandler(annotation, validators);
    getBinder().bind(annotation.prefix(), target, bindHandler);
}
 
Example 24
@Override
@SuppressWarnings("unchecked")
public void setApplicationContext(ApplicationContext context) throws BeansException {
    if (initialized.compareAndSet(false, true)) {
        this.redisTemplate = context.getBean("stringReactiveRedisTemplate", ReactiveRedisTemplate.class);
        this.script = context.getBean(REDIS_SCRIPT_NAME, RedisScript.class);
        if (context.getBeanNamesForType(Validator.class).length > 0) {
            this.setValidator(context.getBean(Validator.class));
        }
    }
}
 
Example 25
@Test
public void simpValidatorCustom() {
	final Validator validator = mock(Validator.class);
	AbstractMessageBrokerConfiguration config = new BaseTestMessageBrokerConfig() {
		@Override
		public Validator getValidator() {
			return validator;
		}
	};

	assertSame(validator, config.simpValidator());
}
 
Example 26
@Test
public void simpValidatorInjected() {
	ApplicationContext context = loadConfig(SimpleBrokerConfig.class);

	SimpAnnotationMethodMessageHandler messageHandler =
			context.getBean(SimpAnnotationMethodMessageHandler.class);

	assertThat(messageHandler.getValidator(), Matchers.notNullValue(Validator.class));
}
 
Example 27
private Validator testValidator() {
	return new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(Object target, Errors errors) {
			String value = (String) target;
			if ("invalidValue".equals(value)) {
				errors.reject("invalid value");
			}
		}
	};
}
 
Example 28
Source Project: tutorials   Source File: ValidatorEventRegister.java    License: MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws Exception {
    List<String> events = Arrays.asList("beforeCreate", "afterCreate", "beforeSave", "afterSave", "beforeLinkSave", "afterLinkSave", "beforeDelete", "afterDelete");

    for (Map.Entry<String, Validator> entry : validators.entrySet()) {
        events.stream().filter(p -> entry.getKey().startsWith(p)).findFirst().ifPresent(p -> validatingRepositoryEventListener.addValidator(p, entry.getValue()));
    }
}
 
Example 29
private Validator testValidator(final String invalidValue) {
	return new Validator() {
		@Override
		public boolean supports(Class<?> clazz) {
			return String.class.isAssignableFrom(clazz);
		}
		@Override
		public void validate(@Nullable Object target, Errors errors) {
			String value = (String) target;
			if (invalidValue.equals(value)) {
				errors.reject("not a valid value");
			}
		}
	};
}
 
Example 30
Source Project: spring-cloud-gray   Source File: ValidationBindHandler.java    License: Apache License 2.0 4 votes vote down vote up
public ValidationBindHandler(Validator... validators) {
    this.validators = validators;
}