public void testAppContextClassHierarchy() { Class<?>[] clazz = ClassUtils.getClassHierarchy(OsgiBundleXmlApplicationContext.class, ClassUtils.ClassSet.ALL_CLASSES); //Closeable.class, Class<?>[] expected = new Class<?>[] { OsgiBundleXmlApplicationContext.class, AbstractDelegatedExecutionApplicationContext.class, AbstractOsgiBundleApplicationContext.class, AbstractRefreshableApplicationContext.class, AbstractApplicationContext.class, DefaultResourceLoader.class, ResourceLoader.class, AutoCloseable.class, DelegatedExecutionOsgiBundleApplicationContext.class, ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, MessageSource.class, BeanFactory.class, DisposableBean.class }; assertTrue(compareArrays(expected, clazz)); }
private void startBeans(boolean autoStartupOnly) { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new HashMap<Integer, LifecycleGroup>(); for (Map.Entry<String, ? extends Lifecycle> entry : lifecycleBeans.entrySet()) { Lifecycle bean = entry.getValue(); if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) { int phase = getPhase(bean); LifecycleGroup group = phases.get(phase); if (group == null) { group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly); phases.put(phase, group); } group.add(entry.getKey(), bean); } } if (phases.size() > 0) { List<Integer> keys = new ArrayList<Integer>(phases.keySet()); Collections.sort(keys); for (Integer key : keys) { phases.get(key).start(); } } }
/** * Start the specified bean as part of the given set of Lifecycle beans, * making sure that any beans that it depends on are started first. * @param lifecycleBeans Map with bean name as key and Lifecycle instance as value * @param beanName the name of the bean to start */ private void doStart(Map<String, ? extends Lifecycle> lifecycleBeans, String beanName, boolean autoStartupOnly) { Lifecycle bean = lifecycleBeans.remove(beanName); if (bean != null && !this.equals(bean)) { String[] dependenciesForBean = this.beanFactory.getDependenciesForBean(beanName); for (String dependency : dependenciesForBean) { doStart(lifecycleBeans, dependency, autoStartupOnly); } if (!bean.isRunning() && (!autoStartupOnly || !(bean instanceof SmartLifecycle) || ((SmartLifecycle) bean).isAutoStartup())) { if (logger.isDebugEnabled()) { logger.debug("Starting bean '" + beanName + "' of type [" + bean.getClass() + "]"); } try { bean.start(); } catch (Throwable ex) { throw new ApplicationContextException("Failed to start bean '" + beanName + "'", ex); } if (logger.isDebugEnabled()) { logger.debug("Successfully started bean '" + beanName + "'"); } } } }
private void stopBeans() { Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans(); Map<Integer, LifecycleGroup> phases = new HashMap<Integer, LifecycleGroup>(); for (Map.Entry<String, Lifecycle> entry : lifecycleBeans.entrySet()) { Lifecycle bean = entry.getValue(); int shutdownOrder = getPhase(bean); LifecycleGroup group = phases.get(shutdownOrder); if (group == null) { group = new LifecycleGroup(shutdownOrder, this.timeoutPerShutdownPhase, lifecycleBeans, false); phases.put(shutdownOrder, group); } group.add(entry.getKey(), bean); } if (phases.size() > 0) { List<Integer> keys = new ArrayList<Integer>(phases.keySet()); Collections.sort(keys, Collections.reverseOrder()); for (Integer key : keys) { phases.get(key).stop(); } } }
/** * Retrieve all applicable Lifecycle beans: all singletons that have already been created, * as well as all SmartLifecycle beans (even if they are marked as lazy-init). * @return the Map of applicable beans, with bean names as keys and bean instances as values */ protected Map<String, Lifecycle> getLifecycleBeans() { Map<String, Lifecycle> beans = new LinkedHashMap<String, Lifecycle>(); String[] beanNames = this.beanFactory.getBeanNamesForType(Lifecycle.class, false, false); for (String beanName : beanNames) { String beanNameToRegister = BeanFactoryUtils.transformedBeanName(beanName); boolean isFactoryBean = this.beanFactory.isFactoryBean(beanNameToRegister); String beanNameToCheck = (isFactoryBean ? BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName); if ((this.beanFactory.containsSingleton(beanNameToRegister) && (!isFactoryBean || Lifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck)))) || SmartLifecycle.class.isAssignableFrom(this.beanFactory.getType(beanNameToCheck))) { Lifecycle bean = this.beanFactory.getBean(beanNameToCheck, Lifecycle.class); if (bean != this) { beans.put(beanNameToRegister, bean); } } } return beans; }
@Test public void singleSmartLifecycleWithoutAutoStartup() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean bean = TestSmartLifecycleBean.forStartupTests(1, startedBeans); bean.setAutoStartup(false); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); assertFalse(bean.isRunning()); context.refresh(); assertFalse(bean.isRunning()); assertEquals(0, startedBeans.size()); context.start(); assertTrue(bean.isRunning()); assertEquals(1, startedBeans.size()); context.stop(); }
@Test public void singleSmartLifecycleAutoStartupWithNonAutoStartupDependency() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean bean = TestSmartLifecycleBean.forStartupTests(1, startedBeans); bean.setAutoStartup(true); TestSmartLifecycleBean dependency = TestSmartLifecycleBean.forStartupTests(1, startedBeans); dependency.setAutoStartup(false); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); context.getBeanFactory().registerSingleton("dependency", dependency); context.getBeanFactory().registerDependentBean("dependency", "bean"); assertFalse(bean.isRunning()); assertFalse(dependency.isRunning()); context.refresh(); assertTrue(bean.isRunning()); assertFalse(dependency.isRunning()); context.stop(); assertFalse(bean.isRunning()); assertFalse(dependency.isRunning()); assertEquals(1, startedBeans.size()); }
@Test public void dependencyStartedFirstButNotSmartLifecycle() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean beanMin = TestSmartLifecycleBean.forStartupTests(Integer.MIN_VALUE, startedBeans); TestSmartLifecycleBean bean7 = TestSmartLifecycleBean.forStartupTests(7, startedBeans); TestLifecycleBean simpleBean = TestLifecycleBean.forStartupTests(startedBeans); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("beanMin", beanMin); context.getBeanFactory().registerSingleton("bean7", bean7); context.getBeanFactory().registerSingleton("simpleBean", simpleBean); context.getBeanFactory().registerDependentBean("simpleBean", "beanMin"); context.refresh(); assertTrue(beanMin.isRunning()); assertTrue(bean7.isRunning()); assertTrue(simpleBean.isRunning()); assertEquals(3, startedBeans.size()); assertEquals(0, getPhase(startedBeans.get(0))); assertEquals(Integer.MIN_VALUE, getPhase(startedBeans.get(1))); assertEquals(7, getPhase(startedBeans.get(2))); context.stop(); }
@Before public void setup() throws Exception { logger.debug("Setting up '" + this.testName.getMethodName() + "', client=" + this.webSocketClient.getClass().getSimpleName() + ", server=" + this.server.getClass().getSimpleName()); this.wac = new AnnotationConfigWebApplicationContext(); this.wac.register(getAnnotatedConfigClasses()); this.wac.register(upgradeStrategyConfigTypes.get(this.server.getClass())); if (this.webSocketClient instanceof Lifecycle) { ((Lifecycle) this.webSocketClient).start(); } this.server.setup(); this.server.deployConfig(this.wac); // Set ServletContext in WebApplicationContext after deployment but before // starting the server. this.wac.setServletContext(this.server.getServletContext()); this.wac.refresh(); this.server.start(); }
@Before public void setup() throws Exception { this.client = new ReactorNettyWebSocketClient(); this.server = new ReactorHttpServer(); this.server.setHandler(createHttpHandler()); this.server.afterPropertiesSet(); this.server.start(); // Set dynamically chosen port this.serverPort = this.server.getPort(); if (this.client instanceof Lifecycle) { ((Lifecycle) this.client).start(); } this.gatewayContext = new SpringApplicationBuilder(GatewayConfig.class) .properties("ws.server.port:"+this.serverPort, "server.port=0", "spring.jmx.enabled=false") .run(); GatewayConfig config = this.gatewayContext.getBean(GatewayConfig.class); ConfigurableEnvironment env = this.gatewayContext.getBean(ConfigurableEnvironment.class); this.gatewayPort = new Integer(env.getProperty("local.server.port")); }
private SimpleMessageListenerContainer verifyContainer(Lifecycle endpoint) { SimpleMessageListenerContainer container; RetryTemplate retry; container = TestUtils.getPropertyValue(endpoint, "messageListenerContainer", SimpleMessageListenerContainer.class); assertThat(container.getAcknowledgeMode()).isEqualTo(AcknowledgeMode.NONE); assertThat(container.getQueueNames()[0]).startsWith("foo.props.0"); assertThat(TestUtils.getPropertyValue(container, "transactional", Boolean.class)).isFalse(); assertThat(TestUtils.getPropertyValue(container, "concurrentConsumers")).isEqualTo(2); assertThat(TestUtils.getPropertyValue(container, "maxConcurrentConsumers")).isEqualTo(3); assertThat(TestUtils.getPropertyValue(container, "defaultRequeueRejected", Boolean.class)).isFalse(); assertThat(TestUtils.getPropertyValue(container, "prefetchCount")).isEqualTo(20); assertThat(TestUtils.getPropertyValue(container, "txSize")).isEqualTo(10); retry = TestUtils.getPropertyValue(endpoint, "retryTemplate", RetryTemplate.class); assertThat(TestUtils.getPropertyValue(retry, "retryPolicy.maxAttempts")).isEqualTo(23); assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.initialInterval")).isEqualTo(2000L); assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.maxInterval")).isEqualTo(20000L); assertThat(TestUtils.getPropertyValue(retry, "backOffPolicy.multiplier")).isEqualTo(5.0); List<?> requestMatchers = TestUtils.getPropertyValue(endpoint, "headerMapper.requestHeaderMatcher.matchers", List.class); assertThat(requestMatchers).hasSize(1); assertThat(TestUtils.getPropertyValue(requestMatchers.get(0), "pattern")).isEqualTo("foo"); return container; }
/** * Stops this repository. */ @Override public void stop() { Status status = _status.get(); if (status == Status.STOPPING || status == Status.STOPPED) { return; // nothing to stop in this thread } if (_status.compareAndSet(status, Status.STOPPING) == false) { return; // another thread just beat this one } for (List<Lifecycle> list : Lists.reverse(ImmutableList.copyOf(_lifecycles.values()))) { for (Lifecycle obj : Lists.reverse(list)) { try { obj.stop(); } catch (Exception ex) { // ignore } } } _status.set(Status.STOPPED); }
public void testStartStop_passThrough() { final Lifecycle lifecycle = Mockito.mock(Lifecycle.class); Mockito.when(lifecycle.isRunning()).thenReturn(true); final TempTargetRepository underlying = new LifecycleTempTargetRepository(lifecycle); final EHCachingTempTargetRepository cache = new EHCachingTempTargetRepository(underlying, _cacheManager); Mockito.verify(lifecycle, Mockito.times(0)).start(); Mockito.verify(lifecycle, Mockito.times(0)).stop(); Mockito.verify(lifecycle, Mockito.times(0)).isRunning(); assertFalse(cache.isRunning()); cache.start(); Mockito.verify(lifecycle, Mockito.times(1)).start(); assertTrue(cache.isRunning()); Mockito.verify(lifecycle, Mockito.times(1)).isRunning(); cache.stop(); Mockito.verify(lifecycle, Mockito.times(1)).stop(); assertFalse(cache.isRunning()); Mockito.verify(lifecycle, Mockito.times(1)).start(); Mockito.verify(lifecycle, Mockito.times(1)).isRunning(); Mockito.verify(lifecycle, Mockito.times(1)).stop(); }
/** * Tries to "close" an object. * <p> * This invokes the close method if it is present. * * @param obj the object, null ignored */ public static void close(final Object obj) { if (obj != null) { try { if (obj instanceof Closeable) { ((Closeable) obj).close(); } else if (obj instanceof Lifecycle) { ((Lifecycle) obj).stop(); } else if (obj instanceof DisposableBean) { ((DisposableBean) obj).destroy(); } else { invokeNoArgsNoException(obj, "close"); invokeNoArgsNoException(obj, "stop"); invokeNoArgsNoException(obj, "shutdown"); } } catch (Exception ex) { // ignored } } }
public void testAppContextClassHierarchy() { Class[] clazz = ClassUtils.getClassHierarchy(OsgiBundleXmlApplicationContext.class, ClassUtils.INCLUDE_ALL_CLASSES); Class[] expected = new Class[] { OsgiBundleXmlApplicationContext.class, AbstractDelegatedExecutionApplicationContext.class, DelegatedExecutionOsgiBundleApplicationContext.class, ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, MessageSource.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, BeanFactory.class, ResourceLoader.class, AutoCloseable.class, AbstractOsgiBundleApplicationContext.class, AbstractRefreshableApplicationContext.class, AbstractApplicationContext.class, DisposableBean.class, DefaultResourceLoader.class }; String msg = "Class: "; for (int i=0;i<clazz.length;i++) { msg += clazz[i].getSimpleName() + " "; } assertTrue(msg, compareArrays(expected, clazz)); }
public void testInterfacesHierarchy() { //Closeable.class, Class<?>[] clazz = ClassUtils.getAllInterfaces(DelegatedExecutionOsgiBundleApplicationContext.class); Class<?>[] expected = { ConfigurableOsgiBundleApplicationContext.class, ConfigurableApplicationContext.class, ApplicationContext.class, Lifecycle.class, Closeable.class, EnvironmentCapable.class, ListableBeanFactory.class, HierarchicalBeanFactory.class, MessageSource.class, ApplicationEventPublisher.class, ResourcePatternResolver.class, BeanFactory.class, ResourceLoader.class, AutoCloseable.class }; assertTrue(compareArrays(expected, clazz)); }
@Test public void singleSmartLifecycleAutoStartup() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean bean = TestSmartLifecycleBean.forStartupTests(1, startedBeans); bean.setAutoStartup(true); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean", bean); assertFalse(bean.isRunning()); context.refresh(); assertTrue(bean.isRunning()); context.stop(); assertFalse(bean.isRunning()); assertEquals(1, startedBeans.size()); }
@Test public void smartLifecycleGroupStartup() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean beanMin = TestSmartLifecycleBean.forStartupTests(Integer.MIN_VALUE, startedBeans); TestSmartLifecycleBean bean1 = TestSmartLifecycleBean.forStartupTests(1, startedBeans); TestSmartLifecycleBean bean2 = TestSmartLifecycleBean.forStartupTests(2, startedBeans); TestSmartLifecycleBean bean3 = TestSmartLifecycleBean.forStartupTests(3, startedBeans); TestSmartLifecycleBean beanMax = TestSmartLifecycleBean.forStartupTests(Integer.MAX_VALUE, startedBeans); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean3", bean3); context.getBeanFactory().registerSingleton("beanMin", beanMin); context.getBeanFactory().registerSingleton("bean2", bean2); context.getBeanFactory().registerSingleton("beanMax", beanMax); context.getBeanFactory().registerSingleton("bean1", bean1); assertFalse(beanMin.isRunning()); assertFalse(bean1.isRunning()); assertFalse(bean2.isRunning()); assertFalse(bean3.isRunning()); assertFalse(beanMax.isRunning()); context.refresh(); assertTrue(beanMin.isRunning()); assertTrue(bean1.isRunning()); assertTrue(bean2.isRunning()); assertTrue(bean3.isRunning()); assertTrue(beanMax.isRunning()); context.stop(); assertEquals(5, startedBeans.size()); assertEquals(Integer.MIN_VALUE, getPhase(startedBeans.get(0))); assertEquals(1, getPhase(startedBeans.get(1))); assertEquals(2, getPhase(startedBeans.get(2))); assertEquals(3, getPhase(startedBeans.get(3))); assertEquals(Integer.MAX_VALUE, getPhase(startedBeans.get(4))); }
@Test public void contextRefreshThenStartWithMixedBeans() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestLifecycleBean simpleBean1 = TestLifecycleBean.forStartupTests(startedBeans); TestLifecycleBean simpleBean2 = TestLifecycleBean.forStartupTests(startedBeans); TestSmartLifecycleBean smartBean1 = TestSmartLifecycleBean.forStartupTests(5, startedBeans); TestSmartLifecycleBean smartBean2 = TestSmartLifecycleBean.forStartupTests(-3, startedBeans); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("simpleBean1", simpleBean1); context.getBeanFactory().registerSingleton("smartBean1", smartBean1); context.getBeanFactory().registerSingleton("simpleBean2", simpleBean2); context.getBeanFactory().registerSingleton("smartBean2", smartBean2); assertFalse(simpleBean1.isRunning()); assertFalse(simpleBean2.isRunning()); assertFalse(smartBean1.isRunning()); assertFalse(smartBean2.isRunning()); context.refresh(); assertTrue(smartBean1.isRunning()); assertTrue(smartBean2.isRunning()); assertFalse(simpleBean1.isRunning()); assertFalse(simpleBean2.isRunning()); assertEquals(2, startedBeans.size()); assertEquals(-3, getPhase(startedBeans.get(0))); assertEquals(5, getPhase(startedBeans.get(1))); context.start(); assertTrue(smartBean1.isRunning()); assertTrue(smartBean2.isRunning()); assertTrue(simpleBean1.isRunning()); assertTrue(simpleBean2.isRunning()); assertEquals(4, startedBeans.size()); assertEquals(0, getPhase(startedBeans.get(2))); assertEquals(0, getPhase(startedBeans.get(3))); }
@Test public void contextRefreshThenStopAndRestartWithMixedBeans() throws Exception { CopyOnWriteArrayList<Lifecycle> startedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestLifecycleBean simpleBean1 = TestLifecycleBean.forStartupTests(startedBeans); TestLifecycleBean simpleBean2 = TestLifecycleBean.forStartupTests(startedBeans); TestSmartLifecycleBean smartBean1 = TestSmartLifecycleBean.forStartupTests(5, startedBeans); TestSmartLifecycleBean smartBean2 = TestSmartLifecycleBean.forStartupTests(-3, startedBeans); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("simpleBean1", simpleBean1); context.getBeanFactory().registerSingleton("smartBean1", smartBean1); context.getBeanFactory().registerSingleton("simpleBean2", simpleBean2); context.getBeanFactory().registerSingleton("smartBean2", smartBean2); assertFalse(simpleBean1.isRunning()); assertFalse(simpleBean2.isRunning()); assertFalse(smartBean1.isRunning()); assertFalse(smartBean2.isRunning()); context.refresh(); assertTrue(smartBean1.isRunning()); assertTrue(smartBean2.isRunning()); assertFalse(simpleBean1.isRunning()); assertFalse(simpleBean2.isRunning()); assertEquals(2, startedBeans.size()); assertEquals(-3, getPhase(startedBeans.get(0))); assertEquals(5, getPhase(startedBeans.get(1))); context.stop(); assertFalse(simpleBean1.isRunning()); assertFalse(simpleBean2.isRunning()); assertFalse(smartBean1.isRunning()); assertFalse(smartBean2.isRunning()); context.start(); assertTrue(smartBean1.isRunning()); assertTrue(smartBean2.isRunning()); assertTrue(simpleBean1.isRunning()); assertTrue(simpleBean2.isRunning()); assertEquals(6, startedBeans.size()); assertEquals(-3, getPhase(startedBeans.get(2))); assertEquals(0, getPhase(startedBeans.get(3))); assertEquals(0, getPhase(startedBeans.get(4))); assertEquals(5, getPhase(startedBeans.get(5))); }
@Test public void smartLifecycleGroupShutdown() throws Exception { Assume.group(TestGroup.PERFORMANCE); CopyOnWriteArrayList<Lifecycle> stoppedBeans = new CopyOnWriteArrayList<Lifecycle>(); TestSmartLifecycleBean bean1 = TestSmartLifecycleBean.forShutdownTests(1, 300, stoppedBeans); TestSmartLifecycleBean bean2 = TestSmartLifecycleBean.forShutdownTests(3, 100, stoppedBeans); TestSmartLifecycleBean bean3 = TestSmartLifecycleBean.forShutdownTests(1, 600, stoppedBeans); TestSmartLifecycleBean bean4 = TestSmartLifecycleBean.forShutdownTests(2, 400, stoppedBeans); TestSmartLifecycleBean bean5 = TestSmartLifecycleBean.forShutdownTests(2, 700, stoppedBeans); TestSmartLifecycleBean bean6 = TestSmartLifecycleBean.forShutdownTests(Integer.MAX_VALUE, 200, stoppedBeans); TestSmartLifecycleBean bean7 = TestSmartLifecycleBean.forShutdownTests(3, 200, stoppedBeans); StaticApplicationContext context = new StaticApplicationContext(); context.getBeanFactory().registerSingleton("bean1", bean1); context.getBeanFactory().registerSingleton("bean2", bean2); context.getBeanFactory().registerSingleton("bean3", bean3); context.getBeanFactory().registerSingleton("bean4", bean4); context.getBeanFactory().registerSingleton("bean5", bean5); context.getBeanFactory().registerSingleton("bean6", bean6); context.getBeanFactory().registerSingleton("bean7", bean7); context.refresh(); context.stop(); assertEquals(Integer.MAX_VALUE, getPhase(stoppedBeans.get(0))); assertEquals(3, getPhase(stoppedBeans.get(1))); assertEquals(3, getPhase(stoppedBeans.get(2))); assertEquals(2, getPhase(stoppedBeans.get(3))); assertEquals(2, getPhase(stoppedBeans.get(4))); assertEquals(1, getPhase(stoppedBeans.get(5))); assertEquals(1, getPhase(stoppedBeans.get(6))); }