@Override public void onApplicationEvent(ApplicationEvent event) { if (event.getClass() == ContextRefreshedEvent.class) { logger.info("register url: " + infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(Registry.class).doRegister(infoHolder.taskProtocolUrl()); try { extensionLoader.loadExtension(ProtocolFactory.class).server().openServer(infoHolder.taskProtocolUrl()); } catch (Exception e) { throw new RuntimeException(e); } sandbox.configSandbox(); } else if (event.getClass() == ContextClosedEvent.class) { logger.info("unregister url: " + infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(Registry.class).unRegister(infoHolder.taskProtocolUrl()); extensionLoader.loadExtension(ProtocolFactory.class).server().close(); } }
public void testBootstrapAndShutdown() throws Exception { // now bring up the bootstrap ApplicationContext ctx = new ClassPathXmlApplicationContext(APP_CONTEXT_XML); // the folder should be gone assertFalse("Folder was not deleted by bootstrap", dir.exists()); // now create the folder again dir.mkdir(); assertTrue("Directory not created", dir.exists()); // announce that the context is closing ctx.publishEvent(new ContextClosedEvent(ctx)); // the folder should be gone assertFalse("Folder was not deleted by shutdown", dir.exists()); }
public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ContextClosedEvent) { enabled = false; return; } if (event instanceof ContextRefreshedEvent) { initialized = true; return; } if (event instanceof OsgiServiceDependencyWaitStartingEvent) { if (enabled) { OsgiServiceDependencyWaitStartingEvent evt = (OsgiServiceDependencyWaitStartingEvent) event; String[] filter = new String[] { evt.getServiceDependency().getServiceFilter().toString() }; BlueprintEvent waitingEvent = new BlueprintEvent(BlueprintEvent.WAITING, bundleContext.getBundle(), extenderBundle, filter); listenerManager.blueprintEvent(waitingEvent); dispatcher.waiting(waitingEvent); } return; } }
@Override public void onApplicationEvent(ContextClosedEvent event) { for (String eventClassName : getSpringContext().getBeanNameByType(ContextEvent.class)) { ContextEvent eventClass = (ContextEvent) getSpringContext().getBean(eventClassName); if (eventClass == null) { continue; } eventClass.stop(); LOGGER.trace("%s stopped", eventClassName); } getTaskExecutor().setWaitForTasksToCompleteOnShutdown(true); getTaskExecutor().setAwaitTerminationSeconds(10); getTaskExecutor().shutdown(); }
@Override public void onApplicationEvent(ContextClosedEvent event) { this.connector.pause(); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { try { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; threadPoolExecutor.shutdown(); if (!threadPoolExecutor.awaitTermination(30, TimeUnit.SECONDS)) { log.warn("Tomcat thread pool did not shut down gracefully within " + "30 seconds. Proceeding with forceful shutdown"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } }
@Override public void onApplicationEvent(ContextClosedEvent event) { log.info("Starting graceful shutdown of Tomcat"); if (this.connector != null) { this.connector.pause(); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { try { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor; threadPoolExecutor.shutdown(); if (!threadPoolExecutor.awaitTermination(20, TimeUnit.SECONDS)) { log.warn("Tomcat thread pool did not shut down gracefully within " + "20 seconds. Proceeding with forceful shutdown"); } else { log.info("Thread pool has closed"); } } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } }
/** * Metacat service shutdown. * * @param event Event when the context is shutting down */ @EventListener public void stop(final ContextClosedEvent event) { log.info("Metacat application is stopped per {}. Stopping services.", event); try { this.pluginsLoaded.set(false); this.connectorManager.stop(); this.catalogsLoaded.set(false); this.threadServiceManager.stop(); this.metacatThriftService.stop(); this.thriftStarted.set(false); } catch (final Exception e) { // Just log it since we're shutting down anyway shouldn't matter to propagate it log.error("Unable to properly shutdown services due to {}", e.getMessage(), e); } log.info("Finished stopping services."); }
@Override public void onApplicationEvent(ApplicationEvent applicationEvent) { // 容器启动完成后装载之前已添加的实例 if (applicationEvent instanceof ContextRefreshedEvent) { LOGGER.info("spring container start all persisted cangoInstance!"); CangoInstances condition = new CangoInstances(); condition.setState(State.START.getCode()); List<CangoInstances> instancesList = cangoInstancesService.findByCondition(condition); int countMysqlInstance = 0; int countOracleInstance = 0; if (!CollectionUtils.isEmpty(instancesList)) { Map<String, Integer> countMap = internalStartCanalAndYuGong(instancesList, null); countMysqlInstance = countMap.get(CANAL_INSTANCE); countOracleInstance = countMap.get(ORACLE_INSTANCE); } LOGGER.info("spring container start all persisted cangoInstance successfully, count MysqlInstance number {}, OracleInstance number {}!", countMysqlInstance, countOracleInstance); } if (applicationEvent instanceof ContextClosedEvent) { shutdown(); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof ApplicationStartedEvent) { onApplicationStartedEvent((ApplicationStartedEvent) event); } else if (event instanceof ApplicationEnvironmentPreparedEvent) { onApplicationEnvironmentPreparedEvent( (ApplicationEnvironmentPreparedEvent) event); } else if (event instanceof ApplicationPreparedEvent) { onApplicationPreparedEvent((ApplicationPreparedEvent) event); } else if (event instanceof ContextClosedEvent && ((ContextClosedEvent) event) .getApplicationContext().getParent() == null) { onContextClosedEvent(); } }
@Test public void closingChildContextDoesNotCleanUpLoggingSystem() { System.setProperty(LoggingSystem.SYSTEM_PROPERTY, TestCleanupLoggingSystem.class.getName()); this.initializer.onApplicationEvent( new ApplicationStartedEvent(this.springApplication, new String[0])); TestCleanupLoggingSystem loggingSystem = (TestCleanupLoggingSystem) ReflectionTestUtils .getField(this.initializer, "loggingSystem"); assertThat(loggingSystem.cleanedUp).isFalse(); GenericApplicationContext childContext = new GenericApplicationContext(); childContext.setParent(this.context); this.initializer.onApplicationEvent(new ContextClosedEvent(childContext)); assertThat(loggingSystem.cleanedUp).isFalse(); this.initializer.onApplicationEvent(new ContextClosedEvent(this.context)); assertThat(loggingSystem.cleanedUp).isTrue(); childContext.close(); }
/** * Listens ContextClosedEvent and Closes all async http connections */ @Bean ApplicationListener<?> applicationListener() { return new SmartApplicationListener() { @Override public int getOrder() { return 0; } @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ContextClosedEvent.class.isAssignableFrom(eventType); } @Override public boolean supportsSourceType(Class<?> sourceType) { return true; } @Override public void onApplicationEvent(ApplicationEvent event) { Closeables.close(proxyInstance); } }; }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { // register a context close handler if (applicationContext instanceof ConfigurableApplicationContext) { ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext; context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() { @Override public void onApplicationEvent(ContextClosedEvent e) { LOG.info("Context '" + e.getApplicationContext().getDisplayName() + "' closed, removing registered ApplicationThreadLocals"); if (!ApplicationThreadLocal.clear()) { LOG.error("Error(s) occurred removing registered ApplicationThreadLocals"); } } }); } }
@Override public void onApplicationEvent(ApplicationContextEvent event) { if (event instanceof ContextRefreshedEvent && !servicePublisherStarted) { // Application initialization complete. Export astrix-services. if (isServer()) { this.astrixContext.startServicePublisher(); } servicePublisherStarted = true; } else if (event instanceof ContextClosedEvent || event instanceof ContextStoppedEvent) { /* * What's the difference between the "stopped" and "closed" event? In our embedded * integration tests we only receive ContextClosedEvent */ destroyAstrixContext(); } }
public void onApplicationEvent(ApplicationEvent event) { if(!doNothing) { if (event instanceof ContextClosedEvent) { m_executorService.shutdown(); try { m_executorService.awaitTermination(5, TimeUnit.SECONDS); } catch (InterruptedException e) { String error = CommonUtils.redirectPrintStackTraceToString(e); if (LOGGER.isErrorEnabled()) LOGGER.error( "Waiting for shutdown, got InterruptedException: " + error); } } else { BeanFactoryUpdater updater = new BeanFactoryUpdater(); updater.setApplicationEvent(event); // Submit to the Executor Service to execute this task. m_executorService.submit(updater); } } }
@Override public void onApplicationEvent(ContextClosedEvent event) { if (!locks.isEmpty()) { LOGGER.info("Application is being shut down but {} locks remain, releasing them...", locks.size()); final Collection<DistributedLock> locksToRelease = new ArrayList<>(locks.values()); for (DistributedLock lock : locksToRelease) { LOGGER.info("Releasing lock '{}'", lock.getKey()); try { lock.unlock(); } catch (Exception e) { LOGGER.warn("Unable to release lock '{}' due to exception.", e); } } LOGGER.info("Locks released."); } else { LOGGER.info("No lock to release on shutdown."); } }
@Test public void shouldReleaseOnClose() throws Exception { // given final LockFactory delegate = mock(LockFactory.class); final DistributedLock mock1 = mock(DistributedLock.class); when(mock1.getKey()).thenReturn("1234"); final DistributedLock mock2 = mock(DistributedLock.class); when(mock2.getKey()).thenReturn("5678"); when(delegate.getLock(eq("1234"))).thenReturn(mock1); when(delegate.getLock(eq("5678"))).thenReturn(mock2); doAnswer(invocation -> { throw new RuntimeException(); // on purpose unchecked exception }).when(mock2).unlock(); final DistributedLockWatcher watcher = new DistributedLockWatcher(delegate); watcher.getLock("1234"); watcher.getLock("5678"); // when watcher.onApplicationEvent(new ContextClosedEvent(new AnnotationConfigApplicationContext())); // then verify(mock1, times(1)).unlock(); verify(mock2, times(1)).unlock(); assertEquals(0, watcher.getLocks().size()); }
@Override public void onApplicationEvent(ApplicationEvent event) { //we only want to tell Eureka that the application is up //when the root application context (thisApplicationContext) has //been fully started. we want to ignore any ContextRefreshedEvent //from child application contexts. if (!event.getSource().equals(thisApplicationContext)) { return; } if (event instanceof ContextRefreshedEvent) { if (!disableEureka) { // tell Eureka the server UP which in turn starts the health checks and heartbeat ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.UP); } } else if (event instanceof ContextClosedEvent) { if (!disableEureka) { ApplicationInfoManager.getInstance().setInstanceStatus(InstanceStatus.DOWN); } } }
@SuppressWarnings({"unchecked", "rawtypes"}) @Test public void test_no_register_after_close() { ApplicationRegistrator registrator = mock(ApplicationRegistrator.class); TaskScheduler scheduler = mock(TaskScheduler.class); RegistrationApplicationListener listener = new RegistrationApplicationListener(registrator, scheduler); ScheduledFuture task = mock(ScheduledFuture.class); when(scheduler.scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10)))).thenReturn(task); listener.onApplicationReady(new ApplicationReadyEvent(mock(SpringApplication.class), null, mock(ConfigurableWebApplicationContext.class))); verify(scheduler).scheduleAtFixedRate(isA(Runnable.class), eq(Duration.ofSeconds(10))); listener.onClosedContext(new ContextClosedEvent(mock(WebApplicationContext.class))); verify(task).cancel(true); }
@Test public void startUpWrongVersion() throws Exception { //shutting the service down workerManager.onApplicationEvent(mock(ContextClosedEvent.class)); assertThat(workerManager.isUp()).isFalse(); reset(workerNodeService); reset(engineVersionService); when(engineVersionService.getEngineVersionId()).thenReturn("666"); //starting it again workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class)); Thread.sleep(1000L); // must sleep some time since the start up is being processed in a new thread assertThat(workerManager.isUp()).isFalse(); reset(engineVersionService); when(engineVersionService.getEngineVersionId()).thenReturn("123"); }
@Test public void startUpWithFailure() throws Exception { //shutting the service down workerManager.onApplicationEvent(mock(ContextClosedEvent.class)); assertThat(workerManager.isUp()).isFalse(); reset(workerNodeService); doThrow(new RuntimeException("try 1")) .doThrow(new RuntimeException("try 2")) .doThrow(new RuntimeException("try 3")) .doReturn("1") .when(workerNodeService).up(CREDENTIAL_UUID, "version", "123"); //start again workerManager.onApplicationEvent(mock(ContextRefreshedEvent.class)); Thread.sleep(2000L); // must sleep some time since the start up is being processed in a new thread verify(workerNodeService, times(4)).up(CREDENTIAL_UUID, "version", "123"); assertThat(workerManager.isUp()).isTrue(); }
@Test(timeout = 5000) public void testRunBeforeCtxClosedEvent() throws Exception { ContextRefreshedEvent refreshEvent = mock(ContextRefreshedEvent.class); inBuffer.onApplicationEvent(refreshEvent); ContextClosedEvent event = mock(ContextClosedEvent.class); when(workerManager.isUp()).thenReturn(true); Thread thread = new Thread(inBuffer); thread.start(); verify(workerManager,timeout(1000).atLeastOnce()).getInBufferSize(); inBuffer.onApplicationEvent(event); while(thread.isAlive()){ Thread.sleep(100L); } }
@Override public void onEvent(ContextClosedEvent event) { if(!event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")){ return ; } //只拦截不是/appconsole工程 if(!vlService.getGloableAttribute(ContextConstant.WEB_CONTEXT_NAME).equals( ContextConstant.WEB_PROJECT_NAME)){ try{ StatServer ss = new StatServer(); ss.setIpAddr(IpUtil.getServerIp()); List<StatServer> ss_list = statServerService.findByExample(ss); if(ss_list!=null && ss_list.size()>0){ ss = (StatServer)ss_list.get(0); ss.setShutdownTime(new Date()); statServerService.saveOrUpdate(ss); } }catch(Exception e){ e.printStackTrace(); } } }
@Test public void dumpContainsReportingValues() { InApplicationMonitor inApplicationMonitor = inApplicationMonitorRule.getInApplicationMonitor(); String counterName = "DummyCounter"; String timerName = "DummyTimer"; String stateValueName = "DummyStateValue"; inApplicationMonitor.incrementCounter(counterName); inApplicationMonitor.addTimerMeasurement(timerName, 42L); inApplicationMonitor.registerStateValue(new SimpleStateValueProvider(stateValueName, 42L)); Appmon4jDumper objectUnderTest = new Appmon4jDumper(inApplicationMonitorRule.getInApplicationMonitor()); objectUnderTest.onApplicationEvent(new ContextClosedEvent(new GenericApplicationContext())); assertThat(loggingEvents, Matchers.<LoggingEvent>hasItem( allOf( loggingEventWithMessageContaining(counterName), loggingEventWithMessageContaining(timerName), loggingEventWithMessageContaining(stateValueName)))); }
@Override public void onApplicationEvent(ApplicationContextEvent event) { try { if (event instanceof ContextRefreshedEvent && !isDeployed) { // deploy the process application afterPropertiesSet(); } else if (event instanceof ContextClosedEvent) { // undeploy the process application destroy(); } else { // ignore } } catch (Exception e) { throw new RuntimeException(e); } }
@Override public void onApplicationEvent(ApplicationEvent event) { if (!ContextClosedEvent.class.isInstance(event) || httpServer == null) { return; } httpServer.stop(); httpServer = null; LOGGER.info("Prometheus httpServer stopped."); }
@Test public void testCseApplicationListenerShutdown(@Injectable ContextClosedEvent event, @Mocked RegistryUtils ru) { new Expectations() { { RegistryUtils.destroy(); } }; CseApplicationListener cal = new CseApplicationListener(); cal.onApplicationEvent(event); }
@Override public void onApplicationEvent(ApplicationEvent event) { if (event.getClass() == ContextRefreshedEvent.class) { extensionLoader.loadExtension(Registry.class).subscribe(); extensionLoader.loadExtension(ProtocolFactory.class).client().open(); extensionLoader.loadExtension(Selector.class).start(); logger.info("subscribe:" + extensionLoader.loadExtension(Registry.class).getDirectory().list()); latch.countDown(); } else if (event.getClass() == ContextClosedEvent.class) { logger.info("unSubscribe task"); extensionLoader.loadExtension(Registry.class).unSubscribe(); extensionLoader.loadExtension(ProtocolFactory.class).client().close(); extensionLoader.loadExtension(Selector.class).close(); } }
@Override public void onApplicationEvent(ApplicationContextEvent event) { if (event instanceof ContextClosedEvent || event instanceof ContextStoppedEvent) { List<Entity> everyone = entityRepository.findByXIsNotNullAndYIsNotNullAndZIsNotNull(); GameOutput output = new GameOutput("[red]EmergentMUD is shutting down. Please check back later!"); entityService.sendMessageToListeners(everyone, output); } }
@Override public void onApplicationEvent(ContextClosedEvent contextClosedEvent) { try { log.info("Stopping sagas"); contextClosedEvent.getApplicationContext().getBean(SagaExecutionComponent.class).terminate(); log.info("Stopped sagas successfully."); } catch (Exception ex) { log.error("Stopped sagas failed.", ex); } }
@Override public void multicastEvent(ApplicationEvent event) { if (event instanceof ContextRefreshedEvent && event.getSource() == this.appContext) { this.isApplicationStarted = true; for (ApplicationEvent queuedEvent : this.queuedEvents) { multicastEventInternal(queuedEvent); } this.queuedEvents.clear(); multicastEventInternal(event); } else if (event instanceof ContextClosedEvent && event.getSource() == this.appContext) { this.isApplicationStarted = false; multicastEventInternal(event); } else if (this.isApplicationStarted) { multicastEventInternal(event); } else { this.queuedEvents.add(event); } }
@Override public void publishEvent(ApplicationEvent event) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } ((ApplicationEventMulticaster) getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)).multicastEvent(event); if (!(getParent() == null || event instanceof ContextRefreshedEvent || event instanceof ContextClosedEvent)) { getParent().publishEvent(event); } }
/** * Spring ContextClosedEvent listener to terminate the {@link Executor}. * <b>YOU MUST NOT CALL THIS METHOD!</b> */ @Override public void onApplicationEvent (ContextClosedEvent event) { LOGGER.debug ("Synchronizer: event " + event + " received"); if (event == null) { return; } // Terminates the Executor LOGGER.info ("Synchronization: Executor is terminating"); executor.removeAllSynchronizers(); executor.terminate(); }
/** * Trap applicable Application Events. * * @param applicationEvent Application Event to be processed. */ @Override public void onApplicationEvent(ApplicationEvent applicationEvent) { if (applicationEvent instanceof EmbeddedServletContainerInitializedEvent) { hostPortUsed = ((EmbeddedServletContainerInitializedEvent) applicationEvent). getEmbeddedServletContainer().getPort(); LOGGER.info("onApplicationEvent Fired, System Port Identity:[{}]", hostPortUsed); } else if (applicationEvent instanceof ContextClosedEvent) { LOGGER.info("onApplicationEvent for ContextClosedEvent..."); } }
@EventListener public void onApplicationEvent(ContextClosedEvent event) { logger.info("ContextClosedEvent"); MessageBus bus = ErraiServiceSingleton.getService().getBus(); if (bus != null) { for (ServiceImplementation serviceImplementation : services) { String subject = serviceImplementation.getSubject(); logger.info("Unsubscribing " + subject); bus.unsubscribeAll(subject); } } }
public void onApplicationEvent(ApplicationContextEvent event) { // publish if (event instanceof ContextRefreshedEvent) { registerService(event.getApplicationContext()); } else if (event instanceof ContextClosedEvent) { unregisterService(); } }
@Override public void onApplicationEvent(ContextClosedEvent event) { // shutdown executor pluginPoolExecutor.setWaitForTasksToCompleteOnShutdown(true); pluginPoolExecutor.setAwaitTerminationSeconds(10); pluginPoolExecutor.shutdown(); // dump cache to file pluginDao.dump(); }