Example usage for com.google.common.eventbus EventBus register

List of usage examples for com.google.common.eventbus EventBus register

Introduction

In this page you can find the example usage for com.google.common.eventbus EventBus register.

Prototype

public void register(Object object) 

Source Link

Document

Registers all subscriber methods on object to receive events.

Usage

From source file:tech.codemaster.bat50question.guava.EventBusExample.java

public static void main(String... args) {
    EventBus eventBus = new EventBus();
    eventBus.register(new EventBusChangeRecorder());
    eventBus.post("tomdeng");
}

From source file:org.apache.niolex.common.guava.GuavaEvent.java

/**
 * @param args//from   w  w w . j  av  a  2  s. c o m
 */
public static void main(String[] args) {
    EventBus eventBus = new EventBus("test");

    // somewhere during initialization
    eventBus.register(new EventBusChangeRecorder());

    int i = 30;

    while (i-- > 0) {
        SystemUtil.sleep(200);
        changeCustomer(eventBus);
    }
}

From source file:es.tid.fiware.fiwareconnectors.cygnus.nodes.CygnusApplication.java

/**
 * Main application to be run when this CygnusApplication is invoked. The only differences with the original one
 * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in
 * the command line./* ww  w.ja v a  2 s.co m*/
 * @param args
 */
public static void main(String[] args) {
    try {
        Options options = new Options();

        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a conf file");
        option.setRequired(true);
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload " + "conf file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        option = new Option("p", "mgmt-if-port", true, "the management interface port");
        option.setRequired(false);
        options.addOption(option);

        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);

        File configurationFile = new File(commandLine.getOptionValue('f'));
        String agentName = commandLine.getOptionValue('n');
        boolean reload = !commandLine.hasOption("no-reload-conf");

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("flume-ng agent", options, true);
            return;
        } // if

        int mgmtIfPort = 8081; // default value

        if (commandLine.hasOption('p')) {
            mgmtIfPort = new Integer(commandLine.getOptionValue('p')).intValue();
        } // if

        // the following is to ensure that by default the agent will fail on startup if the file does not exist

        if (!configurationFile.exists()) {
            // if command line invocation, then need to fail fast
            if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) {
                String path = configurationFile.getPath();

                try {
                    path = configurationFile.getCanonicalPath();
                } catch (IOException ex) {
                    logger.error("Failed to read canonical path for file: " + path, ex);
                } // try catch

                throw new ParseException("The specified configuration file does not exist: " + path);
            } // if
        } // if

        List<LifecycleAware> components = Lists.newArrayList();
        CygnusApplication application;

        if (reload) {
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, 30);
            components.add(configurationProvider);
            application = new CygnusApplication(components, mgmtIfPort);
            eventBus.register(application);
        } else {
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication(mgmtIfPort);
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        application.start();

        final CygnusApplication appReference = application;
        Runtime.getRuntime().addShutdownHook(new Thread("agent-shutdown-hook") {
            @Override
            public void run() {
                appReference.stop();
            } // run
        });
    } catch (Exception e) {
        logger.error("A fatal error occurred while running. Exception follows.", e);
    } // try catch
}

From source file:com.telefonica.iot.cygnus.nodes.CygnusApplication.java

/**
 * Main application to be run when this CygnusApplication is invoked. The only differences with the original one
 * are the CygnusApplication is used instead of the Application one, and the Management Interface port option in
 * the command line.//from ww  w .ja v a  2  s. com
 * @param args
 */
public static void main(String[] args) {
    try {
        // Print Cygnus starting trace including version
        LOGGER.info("Starting Cygnus, version " + CommonUtils.getCygnusVersion() + "."
                + CommonUtils.getLastCommit());

        // Define the options to be read
        Options options = new Options();

        Option option = new Option("n", "name", true, "the name of this agent");
        option.setRequired(true);
        options.addOption(option);

        option = new Option("f", "conf-file", true, "specify a conf file");
        option.setRequired(true);
        options.addOption(option);

        option = new Option(null, "no-reload-conf", false, "do not reload conf file if changed");
        options.addOption(option);

        option = new Option("h", "help", false, "display help text");
        options.addOption(option);

        option = new Option("p", "mgmt-if-port", true, "the management interface port");
        option.setRequired(false);
        options.addOption(option);

        option = new Option("g", "gui-port", true, "the GUI port");
        option.setRequired(false);
        options.addOption(option);

        option = new Option("t", "polling-interval", true, "polling interval");
        option.setRequired(false);
        options.addOption(option);

        // Read the options
        CommandLineParser parser = new GnuParser();
        CommandLine commandLine = parser.parse(options, args);

        File configurationFile = new File(commandLine.getOptionValue('f'));
        String agentName = commandLine.getOptionValue('n');
        boolean reload = !commandLine.hasOption("no-reload-conf");

        if (commandLine.hasOption('h')) {
            new HelpFormatter().printHelp("cygnus-flume-ng agent", options, true);
            return;
        } // if

        int apiPort = DEF_MGMT_IF_PORT;

        if (commandLine.hasOption('p')) {
            apiPort = new Integer(commandLine.getOptionValue('p'));
        } // if

        int guiPort = DEF_GUI_PORT;

        if (commandLine.hasOption('g')) {
            guiPort = new Integer(commandLine.getOptionValue('g'));
        } else {
            guiPort = 0; // this disables the GUI for the time being
        } // if else

        int pollingInterval = DEF_POLLING_INTERVAL;

        if (commandLine.hasOption('t')) {
            pollingInterval = new Integer(commandLine.getOptionValue('t'));
        } // if

        // the following is to ensure that by default the agent will fail on startup if the file does not exist
        if (!configurationFile.exists()) {
            // if command line invocation, then need to fail fast
            if (System.getProperty(Constants.SYSPROP_CALLED_FROM_SERVICE) == null) {
                String path = configurationFile.getPath();

                try {
                    path = configurationFile.getCanonicalPath();
                } catch (IOException e) {
                    LOGGER.error(
                            "Failed to read canonical path for file: " + path + ". Details=" + e.getMessage());
                } // try catch

                throw new ParseException("The specified configuration file does not exist: " + path);
            } // if
        } // if

        List<LifecycleAware> components = Lists.newArrayList();
        CygnusApplication application;

        if (reload) {
            LOGGER.debug(
                    "no-reload-conf was not set, thus the configuration file will be polled each 30 seconds");
            EventBus eventBus = new EventBus(agentName + "-event-bus");
            PollingPropertiesFileConfigurationProvider configurationProvider = new PollingPropertiesFileConfigurationProvider(
                    agentName, configurationFile, eventBus, pollingInterval);
            components.add(configurationProvider);
            application = new CygnusApplication(components);
            eventBus.register(application);
        } else {
            LOGGER.debug("no-reload-conf was set, thus the configuration file will only be read this time");
            PropertiesFileConfigurationProvider configurationProvider = new PropertiesFileConfigurationProvider(
                    agentName, configurationFile);
            application = new CygnusApplication();
            application.handleConfigurationEvent(configurationProvider.getConfiguration());
        } // if else

        // use the agent name as component name in the logs through log4j Mapped Diagnostic Context (MDC)
        MDC.put(CommonConstants.LOG4J_COMP, commandLine.getOptionValue('n'));

        // start the Cygnus application
        application.start();

        // wait until the references to Flume components are not null
        try {
            while (sourcesRef == null || channelsRef == null || sinksRef == null) {
                LOGGER.info("Waiting for valid Flume components references...");
                Thread.sleep(1000);
            } // while
        } catch (InterruptedException e) {
            LOGGER.error("There was an error while waiting for Flume components references. Details: "
                    + e.getMessage());
        } // try catch

        // start the Management Interface, passing references to Flume components
        LOGGER.info("Starting a Jetty server listening on port " + apiPort + " (Management Interface)");
        mgmtIfServer = new JettyServer(apiPort, guiPort, new ManagementInterface(configurationFile, sourcesRef,
                channelsRef, sinksRef, apiPort, guiPort));
        mgmtIfServer.start();

        // create a hook "listening" for shutdown interrupts (runtime.exit(int), crtl+c, etc)
        Runtime.getRuntime().addShutdownHook(new AgentShutdownHook("agent-shutdown-hook", supervisorRef));

        // start YAFS
        YAFS yafs = new YAFS();
        yafs.start();
    } catch (IllegalArgumentException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } catch (ParseException e) {
        LOGGER.error("A fatal error occurred while running. Exception follows. Details=" + e.getMessage());
    } // try catch // try catch
}

From source file:org.excalibur.core.events.EventBusFactory.java

public static EventBus createSyncEventBus(String name, DeadEventLoggingHandler deadEventLoggingHandler) {
    EventBus eventBus = new EventBus(name);
    eventBus.register(deadEventLoggingHandler);
    return eventBus;
}

From source file:com.webbfontaine.valuewebb.irms.eventbus.VWEventBus.java

private static void registerDeadEventHandler(EventBus eventBus) {
    eventBus.register(new DeadEventHandler());
}

From source file:org.apache.ambari.server.utils.EventBusSynchronizer.java

/**
 * Register the normal listeners with the replaced synchronous bus.
 *
 * @param injector/*from w  w  w .jav  a 2 s . c  o  m*/
 * @param synchronizedBus
 */
private static void registerAlertListeners(Injector injector, EventBus synchronizedBus) {
    synchronizedBus.register(injector.getInstance(AlertAggregateListener.class));
    synchronizedBus.register(injector.getInstance(AlertReceivedListener.class));
    synchronizedBus.register(injector.getInstance(AlertStateChangedListener.class));
}

From source file:org.apache.ambari.server.utils.EventBusSynchronizer.java

/**
 * Register the normal listeners with the replaced synchronous bus.
 *
 * @param injector/*from w w  w. j  av a  2s. c  om*/
 * @param synchronizedBus
 */
private static void registerAmbariListeners(Injector injector, EventBus synchronizedBus) {
    synchronizedBus.register(injector.getInstance(AlertMaintenanceModeListener.class));
    synchronizedBus.register(injector.getInstance(AlertLifecycleListener.class));
    synchronizedBus.register(injector.getInstance(AlertServiceStateListener.class));
    synchronizedBus.register(injector.getInstance(DistributeRepositoriesActionListener.class));
    synchronizedBus.register(injector.getInstance(HostVersionOutOfSyncListener.class));
}

From source file:convcao.com.agent.test.AcousticReplay.java

/**
 * Just for testing purposes. This method will start broadcasting all messages in the log according to time
 * separations.//w ww.j  ava  2s . com
 * 
 * @param timeMultiplier If 1.0 is used, the separation between messages will be approximately the same as
 *            real-time. If this value is higher, the replay will be done faster in the same proportion.
 */
public static void replay(LsfIndex index, Object listener) {

    EventBus bus = new EventBus();
    bus.register(listener);
    int numMessages = index.getNumberOfMessages();

    int generatorSrcId = index.getMessage(0).getHeader().getInteger("src");

    long localStartTime = System.currentTimeMillis();
    long lastPrint = 0;

    TimeZone tz = TimeZone.getTimeZone("UTC");

    DateFormat dfGMT = DateFormat.getTimeInstance(DateFormat.DEFAULT);
    dfGMT.setTimeZone(tz);

    for (int i = 0; i < numMessages - 1; i++) {
        long curTime = ((long) (1000.0 * (index.timeOf(i) - index.getStartTime()))) + localStartTime;
        long sleep_millis = curTime - System.currentTimeMillis();
        IMCMessage m = index.getMessage(i);
        bus.post(m);
        //transport.sendMessage("127.0.0.1", 6002, m);
        int src = m.getHeader().getInteger("src");

        if (src == generatorSrcId && sleep_millis > 5 && index.timeOf(i + 1) > index.timeOf(i)) {
            try {
                Thread.sleep(sleep_millis);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        long time = 1000 * (long) index.timeOf(i);
        if (src == generatorSrcId && time > lastPrint) {
            System.out.println(dfGMT.format(new Date(time)));
            lastPrint = time;
        }
    }

    bus.unregister(listener);
}

From source file:com.github.elexx.guavajmx.GuavaJmxManagementService.java

public static void register(EventBus bus, String busName) throws JmxRegistrationException {
    try {//ww w . j  av  a 2 s. co m
        EventBusControllerImpl eventBusController = new EventBusControllerImpl();
        bus.register(eventBusController);
        StandardMBean mBean = new StandardMBean(eventBusController, EventBusController.class);
        ManagementFactory.getPlatformMBeanServer().registerMBean(mBean,
                getJmxBeanName(EventBus.class, busName));
    } catch (NotCompliantMBeanException | MalformedObjectNameException | InstanceAlreadyExistsException
            | MBeanRegistrationException e) {
        throw new JmxRegistrationException("Could not register cache with JMX", e);
    }
}