Example usage for org.springframework.context ApplicationListener ApplicationListener

List of usage examples for org.springframework.context ApplicationListener ApplicationListener

Introduction

In this page you can find the example usage for org.springframework.context ApplicationListener ApplicationListener.

Prototype

ApplicationListener

Source Link

Usage

From source file:com.tcloud.bee.key.server.jetty.SpringJettyServer.java

/**
 * @param args/*  w ww . j  av  a2  s . c om*/
 */
public static void main(String[] args) {

    logger.info("Start Spring Jetty Server.....");

    try {

        @SuppressWarnings("resource")
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        /*
         * One problem with SpringMVC is it creates its own application
         * context, and so it can end up failing but our application will
         * keep running.
         * 
         * To detect the case where the SpringMVC's web application context
         * fails we'll listen for ContextRefreshEvents and set a flag when
         * we see one.
         */
        applicationContext.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {
            @Override
            public void onApplicationEvent(ContextRefreshedEvent event) {
                ApplicationContext ctx = event.getApplicationContext();
                if (ctx instanceof AnnotationConfigWebApplicationContext) {
                    webApplicationContextInitialized = true;
                }
            }
        });

        logger.info("Start register JettyConfiguration.....");
        applicationContext.registerShutdownHook();
        applicationContext.register(RootConfiguration.class);
        applicationContext.refresh();

        if (!webApplicationContextInitialized) {
            logger.error("Web application context not initialized. Exiting.");
            System.exit(1);
        }

        logger.info("Running.");
    } catch (Exception e) {
        logger.error("Error starting application", e);
        System.exit(1);
    }
}

From source file:ca.unx.template.Main.java

public static void main(String[] args) throws Exception {

    final Logger logger = LoggerFactory.getLogger("main");

    try {/* www  .j a v a  2  s  . c o m*/
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        /*
         * One problem with SpringMVC is it creates its own application
         * context, and so it can end up failing but our application will
         * keep running.
         * 
         * To detect the case where the SpringMVC's web application context
         * fails we'll listen for ContextRefreshEvents and set a flag when
         * we see the web application context refresh.
         */
        applicationContext.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {
            @Override
            public void onApplicationEvent(ContextRefreshedEvent event) {
                ApplicationContext ctx = event.getApplicationContext();
                if (ctx instanceof GenericWebApplicationContext) {
                    webApplicationContextInitialized = true;
                }
            }
        });

        applicationContext.registerShutdownHook();
        applicationContext.register(RootConfiguration.class);
        applicationContext.refresh();

        if (!webApplicationContextInitialized) {
            logger.error("Failed to initialize web application.  Exiting.");
            System.exit(1);
        }

        logger.info("Running.");
    } catch (Exception e) {
        logger.error("Error starting application", e);
        System.exit(1);
    }
}

From source file:org.springsource.sinspctr.AdminMain.java

/**
* Launch stream server with the given home and transport
 * @throws IOException /*from w w w .ja  v  a  2  s .co  m*/
*/
static InspctrServer launchStreamServer() throws IOException {
    XmlWebApplicationContext context = new XmlWebApplicationContext();
    context.setConfigLocation("classpath:" + CONFIG_ROOT + "sinspctr-server.xml");

    // Not making StreamServer a spring bean eases move to .war file if
    // needed
    final InspctrServer server = new InspctrServer(context, DEFAULT_PORT);
    server.afterPropertiesSet();
    server.start();
    StringBuilder runtimeInfo = new StringBuilder(
            String.format("Running in Local Mode on port: %s ", server.getPort()));
    System.out.println(BannerUtils.displayBanner(null, runtimeInfo.toString()));
    context.addApplicationListener(new ApplicationListener<ContextClosedEvent>() {
        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
            server.stop();
        }
    });
    context.registerShutdownHook();
    return server;
}

From source file:batch.configuration.BatchConfiguration.java

@Bean
public ApplicationListener listener() {
    return new ApplicationListener() {
        @Override/*from  w  w  w  .j  ava 2 s .  c  o m*/
        public void onApplicationEvent(ApplicationEvent applicationEvent) {
            if (applicationEvent instanceof ContextClosedEvent) {
                System.out.println("Closing!!!");
            }
        }
    };
}

From source file:org.solmix.runtime.support.spring.SpringContainer.java

/**
 * {@inheritDoc}/*w w  w. j av a  2s  .c  om*/
 * 
 * @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
 */
@SuppressWarnings("rawtypes")
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    this.applicationContext = (AbstractApplicationContext) applicationContext;
    ApplicationListener listener = new ApplicationListener() {

        @Override
        public void onApplicationEvent(ApplicationEvent event) {
            SpringContainer.this.onApplicationEvent(event);
        }
    };
    this.applicationContext.addApplicationListener(listener);
    ApplicationContext ac = applicationContext.getParent();
    while (ac != null) {
        if (ac instanceof AbstractApplicationContext) {
            ((AbstractApplicationContext) ac).addApplicationListener(listener);
        }
        ac = ac.getParent();
    }
    setExtension(applicationContext.getClassLoader(), ClassLoader.class);
    setExtension(new SpringConfigurer(applicationContext), BeanConfigurer.class);
    //
    setExtension(applicationContext, ApplicationContext.class);
    //        setBean(new SpringConfigureUnitManager(), ConfigureUnitManager.class);
    ResourceManager m = getExtension(ResourceManager.class);
    m.addResourceResolver(new SpringResourceResolver(applicationContext));
    //at last add the spring bean provider.
    ConfiguredBeanProvider provider = getExtension(ConfiguredBeanProvider.class);
    if (!(provider instanceof SpringBeanProvider)) {
        setExtension(new SpringBeanProvider(applicationContext, this), ConfiguredBeanProvider.class);
    }
    if (getStatus() != ContainerStatus.CREATED) {
        initialize();
    }
}

From source file:xolpoc.plugins.StreamPlugin.java

@Override
public void preProcessModule(final Module module) {
    Properties properties = new Properties();
    properties.setProperty(XD_STREAM_NAME_KEY, module.getDescriptor().getGroup());
    module.addProperties(properties);//w  ww.  ja  va  2 s. c  om
    if (module.getType() == ModuleType.sink) {
        module.addListener(new ApplicationListener<ApplicationPreparedEvent>() {

            @Override
            public void onApplicationEvent(ApplicationPreparedEvent event) {
                Properties producerProperties = extractConsumerProducerProperties(module)[1];
                MessageBusAwareRouterBeanPostProcessor bpp = new MessageBusAwareRouterBeanPostProcessor(
                        messageBus, producerProperties);
                bpp.setBeanFactory(event.getApplicationContext().getBeanFactory());
                event.getApplicationContext().getBeanFactory().addBeanPostProcessor(bpp);
            }

        });
    }
}

From source file:com.obergner.hzserver.Main.java

void start() throws Exception {
    enableHangupSupport();//from   w ww  . ja  va2s .  c  om

    this.serverInfo.logBootStart();

    final GenericApplicationContext ctx = new GenericApplicationContext();
    final XmlBeanDefinitionReader xmlReader = new XmlBeanDefinitionReader(ctx);
    xmlReader.loadBeanDefinitions("classpath:META-INF/spring/hz-server-main-context.xml",
            "classpath*:META-INF/spring/hz-cache-context.xml");
    ctx.registerShutdownHook();
    ctx.addApplicationListener(new ApplicationListener<ContextRefreshedEvent>() {

        @Override
        public void onApplicationEvent(final ContextRefreshedEvent event) {
            Main.this.serverInfo.logBootCompleted();

        }
    });
    ctx.addApplicationListener(new ApplicationListener<ContextStoppedEvent>() {

        @Override
        public void onApplicationEvent(final ContextStoppedEvent event) {
            Main.this.serverInfo.logShutdownCompleted();
        }
    });
    ctx.refresh();
}

From source file:com.amazonaws.serverless.proxy.spring.LambdaSpringApplicationInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    applicationContext.setServletContext(servletContext);

    dispatcherConfig = new DefaultDispatcherConfig(servletContext);
    applicationContext.setServletConfig(dispatcherConfig);

    // Configure the listener for the request handled events. All we do here is release the latch
    applicationContext.addApplicationListener(new ApplicationListener<ServletRequestHandledEvent>() {
        @Override//from w w w .  j  av a  2 s .  co m
        public void onApplicationEvent(ServletRequestHandledEvent servletRequestHandledEvent) {
            try {
                currentResponse.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
                throw new RuntimeException("Could not flush response buffer", e);
            }
        }
    });

    // Manage the lifecycle of the root application context
    this.addListener(new ContextLoaderListener(applicationContext));

    // Register and map the dispatcher servlet
    dispatcherServlet = new DispatcherServlet(applicationContext);

    if (refreshContext) {
        dispatcherServlet.refresh();
    }

    dispatcherServlet.onApplicationEvent(new ContextRefreshedEvent(applicationContext));
    dispatcherServlet.init(dispatcherConfig);

    notifyStartListeners(servletContext);
}

From source file:org.jasig.portlet.calendar.util.MockWebApplicationContextLoader.java

public ApplicationContext loadContext(String... locations) throws Exception {
    // Establish the portlet context and config based on the test class's MockWebApplication annotation.
    MockServletContext mockServletContext = new MockServletContext(configuration.webapp(),
            new FileSystemResourceLoader());
    final ServletWrappingPortletContext portletContext = new ServletWrappingPortletContext(mockServletContext);
    final MockPortletConfig portletConfig = new MockPortletConfig(portletContext, configuration.name());

    // Create a WebApplicationContext and initialize it with the xml and portlet configuration.
    final XmlPortletApplicationContext portletApplicationContext = new XmlPortletApplicationContext();
    portletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
            portletApplicationContext);/*from  w w w  .jav  a2 s . c  om*/
    portletApplicationContext.setPortletConfig(portletConfig);
    portletApplicationContext.setConfigLocations(locations);

    // Create a DispatcherPortlet that uses the previously established WebApplicationContext.
    final DispatcherPortlet dispatcherPortlet = new DispatcherPortlet() {
        @Override
        protected WebApplicationContext createPortletApplicationContext(ApplicationContext parent) {
            return portletApplicationContext;
        }
    };

    final ViewResolver viewResolver = new MockViewResolver();

    // Add the DispatcherPortlet (and anything else you want) to the context.
    // Note: this doesn't happen until refresh is called below.
    portletApplicationContext.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
        public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
            beanFactory.registerResolvableDependency(DispatcherPortlet.class, dispatcherPortlet);
            // Register any other beans here, including a ViewResolver if you are using JSPs.
            beanFactory.registerResolvableDependency(ViewResolver.class, viewResolver);
        }
    });

    // Have the context notify the portlet every time it is refreshed.
    portletApplicationContext.addApplicationListener(new SourceFilteringListener(portletApplicationContext,
            new ApplicationListener<ContextRefreshedEvent>() {
                public void onApplicationEvent(ContextRefreshedEvent event) {
                    dispatcherPortlet.onApplicationEvent(event);
                }
            }));

    // Prepare the context.
    portletApplicationContext.refresh();
    portletApplicationContext.registerShutdownHook();

    // Initialize the portlet.
    dispatcherPortlet.setContextConfigLocation("");
    dispatcherPortlet.init(portletConfig);

    return portletApplicationContext;
}

From source file:burstcoin.jminer.JMinerCommandLine.java

private void initApplicationListeners() {
    context.addApplicationListener(new ApplicationListener<RoundFinishedEvent>() {
        @Override//from w ww. ja  v  a 2s.c  om
        public void onApplicationEvent(RoundFinishedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getRoundTime() / 1000;
            long ms = event.getRoundTime() % 1000;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("FINISH block '" + event.getBlockNumber() + "', " + "best deadline '" + bestDeadline
                    + "', " + "round time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStoppedEvent>() {
        @Override
        public void onApplicationEvent(RoundStoppedEvent event) {
            previousRemainingCapacity = 0;
            previousElapsedTime = 0;

            long s = event.getElapsedTime() / 1000;
            long ms = event.getElapsedTime() % 1000;

            BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
            BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
            BigDecimal progress = factor
                    .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
            int percentage = (int) Math.ceil(progress.doubleValue() * 100);
            percentage = percentage > 100 ? 100 : percentage;

            String bestDeadline = Long.MAX_VALUE == event.getBestCommittedDeadline() ? "N/A"
                    : String.valueOf(event.getBestCommittedDeadline());
            LOG.info("STOP block '" + event.getBlockNumber() + "', " + String.valueOf(percentage) + "% done, "
                    + "best deadline '" + bestDeadline + "', " + "elapsed time '" + s + "s " + ms + "ms'");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkLastWinnerEvent>() {
        @Override
        public void onApplicationEvent(NetworkLastWinnerEvent event) {
            if (blockNumber - 1 == event.getLastBlockNumber()) {
                LOG.info(
                        "      winner block '" + event.getLastBlockNumber() + "', '" + event.getWinner() + "'");
            } else {
                LOG.error("Error: NetworkLastWinnerEvent for block: " + event.getLastBlockNumber()
                        + " is outdated!");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkStateChangeEvent>() {
        @Override
        public void onApplicationEvent(NetworkStateChangeEvent event) {
            blockNumber = event.getBlockNumber();
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundStartedEvent>() {
        @Override
        public void onApplicationEvent(RoundStartedEvent event) {
            progressLogStep = NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            LOG.info("-------------------------------------------------------");
            LOG.info("START block '" + event.getBlockNumber() + "', " + "scoopNumber '" + event.getScoopNumber()
                    + "', " + "capacity '" + event.getCapacity() / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR
                    + " " + G_UNIT + "'");
            String target = event.getTargetDeadline() == Long.MAX_VALUE ? "N/A"
                    : String.valueOf(event.getTargetDeadline());
            LOG.info("      targetDeadline '" + target + "', " + "baseTarget '"
                    + String.valueOf(event.getBaseTarget()) + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderProgressChangedEvent>() {
        @Override
        public void onApplicationEvent(ReaderProgressChangedEvent event) {
            long logStepCapacity = event.getCapacity() / NUMBER_OF_PROGRESS_LOGS_PER_ROUND;

            if (event.getRemainingCapacity() < logStepCapacity * progressLogStep
                    || event.getRemainingCapacity() == 0) {
                progressLogStep--;

                // trigger garbage collection on every progress step
                System.gc();

                BigDecimal totalCapacity = new BigDecimal(event.getCapacity());
                BigDecimal factor = BigDecimal.ONE.divide(totalCapacity, MathContext.DECIMAL32);
                BigDecimal progress = factor
                        .multiply(new BigDecimal(event.getCapacity() - event.getRemainingCapacity()));
                int percentage = (int) Math.ceil(progress.doubleValue() * 100);
                percentage = percentage > 100 ? 100 : percentage;

                // calculate capacity
                long effMBPerSec = 0;
                if (previousRemainingCapacity > 0) {
                    long effDoneBytes = previousRemainingCapacity - event.getRemainingCapacity();

                    // calculate current reading speed (since last info)
                    long effBytesPerMs = (effDoneBytes / 4096) / (event.getElapsedTime() - previousElapsedTime);
                    effMBPerSec = (effBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;
                }

                // calculate capacity
                long doneBytes = event.getCapacity() - event.getRemainingCapacity();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                // calculate reading speed (average)
                long averageBytesPerMs = (doneBytes / 4096) / event.getElapsedTime();
                long averageMBPerSec = (averageBytesPerMs * 1000) / SIZE_DIVISOR / SIZE_DIVISOR;

                previousRemainingCapacity = event.getRemainingCapacity();
                previousElapsedTime = event.getElapsedTime();

                LOG.info(String.valueOf(percentage) + "% done (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + "), avg.'" + averageMBPerSec + " " + M_UNIT + "/s'"
                        + (effMBPerSec > 0 ? ", eff.'" + effMBPerSec + " " + M_UNIT + "/s'" : ""));
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultEvent event) {
            LOG.info("dl '" + event.getCalculatedDeadline() + "' send ("
                    + (event.isPoolMining() ? "pool" : "solo") + ")");
        }
    });

    context.addApplicationListener(new ApplicationListener<RoundSingleResultSkippedEvent>() {
        @Override
        public void onApplicationEvent(RoundSingleResultSkippedEvent event) {
            LOG.info(
                    "dl '" + event.getCalculatedDeadline() + "' > '" + event.getTargetDeadline() + "' skipped");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultConfirmedEvent event) {
            LOG.info("dl '" + event.getDeadline() + "' confirmed!  [ " + getDeadlineTime(event.getDeadline())
                    + " ]");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkDevResultConfirmedEvent>() {
        @Override
        public void onApplicationEvent(NetworkDevResultConfirmedEvent event) {
            LOG.info("devPool response '" + event.getResponse() + "', block '" + event.getBlockNumber() + "'");
            for (DevPoolResult devPoolResult : event.getDevPoolResults()) {
                LOG.info("dl '" + devPoolResult.getCalculatedDeadline() + "' successful committed!  [ "
                        + getDeadlineTime(devPoolResult.getCalculatedDeadline()) + " ]");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkResultErrorEvent>() {
        @Override
        public void onApplicationEvent(NetworkResultErrorEvent event) {
            LOG.info("strange dl result '" + event.getStrangeDeadline() + "', calculated '"
                    + event.getCalculatedDeadline() + "' " + "block '" + event.getBlockNumber() + "' nonce '"
                    + event.getNonce() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderCorruptFileEvent>() {
        @Override
        public void onApplicationEvent(ReaderCorruptFileEvent event) {
            LOG.info("strange dl source '" + event.getFilePath() + "' (try replotting!?)");
            LOG.info("strange dl file chunks '" + event.getNumberOfChunks() + "', " + "parts per chunk '"
                    + event.getNumberOfParts() + "', " + "block '" + event.getBlockNumber() + "'");
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveFinishEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveFinishEvent event) {
            if (blockNumber == event.getBlockNumber()) {
                // calculate capacity
                long doneBytes = event.getSize();
                long doneTB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR;
                long doneGB = doneBytes / SIZE_DIVISOR / SIZE_DIVISOR / SIZE_DIVISOR % SIZE_DIVISOR;

                long s = event.getTime() / 1000;
                long ms = event.getTime() % 1000;

                LOG.info("read '" + event.getDirectory() + "' (" + doneTB + T_UNIT + " " + doneGB + G_UNIT
                        + ") in '" + s + "s " + ms + "ms'");
            }
        }
    });

    context.addApplicationListener(new ApplicationListener<ReaderDriveInterruptedEvent>() {
        @Override
        public void onApplicationEvent(ReaderDriveInterruptedEvent event) {
            LOG.info("stopped '" + event.getDirectory() + "' for block '" + event.getBlockNumber() + "'.");
        }
    });

    context.addApplicationListener(new ApplicationListener<NetworkPoolInfoEvent>() {
        @Override
        public void onApplicationEvent(NetworkPoolInfoEvent event) {
            String value = event.getPoolBalanceNQT();
            String amount = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            value = event.getPoolForgedBalanceNQT();
            String totalForget = value.length() > 8 ? value.substring(0, value.length() - 8) : value;
            LOG.info("-------------------------------------------------------");
            LOG.info("POOL account '" + event.getPoolAccountRS() + "', assigned miners '"
                    + event.getPoolNumberOfMiningAccounts() + "'");
            LOG.info("     balance '" + amount + " BURST', total mined '" + totalForget + " BURST'");
        }
    });
}