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

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

Introduction

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

Prototype

public EventBus(SubscriberExceptionHandler exceptionHandler) 

Source Link

Document

Creates a new EventBus with the given SubscriberExceptionHandler .

Usage

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

/**
 * @param args//  ww w.  j a v  a2  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.// w  w w .  ja  va2s. c  om
 * @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  . j  av  a  2s.c  o  m
 * @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.asoem.greyfish.cli.GreyfishCLIApplication.java

public static void main(final String[] args) {

    final Optional<String> commitHash = getCommitHash(GreyfishCLIApplication.class);
    if (commitHash.isPresent()) {
        logger.debug("Git Commit Hash for current Jar: %s", commitHash.get());
    }//  w ww  .ja  v a2s  . co  m

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            try {
                closer.close();
            } catch (IOException e) {
                logger.warn("Exception while closing resources", e);
            }
        }
    });

    try {
        final OptionSet optionSet = optionParser.parse(args);

        if (optionSet.has(helpOptionSpec)) {
            printHelp();
            System.exit(0);
        }

        final Module commandLineModule = createCommandLineModule(optionSet);
        final RandomGenerator randomGenerator = RandomGenerators
                .threadLocalGenerator(new Supplier<RandomGenerator>() {
                    @Override
                    public RandomGenerator get() {
                        return new Well19937c();
                    }
                });
        final EventBus eventBus = new EventBus(new SubscriberExceptionHandler() {
            @Override
            public void handleException(final Throwable exception, final SubscriberExceptionContext context) {
                context.getEventBus()
                        .post(new AssertionError("The EventBus could not dispatch event: "
                                + context.getSubscriber() + " to " + context.getSubscriberMethod(),
                                exception.getCause()));
            }
        });
        final Module coreModule = new CoreModule(randomGenerator, eventBus);

        final Injector injector = Guice.createInjector(coreModule, commandLineModule);

        final ExperimentExecutionService experimentExecutionService = injector
                .getInstance(ExperimentExecutionService.class);

        if (!optionSet.has(quietOptionSpec)) {
            final ExperimentMonitorService monitorService = new ExperimentMonitorService(System.out, eventBus);

            monitorService.addListener(new Service.Listener() {
                @Override
                public void starting() {
                }

                @Override
                public void running() {
                }

                @Override
                public void stopping(final Service.State from) {
                }

                @Override
                public void terminated(final Service.State from) {
                }

                @Override
                public void failed(final Service.State from, final Throwable failure) {
                    logger.error("Monitor service failed", failure);
                }
            }, MoreExecutors.sameThreadExecutor());

            experimentExecutionService.addListener(new MonitorServiceController(monitorService),
                    MoreExecutors.sameThreadExecutor());
        }

        // start getSimulation
        experimentExecutionService.startAsync();

        // stop getSimulation on shutdown request (^C)
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (experimentExecutionService.isRunning()) {
                    experimentExecutionService.stopAsync().awaitTerminated();
                }
            }
        });

        try {
            experimentExecutionService.awaitTerminated();
        } catch (IllegalStateException e) {
            exitWithErrorMessage("Simulation execution failed", e);
        }
    } catch (OptionException e) {
        exitWithErrorMessage("Failed parsing options: ", e, true);
    } catch (Throwable e) {
        exitWithErrorMessage(String.format(
                "Exception during simulation execution: %s\n" + "Check log file for a stack trace.",
                e.getCause() != null ? e.getCause().getMessage() : e.getMessage()), e);
    }

    System.exit(0);
}

From source file:org.dspace.event.Channel.java

public void init(String name) {
    this.name = name;
    this.bus = new EventBus(name);
}

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:org.killbill.commons.jdbi.notification.DatabaseTransactionNotificationApi.java

public DatabaseTransactionNotificationApi() {
    this.eventBus = new EventBus(this.getClass().getName());
}

From source file:org.muhia.app.psi.portal.eventbus.SyncEventBusService.java

public SyncEventBusService() {
    //        eventBus = new AsyncEventBus("ui-events", Executors.newCachedThreadPool());
    eventBus = new EventBus("ui-events");
}

From source file:org.apache.ambari.server.events.publishers.AmbariEventPublisher.java

/**
 * Constructor.
 */
public AmbariEventPublisher() {
    m_eventBus = new EventBus("ambari-event-bus");
}

From source file:com.mycollab.eventmanager.EventBusFactoryImpl.java

@Override
public EventBus getInstanceInSession() {
    EventBus eventBus = (EventBus) MyCollabSession.getCurrentUIVariable(EVENT_BUS_VAL);
    LOG.debug("Event bus {}", eventBus);
    if (eventBus == null) {
        eventBus = new EventBus(new SubscriberEventBusExceptionHandler());
        MyCollabSession.putCurrentUIVariable(EVENT_BUS_VAL, eventBus);
        LOG.debug("Create new event bus {}", eventBus);
    }//ww  w  . j a va  2s  .co  m
    return eventBus;
}