@Test public void setTableName_Valid_ShouldSetTableName() { String tableName = "my_table"; JdbcClientRepository clientRepository = new JdbcClientRepository(this.jdbcOperations); clientRepository.setTableName(tableName); clientRepository.init(); assertThat((String) new DirectFieldAccessor(clientRepository).getPropertyValue("statementInsert")) .contains(tableName); assertThat((String) new DirectFieldAccessor(clientRepository).getPropertyValue("statementSelectById")) .contains(tableName); assertThat((String) new DirectFieldAccessor(clientRepository).getPropertyValue("statementSelectAll")) .contains(tableName); assertThat((String) new DirectFieldAccessor(clientRepository).getPropertyValue("statementUpdate")) .contains(tableName); assertThat((String) new DirectFieldAccessor(clientRepository).getPropertyValue("statementDelete")) .contains(tableName); }
@Test public void setTableName_Valid_ShouldSetTableName() { String tableName = "my_table"; JdbcRefreshTokenStore refreshTokenStore = new JdbcRefreshTokenStore(this.jdbcOperations); refreshTokenStore.setTableName(tableName); refreshTokenStore.init(); assertThat((String) new DirectFieldAccessor(refreshTokenStore).getPropertyValue("statementInsert")) .contains(tableName); assertThat((String) new DirectFieldAccessor(refreshTokenStore).getPropertyValue("statementSelectByToken")) .contains(tableName); assertThat((String) new DirectFieldAccessor(refreshTokenStore) .getPropertyValue("statementSelectByClientIdAndSubject")).contains(tableName); assertThat((String) new DirectFieldAccessor(refreshTokenStore).getPropertyValue("statementDeleteByToken")) .contains(tableName); assertThat((String) new DirectFieldAccessor(refreshTokenStore).getPropertyValue("statementDeleteExpired")) .contains(tableName); }
@Test public void fixedDelayTask() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(FixedDelayTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedDelayTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks"); assertEquals(1, fixedDelayTasks.size()); IntervalTask task = fixedDelayTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("fixedDelay", targetMethod.getName()); assertEquals(0L, task.getInitialDelay()); assertEquals(5000L, task.getInterval()); }
@Test public void fixedRateTask() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedRateTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); assertEquals(1, fixedRateTasks.size()); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("fixedRate", targetMethod.getName()); assertEquals(0L, task.getInitialDelay()); assertEquals(3000L, task.getInterval()); }
@Test public void fixedRateTaskWithInitialDelay() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(FixedRateWithInitialDelayTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedRateTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); assertEquals(1, fixedRateTasks.size()); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("fixedRate", targetMethod.getName()); assertEquals(1000L, task.getInitialDelay()); assertEquals(3000L, task.getInterval()); }
@Test public void testParentConnectionFactoryInheritedIfOverridden() { context = new SpringApplicationBuilder(SimpleProcessor.class, ConnectionFactoryConfiguration.class) .web(WebApplicationType.NONE) .run("--server.port=0"); BinderFactory binderFactory = context.getBean(BinderFactory.class); Binder<?, ?, ?> binder = binderFactory.getBinder(null, MessageChannel.class); assertThat(binder).isInstanceOf(RabbitMessageChannelBinder.class); DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder); ConnectionFactory binderConnectionFactory = (ConnectionFactory) binderFieldAccessor .getPropertyValue("connectionFactory"); assertThat(binderConnectionFactory).isSameAs(MOCK_CONNECTION_FACTORY); ConnectionFactory connectionFactory = context.getBean(ConnectionFactory.class); assertThat(binderConnectionFactory).isSameAs(connectionFactory); CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", CompositeHealthIndicator.class); assertThat(bindersHealthIndicator).isNotNull(); DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); @SuppressWarnings("unchecked") Map<String, HealthIndicator> healthIndicators = (Map<String, HealthIndicator>) directFieldAccessor .getPropertyValue("indicators"); assertThat(healthIndicators).containsKey("rabbit"); // mock connection factory behaves as if down assertThat(healthIndicators.get("rabbit").health().getStatus()).isEqualTo(Status.DOWN); }
@Test public void dispatcherServletDefaultConfig() { this.context = new AnnotationConfigWebApplicationContext(); this.context.setServletContext(new MockServletContext()); this.context.register(ServerPropertiesAutoConfiguration.class, DispatcherServletAutoConfiguration.class); this.context.refresh(); DispatcherServlet bean = this.context.getBean(DispatcherServlet.class); assertThat(bean).extracting("throwExceptionIfNoHandlerFound") .containsExactly(false); assertThat(bean).extracting("dispatchOptionsRequest").containsExactly(true); assertThat(bean).extracting("dispatchTraceRequest").containsExactly(false); assertThat(new DirectFieldAccessor( this.context.getBean("dispatcherServletRegistration")) .getPropertyValue("loadOnStartup")).isEqualTo(-1); }
@Test public void metaAnnotationWithCronExpression() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(MetaAnnotationCronTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<CronTask> cronTasks = (List<CronTask>) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); assertEquals(1, cronTasks.size()); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("generateReport", targetMethod.getName()); assertEquals("0 0 * * * ?", task.getExpression()); }
@Test public void defaultPropertyValues() throws Exception { this.context = new AnnotationConfigEmbeddedWebApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.mobile.devicedelegatingviewresolver.enabled:true"); this.context.register(Config.class, WebMvcAutoConfiguration.class, HttpMessageConvertersAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class, DeviceDelegatingViewResolverConfiguration.class); this.context.refresh(); LiteDeviceDelegatingViewResolver liteDeviceDelegatingViewResolver = this.context .getBean("deviceDelegatingViewResolver", LiteDeviceDelegatingViewResolver.class); DirectFieldAccessor accessor = new DirectFieldAccessor( liteDeviceDelegatingViewResolver); assertThat(accessor.getPropertyValue("enableFallback")).isEqualTo(Boolean.FALSE); assertThat(accessor.getPropertyValue("normalPrefix")).isEqualTo(""); assertThat(accessor.getPropertyValue("mobilePrefix")).isEqualTo("mobile/"); assertThat(accessor.getPropertyValue("tabletPrefix")).isEqualTo("tablet/"); assertThat(accessor.getPropertyValue("normalSuffix")).isEqualTo(""); assertThat(accessor.getPropertyValue("mobileSuffix")).isEqualTo(""); assertThat(accessor.getPropertyValue("tabletSuffix")).isEqualTo(""); }
@Test public void detectScriptTemplateConfigWithEngine() { InvocableScriptEngine engine = mock(InvocableScriptEngine.class); this.configurer.setEngine(engine); this.configurer.setRenderObject("Template"); this.configurer.setRenderFunction("render"); this.configurer.setContentType(MediaType.TEXT_PLAIN_VALUE); this.configurer.setCharset(StandardCharsets.ISO_8859_1); this.configurer.setSharedEngine(true); DirectFieldAccessor accessor = new DirectFieldAccessor(this.view); this.view.setApplicationContext(this.wac); assertEquals(engine, accessor.getPropertyValue("engine")); assertEquals("Template", accessor.getPropertyValue("renderObject")); assertEquals("render", accessor.getPropertyValue("renderFunction")); assertEquals(MediaType.TEXT_PLAIN_VALUE, accessor.getPropertyValue("contentType")); assertEquals(StandardCharsets.ISO_8859_1, accessor.getPropertyValue("charset")); assertEquals(true, accessor.getPropertyValue("sharedEngine")); }
@Test public void testConnectionFactoryWithOverrides() { load(TestConfiguration.class, "spring.rabbitmq.host:remote-server", "spring.rabbitmq.port:9000", "spring.rabbitmq.username:alice", "spring.rabbitmq.password:secret", "spring.rabbitmq.virtual_host:/vhost", "spring.rabbitmq.connection-timeout:123"); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); assertThat(connectionFactory.getHost()).isEqualTo("remote-server"); assertThat(connectionFactory.getPort()).isEqualTo(9000); assertThat(connectionFactory.getVirtualHost()).isEqualTo("/vhost"); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); com.rabbitmq.client.ConnectionFactory rcf = (com.rabbitmq.client.ConnectionFactory) dfa .getPropertyValue("rabbitConnectionFactory"); assertThat(rcf.getConnectionTimeout()).isEqualTo(123); }
@SuppressWarnings("unchecked") @Test public void standardDataSourceIsNotExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = new org.apache.commons.dbcp.BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); assertThat(excludedBeans).isEmpty(); }
private void doTestCustomValidator(String xml) throws Exception { loadBeanDefinitions(xml, 14); RequestMappingHandlerMapping mapping = appContext.getBean(RequestMappingHandlerMapping.class); assertNotNull(mapping); assertFalse(mapping.getUrlPathHelper().shouldRemoveSemicolonContent()); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); assertEquals(true, new DirectFieldAccessor(adapter).getPropertyValue("ignoreDefaultModelOnRedirect")); // default web binding initializer behavior test MockHttpServletRequest request = new MockHttpServletRequest(); request.addParameter("date", "2009-10-31"); MockHttpServletResponse response = new MockHttpServletResponse(); adapter.handle(request, response, handlerMethod); assertTrue(appContext.getBean(TestValidator.class).validatorInvoked); assertFalse(handler.recordedValidationError); }
@Test public void testAsyncSupportOptions() throws Exception { loadBeanDefinitions("mvc-config-async-support.xml", 15); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(adapter); assertEquals(ConcurrentTaskExecutor.class, fieldAccessor.getPropertyValue("taskExecutor").getClass()); assertEquals(2500L, fieldAccessor.getPropertyValue("asyncRequestTimeout")); CallableProcessingInterceptor[] callableInterceptors = (CallableProcessingInterceptor[]) fieldAccessor.getPropertyValue("callableInterceptors"); assertEquals(1, callableInterceptors.length); DeferredResultProcessingInterceptor[] deferredResultInterceptors = (DeferredResultProcessingInterceptor[]) fieldAccessor.getPropertyValue("deferredResultInterceptors"); assertEquals(1, deferredResultInterceptors.length); }
@Test public void testDefaultRabbitConfiguration() { load(TestConfiguration.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); RabbitMessagingTemplate messagingTemplate = this.context .getBean(RabbitMessagingTemplate.class); CachingConnectionFactory connectionFactory = this.context .getBean(CachingConnectionFactory.class); DirectFieldAccessor dfa = new DirectFieldAccessor(connectionFactory); RabbitAdmin amqpAdmin = this.context.getBean(RabbitAdmin.class); assertThat(rabbitTemplate.getConnectionFactory()).isEqualTo(connectionFactory); assertThat(getMandatory(rabbitTemplate)).isFalse(); assertThat(messagingTemplate.getRabbitTemplate()).isEqualTo(rabbitTemplate); assertThat(amqpAdmin).isNotNull(); assertThat(connectionFactory.getHost()).isEqualTo("localhost"); assertThat(dfa.getPropertyValue("publisherConfirms")).isEqualTo(false); assertThat(dfa.getPropertyValue("publisherReturns")).isEqualTo(false); assertThat(this.context.containsBean("rabbitListenerContainerFactory")) .as("Listener container factory should be created by default").isTrue(); }
@SuppressWarnings("unchecked") @Test public void testArgumentResolvers() { loadBeanDefinitions("mvc-config-argument-resolvers.xml"); RequestMappingHandlerAdapter adapter = appContext.getBean(RequestMappingHandlerAdapter.class); assertNotNull(adapter); Object value = new DirectFieldAccessor(adapter).getPropertyValue("customArgumentResolvers"); assertNotNull(value); assertTrue(value instanceof List); List<HandlerMethodArgumentResolver> resolvers = (List<HandlerMethodArgumentResolver>) value; assertEquals(3, resolvers.size()); assertTrue(resolvers.get(0) instanceof ServletWebArgumentResolverAdapter); assertTrue(resolvers.get(1) instanceof TestHandlerMethodArgumentResolver); assertTrue(resolvers.get(2) instanceof TestHandlerMethodArgumentResolver); assertNotSame(resolvers.get(1), resolvers.get(2)); }
@Test public void testJcaContainerConfiguration() throws Exception { Map<String, JmsMessageEndpointManager> containers = context.getBeansOfType(JmsMessageEndpointManager.class); assertTrue("listener3 not found", containers.containsKey("listener3")); JmsMessageEndpointManager listener3 = containers.get("listener3"); assertEquals("Wrong resource adapter", context.getBean("testResourceAdapter"), listener3.getResourceAdapter()); assertEquals("Wrong activation spec factory", context.getBean("testActivationSpecFactory"), new DirectFieldAccessor(listener3).getPropertyValue("activationSpecFactory")); Object endpointFactory = new DirectFieldAccessor(listener3).getPropertyValue("endpointFactory"); Object messageListener = new DirectFieldAccessor(endpointFactory).getPropertyValue("messageListener"); assertEquals("Wrong message listener", MessageListenerAdapter.class, messageListener.getClass()); MessageListenerAdapter adapter = (MessageListenerAdapter) messageListener; DirectFieldAccessor adapterFieldAccessor = new DirectFieldAccessor(adapter); assertEquals("Message converter not set properly", context.getBean("testMessageConverter"), adapterFieldAccessor.getPropertyValue("messageConverter")); assertEquals("Wrong delegate", context.getBean("testBean1"), adapterFieldAccessor.getPropertyValue("delegate")); assertEquals("Wrong method name", "setName", adapterFieldAccessor.getPropertyValue("defaultListenerMethod")); }
@Test public void testParentConnectionFactoryInheritedByDefault() { context = SpringApplication.run(SimpleProcessor.class, "--server.port=0"); BinderFactory<?> binderFactory = context.getBean(BinderFactory.class); Binder binder = binderFactory.getBinder(null); assertThat(binder, instanceOf(RedisMessageChannelBinder.class)); DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder); RedisConnectionFactory binderConnectionFactory = (RedisConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory"); assertThat(binderConnectionFactory, instanceOf(RedisConnectionFactory.class)); RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class); assertThat(binderConnectionFactory, is(connectionFactory)); CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", CompositeHealthIndicator.class); assertNotNull(bindersHealthIndicator); DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); @SuppressWarnings("unchecked") Map<String,HealthIndicator> healthIndicators = (Map<String, HealthIndicator>) directFieldAccessor.getPropertyValue("indicators"); assertThat(healthIndicators, hasKey("redis")); assertThat(healthIndicators.get("redis").health().getStatus(), equalTo(Status.UP)); }
@Test public void testParentConnectionFactoryInheritedIfOverridden() { context = new SpringApplication(SimpleProcessor.class, ConnectionFactoryConfiguration.class).run("--server.port=0"); BinderFactory<?> binderFactory = context.getBean(BinderFactory.class); Binder binder = binderFactory.getBinder(null); assertThat(binder, instanceOf(RedisMessageChannelBinder.class)); DirectFieldAccessor binderFieldAccessor = new DirectFieldAccessor(binder); RedisConnectionFactory binderConnectionFactory = (RedisConnectionFactory) binderFieldAccessor.getPropertyValue("connectionFactory"); assertThat(binderConnectionFactory, is(MOCK_CONNECTION_FACTORY)); RedisConnectionFactory connectionFactory = context.getBean(RedisConnectionFactory.class); assertThat(binderConnectionFactory, is(connectionFactory)); CompositeHealthIndicator bindersHealthIndicator = context.getBean("bindersHealthIndicator", CompositeHealthIndicator.class); assertNotNull(bindersHealthIndicator); DirectFieldAccessor directFieldAccessor = new DirectFieldAccessor(bindersHealthIndicator); @SuppressWarnings("unchecked") Map<String,HealthIndicator> healthIndicators = (Map<String, HealthIndicator>) directFieldAccessor.getPropertyValue("indicators"); assertThat(healthIndicators, hasKey("redis")); assertThat(healthIndicators.get("redis").health().getStatus(), equalTo(Status.UP)); }
@SuppressWarnings("unchecked") @Test public void mbeanDataSourceIsExcludedFromExport() throws IllegalStateException, NamingException { DataSource dataSource = new BasicDataSource(); configureJndi("foo", dataSource); this.context = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(this.context, "spring.datasource.jndi-name:foo"); this.context.register(JndiDataSourceAutoConfiguration.class, MBeanExporterConfiguration.class); this.context.refresh(); assertThat(this.context.getBean(DataSource.class)).isEqualTo(dataSource); MBeanExporter exporter = this.context.getBean(MBeanExporter.class); Set<String> excludedBeans = (Set<String>) new DirectFieldAccessor(exporter) .getPropertyValue("excludedBeans"); assertThat(excludedBeans).containsExactly("dataSource"); }
@Test public void hazelcastCacheWithMainHazelcastAutoConfigurationAndSeparateCacheConfig() throws IOException { String mainConfig = "org/springframework/boot/autoconfigure/hazelcast/hazelcast-specific.xml"; String cacheConfig = "org/springframework/boot/autoconfigure/cache/hazelcast-specific.xml"; AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(); EnvironmentTestUtils.addEnvironment(applicationContext, "spring.cache.type=hazelcast", "spring.cache.hazelcast.config=" + cacheConfig, "spring.hazelcast.config=" + mainConfig); applicationContext.register(DefaultCacheConfiguration.class); applicationContext.register(HazelcastAndCacheConfiguration.class); applicationContext.refresh(); this.context = applicationContext; HazelcastInstance hazelcastInstance = this.context .getBean(HazelcastInstance.class); HazelcastCacheManager cacheManager = validateCacheManager( HazelcastCacheManager.class); HazelcastInstance cacheHazelcastInstance = (HazelcastInstance) new DirectFieldAccessor( cacheManager).getPropertyValue("hazelcastInstance"); assertThat(cacheHazelcastInstance).isNotEqualTo(hazelcastInstance); // Our custom assertThat(hazelcastInstance.getConfig().getConfigurationFile()) .isEqualTo(new ClassPathResource(mainConfig).getFile()); assertThat(cacheHazelcastInstance.getConfig().getConfigurationFile()) .isEqualTo(new ClassPathResource(cacheConfig).getFile()); }
@Test public void testSink() throws Exception { assertNotNull(this.sink.input()); this.sink.input().send(new GenericMessage<>("foo")); Log logger = spy(TestUtils.getPropertyValue(this.configuration, "logger", Log.class)); new DirectFieldAccessor(this.configuration).setPropertyValue("logger", logger); final CountDownLatch latch = new CountDownLatch(1); doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { invocation.callRealMethod(); latch.countDown(); return null; } }).when(logger).info(anyString()); assertTrue(latch.await(10, TimeUnit.SECONDS)); }
@Test public void testDecoratingChainBuiltCorrectly() throws Exception { System.setProperty(PropertyLoader.PROPERTIES_FILE_PATH, "db/decorator/flexy-pool.properties"); context.register(DataSourceAutoConfiguration.class, DataSourceDecoratorAutoConfiguration.class, PropertyPlaceholderAutoConfiguration.class); context.refresh(); DataSource dataSource = context.getBean(DataSource.class); DecoratedDataSource dataSource1 = context.getBean(DecoratedDataSource.class); assertThat(dataSource1).isNotNull(); DataSource p6DataSource = dataSource1.getDecoratedDataSource(); assertThat(p6DataSource).isNotNull(); assertThat(p6DataSource).isInstanceOf(P6DataSource.class); DataSource proxyDataSource = (DataSource) new DirectFieldAccessor(p6DataSource) .getPropertyValue("realDataSource"); assertThat(proxyDataSource).isNotNull(); assertThat(proxyDataSource).isInstanceOf(ProxyDataSource.class); DataSource flexyDataSource = (DataSource) new DirectFieldAccessor(proxyDataSource) .getPropertyValue("dataSource"); assertThat(flexyDataSource).isNotNull(); assertThat(flexyDataSource).isInstanceOf(FlexyPoolDataSource.class); DataSource realDataSource = (DataSource) new DirectFieldAccessor(flexyDataSource) .getPropertyValue("targetDataSource"); assertThat(realDataSource).isNotNull(); assertThat(realDataSource).isInstanceOf((Class<? extends DataSource>) org.apache.tomcat.jdbc.pool.DataSource.class); assertThatDataSourceDecoratingChain(dataSource).containsExactly(P6DataSource.class, ProxyDataSource.class, FlexyPoolDataSource.class); assertThat(dataSource.toString()).isEqualTo( "p6SpyDataSourceDecorator [com.p6spy.engine.spy.P6DataSource] -> " + "proxyDataSourceDecorator [net.ttddyy.dsproxy.support.ProxyDataSource] -> " + "flexyPoolDataSourceDecorator [com.vladmihalcea.flexypool.FlexyPoolDataSource] -> " + "dataSource [org.apache.tomcat.jdbc.pool.DataSource]"); }
@Test public void setMapName_Valid_ShouldSetMapName() { String mapName = "myMap"; HazelcastAuthorizationCodeService authorizationCodeService = new HazelcastAuthorizationCodeService( this.hazelcastInstance); authorizationCodeService.setMapName(mapName); authorizationCodeService.init(); assertThat((String) new DirectFieldAccessor(authorizationCodeService).getPropertyValue("mapName")) .isEqualTo(mapName); }
@Test public void setCodeLifetime_Valid_ShouldSetCodeLifetime() { Duration codeLifetime = Duration.ofMinutes(1); HazelcastAuthorizationCodeService authorizationCodeService = new HazelcastAuthorizationCodeService( this.hazelcastInstance); authorizationCodeService.setCodeLifetime(codeLifetime); authorizationCodeService.init(); assertThat((Duration) new DirectFieldAccessor(authorizationCodeService).getPropertyValue("codeLifetime")) .isEqualTo(codeLifetime); }
private <E> E getRowObject(Row row, Map<Integer, String> interestServerRowDetail, Class<E> clz) { E instance = ClassUtils.newInstance(clz, true); DirectFieldAccessor fieldAccessor = new DirectFieldAccessor(instance); fieldAccessor.setConversionService(getConversionService()); for (Entry<Integer, String> entry : interestServerRowDetail.entrySet()) { Cell cell = row.getCell(entry.getKey()); if(cell == null){ continue; } String cellContent = getCellContent(cell); try { fieldAccessor.setPropertyValue(entry.getValue(), cellContent); } catch (Exception e) { if(getDebug().isIgnoreConvert()){ break; } /* * String message = MessageFormatter * .format("无法将[{}]资源的Sheet[{}]的[{}]行的[{}]--[{}]转换成对应的属性") * .getMessage(); */ String message = new StringBuilder().append("无法将[").append(clz.getSimpleName()).append("]资源的Sheet[") .append(row.getSheet().getSheetName()).append("]的[").append(row.getRowNum()).append("]行的[") .append(entry.getValue()).append("]--[").append(cellContent).append("]转换成对应的属性").toString(); log.error(message); throw new ResourceParseException(message); } } return instance; }
private void severalFixedRates(StaticApplicationContext context, BeanDefinition processorDefinition, BeanDefinition targetDefinition) { context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedRateTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); assertEquals(2, fixedRateTasks.size()); IntervalTask task1 = fixedRateTasks.get(0); ScheduledMethodRunnable runnable1 = (ScheduledMethodRunnable) task1.getRunnable(); Object targetObject = runnable1.getTarget(); Method targetMethod = runnable1.getMethod(); assertEquals(target, targetObject); assertEquals("fixedRate", targetMethod.getName()); assertEquals(0, task1.getInitialDelay()); assertEquals(4000L, task1.getInterval()); IntervalTask task2 = fixedRateTasks.get(1); ScheduledMethodRunnable runnable2 = (ScheduledMethodRunnable) task2.getRunnable(); targetObject = runnable2.getTarget(); targetMethod = runnable2.getMethod(); assertEquals(target, targetObject); assertEquals("fixedRate", targetMethod.getName()); assertEquals(2000L, task2.getInitialDelay()); assertEquals(4000L, task2.getInterval()); }
@Test public void cronTask() throws InterruptedException { Assume.group(TestGroup.LONG_RUNNING); BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition targetDefinition = new RootBeanDefinition(CronTestBean.class); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<CronTask> cronTasks = (List<CronTask>) new DirectFieldAccessor(registrar).getPropertyValue("cronTasks"); assertEquals(1, cronTasks.size()); CronTask task = cronTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("cron", targetMethod.getName()); assertEquals("*/7 * * * * ?", task.getExpression()); Thread.sleep(10000); }
@Test public void testRabbitTemplateMessageConverters() { load(MessageConvertersConfiguration.class); RabbitTemplate rabbitTemplate = this.context.getBean(RabbitTemplate.class); assertThat(rabbitTemplate.getMessageConverter()) .isSameAs(this.context.getBean("myMessageConverter")); DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate); assertThat(dfa.getPropertyValue("retryTemplate")).isNull(); }
@Test public void propertyPlaceholderWithFixedDelay() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); Properties properties = new Properties(); properties.setProperty("fixedDelay", "5000"); properties.setProperty("initialDelay", "1000"); placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties); BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedDelayTestBean.class); context.registerBeanDefinition("placeholder", placeholderDefinition); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedDelayTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedDelayTasks"); assertEquals(1, fixedDelayTasks.size()); IntervalTask task = fixedDelayTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("fixedDelay", targetMethod.getName()); assertEquals(1000L, task.getInitialDelay()); assertEquals(5000L, task.getInterval()); }
@Test public void propertyPlaceholderWithFixedRate() { BeanDefinition processorDefinition = new RootBeanDefinition(ScheduledAnnotationBeanPostProcessor.class); BeanDefinition placeholderDefinition = new RootBeanDefinition(PropertyPlaceholderConfigurer.class); Properties properties = new Properties(); properties.setProperty("fixedRate", "3000"); properties.setProperty("initialDelay", "1000"); placeholderDefinition.getPropertyValues().addPropertyValue("properties", properties); BeanDefinition targetDefinition = new RootBeanDefinition(PropertyPlaceholderWithFixedRateTestBean.class); context.registerBeanDefinition("placeholder", placeholderDefinition); context.registerBeanDefinition("postProcessor", processorDefinition); context.registerBeanDefinition("target", targetDefinition); context.refresh(); Object postProcessor = context.getBean("postProcessor"); Object target = context.getBean("target"); ScheduledTaskRegistrar registrar = (ScheduledTaskRegistrar) new DirectFieldAccessor(postProcessor).getPropertyValue("registrar"); @SuppressWarnings("unchecked") List<IntervalTask> fixedRateTasks = (List<IntervalTask>) new DirectFieldAccessor(registrar).getPropertyValue("fixedRateTasks"); assertEquals(1, fixedRateTasks.size()); IntervalTask task = fixedRateTasks.get(0); ScheduledMethodRunnable runnable = (ScheduledMethodRunnable) task.getRunnable(); Object targetObject = runnable.getTarget(); Method targetMethod = runnable.getMethod(); assertEquals(target, targetObject); assertEquals("fixedRate", targetMethod.getName()); assertEquals(1000L, task.getInitialDelay()); assertEquals(3000L, task.getInterval()); }
@Test public void checkTarget() { List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedRateTasks"); Runnable runnable = tasks.get(0).getRunnable(); assertEquals(ScheduledMethodRunnable.class, runnable.getClass()); Object targetObject = ((ScheduledMethodRunnable) runnable).getTarget(); Method targetMethod = ((ScheduledMethodRunnable) runnable).getMethod(); assertEquals(this.testBean, targetObject); assertEquals("test", targetMethod.getName()); }
@Test public void fixedRateTasks() { List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedRateTasks"); assertEquals(3, tasks.size()); assertEquals(1000L, tasks.get(0).getInterval()); assertEquals(2000L, tasks.get(1).getInterval()); assertEquals(4000L, tasks.get(2).getInterval()); assertEquals(500, tasks.get(2).getInitialDelay()); }
@Test public void fixedDelayTasks() { List<IntervalTask> tasks = (List<IntervalTask>) new DirectFieldAccessor( this.registrar).getPropertyValue("fixedDelayTasks"); assertEquals(2, tasks.size()); assertEquals(3000L, tasks.get(0).getInterval()); assertEquals(3500L, tasks.get(1).getInterval()); assertEquals(250, tasks.get(1).getInitialDelay()); }
@Test public void defaultLifecycleProcessorInstance() { StaticApplicationContext context = new StaticApplicationContext(); context.refresh(); Object lifecycleProcessor = new DirectFieldAccessor(context).getPropertyValue("lifecycleProcessor"); assertNotNull(lifecycleProcessor); assertEquals(DefaultLifecycleProcessor.class, lifecycleProcessor.getClass()); }
@Test public void redisSessionStoreWithCustomizations() { load(Collections.<Class<?>>singletonList(RedisAutoConfiguration.class), "spring.session.store-type=redis", "spring.session.redis.namespace=foo", "spring.session.redis.flush-mode=immediate"); RedisOperationsSessionRepository repository = validateSessionRepository( RedisOperationsSessionRepository.class); assertThat(repository.getSessionCreatedChannelPrefix()) .isEqualTo("spring:session:foo:event:created:"); assertThat(new DirectFieldAccessor(repository).getPropertyValue("redisFlushMode")) .isEqualTo(RedisFlushMode.IMMEDIATE); }
@Test public void jdbcSessionStoreCustomTableName() { load(Arrays.asList(EmbeddedDataSourceConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class), "spring.session.store-type=jdbc", "spring.session.jdbc.table-name=FOO_BAR"); JdbcOperationsSessionRepository repository = validateSessionRepository( JdbcOperationsSessionRepository.class); assertThat(new DirectFieldAccessor(repository).getPropertyValue("tableName")) .isEqualTo("FOO_BAR"); }