org.springframework.validation.Validator Java Examples
The following examples show how to use
org.springframework.validation.Validator.
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: DelegatingWebFluxConfigurationTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #2
Source File: DefaultMessageHandlerMethodFactoryTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@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
Source File: DefaultMessageHandlerMethodFactoryTests.java From spring-analysis-note with MIT License | 6 votes |
@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 #4
Source File: ConfigurationPropertiesBinder.java From spring-cloud-gray with Apache License 2.0 | 5 votes |
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 #5
Source File: ProductValidator.java From maven-framework-project with MIT License | 5 votes |
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 #6
Source File: MessageBrokerConfigurationTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #7
Source File: PayloadArgumentResolverTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
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 #8
Source File: ConfigurationService.java From spring-cloud-gateway with Apache License 2.0 | 5 votes |
public ConfigurationService(BeanFactory beanFactory, Supplier<ConversionService> conversionService, Supplier<Validator> validator) { this.beanFactory = beanFactory; this.conversionService = conversionService; this.validator = validator; }
Example #9
Source File: MethodJmsListenerEndpointTests.java From java-technology-stack with MIT License | 5 votes |
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 #10
Source File: MessageBrokerConfigurationTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void simpValidatorInjected() { SimpAnnotationMethodMessageHandler messageHandler = this.simpleBrokerContext.getBean(SimpAnnotationMethodMessageHandler.class); assertThat(messageHandler.getValidator(), Matchers.notNullValue(Validator.class)); }
Example #11
Source File: GrailsHibernateDomainClass.java From AlgoTrader with GNU General Public License v2.0 | 5 votes |
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 #12
Source File: ValidatorEventRegister.java From tutorials with MIT License | 5 votes |
@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 #13
Source File: WebFluxConfigurationSupport.java From spring-analysis-note with MIT License | 5 votes |
/** * 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 #14
Source File: WebFluxConfigurationSupportTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #15
Source File: ModelInitializerTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #16
Source File: PayloadArgumentResolverTests.java From java-technology-stack with MIT License | 5 votes |
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 #17
Source File: ControllerAdviceTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #18
Source File: MessageBrokerConfigurationTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void simpValidatorInjected() { ApplicationContext context = loadConfig(SimpleBrokerConfig.class); SimpAnnotationMethodMessageHandler messageHandler = context.getBean(SimpAnnotationMethodMessageHandler.class); assertThat(messageHandler.getValidator(), Matchers.notNullValue(Validator.class)); }
Example #19
Source File: MessageBrokerConfigurationTests.java From java-technology-stack with MIT License | 5 votes |
@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 #20
Source File: WebMvcConfigurationSupport.java From spring-analysis-note with MIT License | 5 votes |
/** * 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 #21
Source File: WebMvcConfigurationSupportExtensionTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #22
Source File: WebMvcConfigurationSupportTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #23
Source File: MessageBrokerBeanDefinitionParserTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #24
Source File: ConversionServiceObjectMapper.java From gvnix with GNU General Public License v3.0 | 5 votes |
/** * 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 #25
Source File: ProductValidator.java From maven-framework-project with MIT License | 5 votes |
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 #26
Source File: RateCheckRedisRateLimiter.java From momo-cloud-permission with Apache License 2.0 | 5 votes |
@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 #27
Source File: WebMvcConfigurationSupportTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@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 #28
Source File: ProductValidator.java From maven-framework-project with MIT License | 5 votes |
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 #29
Source File: ServletConfiguration.java From airsonic-advanced with GNU General Public License v3.0 | 5 votes |
@Override public Validator getValidator() { // need to get constraint violation message codes translated LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean(); factory.setValidationMessageSource(ms); return factory; }
Example #30
Source File: WebMvcConfigurationSupport.java From java-technology-stack with MIT License | 4 votes |
/** * Override this method to provide a custom {@link Validator}. */ @Nullable protected Validator getValidator() { return null; }