@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory( DataSource dataSource, MultiTenantConnectionProvider multiTenantConnectionProviderImpl, CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl, LocalValidatorFactoryBean localValidatorFactoryBean) { Map<String, Object> properties = new HashMap<>(); properties.putAll(jpaProperties.getHibernateProperties(dataSource)); properties.put(MULTI_TENANT, MultiTenancyStrategy.SCHEMA); properties.put(MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl); properties.put(MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl); properties.put(JPA_VALIDATION_FACTORY, localValidatorFactoryBean); LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan(JPA_PACKAGES); em.setJpaVendorAdapter(jpaVendorAdapter()); em.setJpaPropertyMap(properties); return em; }
@Test public void requestMappingHandlerAdapter() throws Exception { delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); RequestMappingHandlerAdapter adapter = delegatingConfig.requestMappingHandlerAdapter(); ConfigurableWebBindingInitializer initializer = (ConfigurableWebBindingInitializer) adapter.getWebBindingInitializer(); ConversionService initializerConversionService = initializer.getConversionService(); assertTrue(initializer.getValidator() instanceof LocalValidatorFactoryBean); 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()); assertSame(conversionService.getValue(), initializerConversionService); assertEquals(0, resolvers.getValue().size()); assertEquals(0, handlers.getValue().size()); assertEquals(converters.getValue(), adapter.getMessageConverters()); assertNotNull(asyncConfigurer); }
@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(); }
@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(); }
@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")); }
@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(); }
@Test public void testSpringValidationWithErrorInListElement() throws Exception { 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()); }
@Test public void testSpringValidationWithErrorInSetElement() throws Exception { 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()); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); EventValidator.ValidationConfig validationConfig = new EventValidator.ValidationConfig(); validationConfig.setEnvironment(Mockito.mock(Environment.class)); EventValidator.setValidationConfig(validationConfig); this.validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); EntityFactory entityFactory = new HibEntityFactory(); EntityConverter entityConverter = new EntityConverter(entityFactory); this.converter = new ContentConverter(entityConverter); instanceUnderTest = new SimpleUrlContentReader(converter, null, validator, 700, instanceProvider); }
@Test public void requestMappingHandlerAdapter() throws Exception { RequestMappingHandlerAdapter adapter = mvcConfiguration.requestMappingHandlerAdapter(); List<HttpMessageConverter<?>> expectedConverters = new ArrayList<HttpMessageConverter<?>>(); mvcConfiguration.addDefaultHttpMessageConverters(expectedConverters); assertEquals(expectedConverters.size(), adapter.getMessageConverters().size()); 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); }
@Before public void setUp(){ currentUser.setProxyUser("admin", "test", new String[] {"VIEW_ENTITY", "CREATE_ENTITY"}); assertNotNull(headOfHouseholdService); localValidatorFactory = new LocalValidatorFactoryBean(); localValidatorFactory.setProviderClass(HibernateValidator.class); localValidatorFactory.afterPropertiesSet(); oldHoh = genericDao.findByProperty(Individual.class, "extId", "NBAS1I"); newHoh = genericDao.findByProperty(Individual.class, "extId", "BJOH1J"); visit = genericDao.findByProperty(Visit.class, "extId", "VLOCMBI11J"); fieldWorker = genericDao.findByProperty(FieldWorker.class, "extId", "FWEK1D"); socialGroup = genericDao.findByProperty(SocialGroup.class, "extId", "MBI1", false); assertNotNull(oldHoh); assertNotNull(newHoh); assertNotNull(visit); assertNotNull(fieldWorker); assertNotNull(socialGroup); }
@Bean public LocalValidatorFactoryBean localValidatorFactoryBean() { HibernateValidatorConfigurationStrategy strategy = Optional.ofNullable(hibernateValidatorConfigurationStrategy) .orElseGet(() -> configuration -> { }); List<? extends ConstraintValidator> validators = Optional.ofNullable(this.validators) .orElseGet(Collections::emptyList); return new CustomLocalValidatorFactoryBean(strategy, validators); }
@Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, MultiTenantConnectionProvider multiTenantConnectionProviderImpl, CurrentTenantIdentifierResolver currentTenantIdentifierResolverImpl, LocalValidatorFactoryBean localValidatorFactoryBean) { Map<String, Object> properties = new HashMap<>(); properties.putAll(jpaProperties.getHibernateProperties(dataSource)); properties.put(org.hibernate.cfg.Environment.MULTI_TENANT, MultiTenancyStrategy.SCHEMA); properties .put(org.hibernate.cfg.Environment.MULTI_TENANT_CONNECTION_PROVIDER, multiTenantConnectionProviderImpl); properties .put(org.hibernate.cfg.Environment.MULTI_TENANT_IDENTIFIER_RESOLVER, currentTenantIdentifierResolverImpl); properties.put(JPA_VALIDATION_FACTORY, localValidatorFactoryBean); LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(dataSource); em.setPackagesToScan(JPA_PACKAGES); em.setJpaVendorAdapter(jpaVendorAdapter()); em.setJpaPropertyMap(properties); return em; }
/** * Custom validator. * @param messageSource {@link MessageSource} * @return de {@link Validator} */ @Bean public Validator validator(MessageSource messageSource) { LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean(); factory.setValidationMessageSource(messageSource); return factory; }
@Override public Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource); return validator; }
@Override public Validator getValidator() { LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean(); localValidatorFactoryBean.setProviderClass(org.hibernate.validator.HibernateValidator.class); localValidatorFactoryBean.setValidationMessageSource(messageSource()); return localValidatorFactoryBean; }
@Before public void setup() { job = new Job(); localValidatorFactory = new LocalValidatorFactoryBean(); localValidatorFactory.setProviderClass(HibernateValidator.class); localValidatorFactory.afterPropertiesSet(); }
/** BeanValidationメッセージのUTF-8に対応したValidator。 */ @Bean LocalValidatorFactoryBean defaultValidator(MessageSource message) { LocalValidatorFactoryBean factory = new LocalValidatorFactoryBean(); factory.setValidationMessageSource(message); return factory; }
@SuppressWarnings("unused") @InitBinder private void initBinder(WebDataBinder binder) { binder.initBeanPropertyAccess(); binder.setRequiredFields("sex"); 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)); }
@SuppressWarnings("unused") @InitBinder({"myCommand", "date"}) private 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)); }
@Override public void initBinder(WebDataBinder binder, WebRequest request) { LocalValidatorFactoryBean vf = new LocalValidatorFactoryBean(); vf.afterPropertiesSet(); binder.setValidator(vf); assertNotNull(request.getLocale()); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false)); }
@Override public WebDataBinder createBinder(NativeWebRequest webRequest, Object target, String objectName) { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); WebDataBinder dataBinder = new WebDataBinder(target, objectName); dataBinder.setValidator(validator); return dataBinder; }
@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; }
@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()); }
@Test public void getCustomValidator() { given(webMvcConfigurer.getValidator()).willReturn(new LocalValidatorFactoryBean()); delegatingConfig.setConfigurers(Arrays.asList(webMvcConfigurer)); delegatingConfig.mvcValidator(); verify(webMvcConfigurer).getValidator(); }
@Test public void testSimpleValidationWithClassLevel() throws Exception { 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); }
@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)); }
@Test public void testSpringValidation() throws Exception { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.afterPropertiesSet(); ValidPerson person = new ValidPerson(); BeanPropertyBindingResult result = new BeanPropertyBindingResult(person, "person"); validator.validate(person, result); assertEquals(2, result.getErrorCount()); FieldError fieldError = result.getFieldError("name"); assertEquals("name", fieldError.getField()); List<String> errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(4, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.name")); assertTrue(errorCodes.contains("NotNull.name")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); fieldError = result.getFieldError("address.street"); assertEquals("address.street", fieldError.getField()); errorCodes = Arrays.asList(fieldError.getCodes()); assertEquals(5, errorCodes.size()); assertTrue(errorCodes.contains("NotNull.person.address.street")); assertTrue(errorCodes.contains("NotNull.address.street")); assertTrue(errorCodes.contains("NotNull.street")); assertTrue(errorCodes.contains("NotNull.java.lang.String")); assertTrue(errorCodes.contains("NotNull")); }
@Test public void testInnerBeanValidation() throws Exception { 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); }
@Test public void testValidationWithOptionalField() throws Exception { 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); }
@Bean public LocalValidatorFactoryBean localValidatorFactoryBean() throws ClassNotFoundException { LocalValidatorFactoryBean result = new LocalValidatorFactoryBean(); result.setProviderClass(Class.forName("org.hibernate.validator.HibernateValidator")); result.setValidationMessageSource(this.messageSource()); return result; }
@Override public Validator getValidator() { LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean(); validator.setValidationMessageSource(messageSource()); return validator; }
private RelaxedDataBinder getBinder(Object target, String namePrefix) { RelaxedDataBinder binder = new RelaxedDataBinder(target, namePrefix); binder.setIgnoreUnknownFields(false); LocalValidatorFactoryBean validatorFactoryBean = new LocalValidatorFactoryBean(); validatorFactoryBean.afterPropertiesSet(); binder.setValidator(validatorFactoryBean); binder.setConversionService(this.conversionService); return binder; }