Example usage for java.lang Runnable Runnable

List of usage examples for java.lang Runnable Runnable

Introduction

In this page you can find the example usage for java.lang Runnable Runnable.

Prototype

Runnable

Source Link

Usage

From source file:wh.contrib.RewardOptimizerHttpClient.java

public static void main(String[] args) throws Exception {
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
            .setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
            .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 64 * 1024)
            .setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
            .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
            .setParameter(CoreProtocolPNames.USER_AGENT,
                    "HttpComponents/1.1 (RewardOptimizer - karlthepagan@gmail.com)");

    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);

    BasicHttpProcessor httpproc = new BasicHttpProcessor();
    httpproc.addInterceptor(new RequestContent());
    httpproc.addInterceptor(new RequestTargetHost());
    httpproc.addInterceptor(new RequestConnControl());
    httpproc.addInterceptor(new RequestUserAgent());
    httpproc.addInterceptor(new RequestExpectContinue());

    // We are going to use this object to synchronize between the 
    // I/O event and main threads
    RequestCount requestCount = new RequestCount(1);

    BufferingHttpClientHandler handler = new BufferingHttpClientHandler(httpproc,
            new MyHttpRequestExecutionHandler(requestCount), new DefaultConnectionReuseStrategy(), params);

    handler.setEventListener(new EventLogger());

    final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);

    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }//ww  w . j av a  2 s  . c  om
            System.out.println("Shutdown");
        }

    });
    t.start();

    List<SessionRequest> reqs = new ArrayList<SessionRequest>();
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.yahoo.com", 80), 
    //                null, 
    //                new HttpHost("www.yahoo.com"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.google.com", 80), 
    //                null,
    //                new HttpHost("www.google.ch"),
    //                null));
    //        reqs.add(ioReactor.connect(
    //                new InetSocketAddress("www.apache.org", 80), 
    //                null,
    //                new HttpHost("www.apache.org"),
    //                null));

    reqs.add(ioReactor.connect(new InetSocketAddress("www.wowhead.com", 80), null,
            new HttpHost("www.wowhead.com"), null));

    // Block until all connections signal
    // completion of the request execution
    synchronized (requestCount) {
        while (requestCount.getValue() > 0) {
            requestCount.wait();
        }
    }

    System.out.println("Shutting down I/O reactor");

    ioReactor.shutdown();

    System.out.println("Done");
}

From source file:com.amazonaws.services.kinesis.samples.datavis.HttpReferrerStreamWriter.java

/**
 * Start a number of threads and send randomly generated {@link HttpReferrerPair}s to a Kinesis Stream until the
 * program is terminated.//from   w  w  w  .  j ava 2  s.c o m
 *
 * @param args Expecting 3 arguments: A numeric value indicating the number of threads to use to send
 *        data to Kinesis and the name of the stream to send records to, and the AWS region in which these resources
 *        exist or should be created.
 * @throws InterruptedException If this application is interrupted while sending records to Kinesis.
 */
public static void main(String[] args) throws InterruptedException {
    if (args.length != 3) {
        System.err.println("Usage: " + HttpReferrerStreamWriter.class.getSimpleName()
                + " <number of threads> <stream name> <region>");
        System.exit(1);
    }

    int numberOfThreads = Integer.parseInt(args[0]);
    String streamName = args[1];
    Region region = SampleUtils.parseRegion(args[2]);

    AWSCredentialsProvider credentialsProvider = new DefaultAWSCredentialsProviderChain();
    ClientConfiguration clientConfig = SampleUtils.configureUserAgentForSample(new ClientConfiguration());
    AmazonKinesis kinesis = new AmazonKinesisClient(credentialsProvider, clientConfig);
    kinesis.setRegion(region);

    // The more resources we declare the higher write IOPS we need on our DynamoDB table.
    // We write a record for each resource every interval.
    // If interval = 500ms, resource count = 7 we need: (1000/500 * 7) = 14 write IOPS minimum.
    List<String> resources = new ArrayList<>();
    resources.add("/index.html");

    // These are the possible referrers to use when generating pairs
    List<String> referrers = new ArrayList<>();
    referrers.add("http://www.amazon.com");
    referrers.add("http://www.google.com");
    referrers.add("http://www.yahoo.com");
    referrers.add("http://www.bing.com");
    referrers.add("http://www.stackoverflow.com");
    referrers.add("http://www.reddit.com");

    HttpReferrerPairFactory pairFactory = new HttpReferrerPairFactory(resources, referrers);

    // Creates a stream to write to with 2 shards if it doesn't exist
    StreamUtils streamUtils = new StreamUtils(kinesis);
    streamUtils.createStreamIfNotExists(streamName, 2);
    LOG.info(String.format("%s stream is ready for use", streamName));

    final HttpReferrerKinesisPutter putter = new HttpReferrerKinesisPutter(pairFactory, kinesis, streamName);

    ExecutorService es = Executors.newCachedThreadPool();

    Runnable pairSender = new Runnable() {
        @Override
        public void run() {
            try {
                putter.sendPairsIndefinitely(DELAY_BETWEEN_RECORDS_IN_MILLIS, TimeUnit.MILLISECONDS);
            } catch (Exception ex) {
                LOG.warn(
                        "Thread encountered an error while sending records. Records will no longer be put by this thread.",
                        ex);
            }
        }
    };

    for (int i = 0; i < numberOfThreads; i++) {
        es.submit(pairSender);
    }

    LOG.info(String.format("Sending pairs with a %dms delay between records with %d thread(s).",
            DELAY_BETWEEN_RECORDS_IN_MILLIS, numberOfThreads));

    es.shutdown();
    es.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
}

From source file:com.ibm.soatf.SOATestingFramework.java

/**
 * SOA Testing Framework main static method.
 *
 * @param args Main input parameters.//from  w w  w  .  jav  a2  s  .  co m
 */
public static void main(String[] args) {
    Options options = new Options();
    options.addOption(new Option("gui", "Display a GUI"));

    options.addOption(OptionBuilder.withArgName("environment").hasArg()
            .withDescription("Environment to run the tests on").create("env")); // has a value
    options.addOption(OptionBuilder.withArgName("project").hasArg()
            .withDescription("Project to run the tests on").create("p")); // has a value
    options.addOption(OptionBuilder.withArgName("interface").hasArg()
            .withDescription("Interface to run the tests on").create("i")); // has a value
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);
        validate(cmd);

        if (cmd.hasOption("gui")) {

            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                if (false) { //disabled the OS Look'n'Feel
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } else {
                    for (UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                        if ("Nimbus".equals(info.getName())) {
                            javax.swing.UIManager.setLookAndFeel(info.getClassName());
                            break;
                        }
                    }
                    UIManager.getLookAndFeelDefaults().put("nimbusOrange", (new Color(0, 128, 255)));
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                    | javax.swing.UnsupportedLookAndFeelException ex) {
                logger.error("Cannot set look and feel", ex);
            }
            //</editor-fold>

            final SOATestingFrameworkGUI soatfgui = new SOATestingFrameworkGUI();
            java.awt.EventQueue.invokeLater(new Runnable() {

                @Override
                public void run() {
                    soatfgui.setVisible(true);
                }
            });
        } else {
            //<editor-fold defaultstate="collapsed" desc="Command line mode">
            try {
                // Initialization of configuration manager.
                ConfigurationManager.getInstance().init();

                String env = cmd.getOptionValue("env", null);
                String ifaceName;
                boolean inboundOnly = false;
                if (cmd.hasOption("p")) {
                    String projectName = cmd.getOptionValue("p");
                    MasterConfiguration masterConfig = ConfigurationManager.getInstance().getMasterConfig();
                    List<SOATestingFrameworkMasterConfiguration.Interfaces.Interface> interfaces = masterConfig
                            .getInterfaces();
                    all: for (Interface iface : interfaces) {
                        List<Project> projects = iface.getProjects().getProject();
                        for (Project project : projects) {
                            if (project.getName().equals(projectName)) {
                                inboundOnly = "INBOUND".equalsIgnoreCase(project.getDirection());
                                ifaceName = iface.getName();
                                break all;
                            }
                        }
                    }
                    throw new FrameworkExecutionException(
                            "No such project found in master configuration: " + projectName);
                } else {
                    ifaceName = cmd.getOptionValue("i");
                    inboundOnly = false;
                }
                DirectoryStructureManager.checkFrameworkDirectoryStructure(ifaceName);
                FlowExecutor flowExecutor = new FlowExecutor(inboundOnly, env, ifaceName);
                flowExecutor.execute();
            } catch (FrameworkConfigurationException ex) {
                logger.fatal("Configuration corrupted. See the exception stack trace for details.", ex);
            } catch (FrameworkException ex) {
                logger.fatal(ex);
            }
            //</editor-fold>
        }
    } catch (ParseException ex) {
        logger.fatal("Could not parse the command line arguments. Reason: " + ex);
        printUsage();
    } catch (Throwable ex) {
        logger.fatal("Unexpected error occured: ", ex);
        printUsage();
        System.exit(-1);
    }
}

From source file:com.pushtechnology.consulting.Benchmarker.java

public static void main(String[] args) throws InterruptedException {
    LOG.info("Starting Java Benchmark Suite v{}", Benchmarker.class.getPackage().getImplementationVersion());

    final Arguments arguments = Arguments.parse(args);

    try {/*ww w . j a v  a2s  .co m*/
        LOG.debug("Trying to set client InboundThreadPool queue size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        final ThreadsConfig threadsConfig = ConfigManager.getConfig().getThreads();
        final ThreadPoolConfig inboundPool = threadsConfig.addPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        inboundPool.setQueueSize(CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        inboundPool.setCoreSize(CLIENT_INBOUND_QUEUE_CORE_SIZE);
        inboundPool.setMaximumSize(CLIENT_INBOUND_QUEUE_MAX_SIZE);
        threadsConfig.setInboundPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        LOG.debug("Successfully set client InboundThreadPool queue size to '{}'",
                CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
    } catch (APIException ex) {
        LOG.error("Failed to set client inbound pool size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        ex.printStackTrace();
    }

    connectThreadPool = Executors.newScheduledThreadPool(arguments.connectThreadPoolSize);
    final Publisher publisher;

    if (arguments.doPublish) {
        LOG.info("Creating Publisher with connection string: '{}'", arguments.publisherConnectionString);
        publisher = new Publisher(arguments.publisherConnectionString, arguments.publisherUsername,
                arguments.publisherPassword, arguments.topics, arguments.topicType);
        publisher.start();

        publisherMonitor = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("publisherMonitor fired");
                LOG.info("There are {} publishers running for topics: '{}'",
                        publisher.getUpdaterFuturessByTopic().size(),
                        ArrayUtils.toString(publisher.getUpdaterFuturessByTopic().keySet()));
                for (ScheduledFuture<?> svc : publisher.getUpdaterFuturessByTopic().values()) {
                    if (svc.isCancelled()) {
                        LOG.debug("Service is cancelled...");
                    }
                    if (svc.isDone()) {
                        LOG.debug("Service is done...");
                    }
                }
                LOG.trace("Done publisherMonitor fired");
            }
        }, 2L, 5L, SECONDS);
    } else {
        publisher = null;
    }

    /* Create subscribing sessions. Finite or churning */
    if (arguments.doCreateSessions) {
        if (arguments.maxNumSessions > 0) {
            LOG.info("Creating {} Sessions with connection string: '{}'", arguments.maxNumSessions,
                    arguments.sessionConnectionString);
        } else {
            LOG.info("Creating Sessions with connection string: '{}s'", arguments.sessionConnectionString);
            LOG.info("Creating Sessions at {}/second, disconnecting after {} seconds", arguments.sessionRate,
                    arguments.sessionDuration);
        }
        sessionCreator = new SessionCreator(arguments.sessionConnectionString, arguments.myTopics,
                arguments.topicType);

        LOG.info(
                "Sessions: [Connected] [Started] [Recovering] [Closed] [Ended] [Failed]  | Messages: [Number] [Bytes]");
        sessionsCounter = globalThreadPool.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                LOG.trace("sessionsCounter fired");
                LOG.info("Sessions: {} {} {} {} {} {} | Messages: {} {}",
                        sessionCreator.getConnectedSessions().get(), sessionCreator.getStartedSessions().get(),
                        sessionCreator.getRecoveringSessions().get(), sessionCreator.getClosedSessions().get(),
                        sessionCreator.getEndedSessions().get(), sessionCreator.getConnectionFailures().get(),
                        sessionCreator.getMessageCount().getAndSet(0),
                        sessionCreator.getMessageByteCount().getAndSet(0));
                LOG.trace("Done sessionsCounter fired");
            }
        }, 0L, 5L, SECONDS);

        if (arguments.maxNumSessions > 0) {
            sessionCreator.start(arguments.maxNumSessions);
        } else {
            sessionCreator.start(arguments.sessionRate, arguments.sessionDuration);
        }
    }

    RUNNING_LATCH.await();

    if (arguments.doPublish) {
        if (publisher != null) {
            publisher.shutdown();
        }
        publisherMonitor.cancel(false);
    }

    if (arguments.doCreateSessions) {
        sessionCreator.shutdown();
        sessionsCounter.cancel(false);
    }

    if (!globalThreadPool.isTerminated()) {
        try {
            globalThreadPool.awaitTermination(1L, SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.brainflow.application.toplevel.Brainflow.java

public static void main(String[] args) {

    final Brainflow bflow = getInstance();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            try {
                log.info("Launching Brainflow ...");
                bflow.launch();/*from w w w.  j ava 2s .co m*/
            } catch (Throwable e) {
                Logger.getAnonymousLogger().severe("Error Launching Brainflow, exiting");
                e.printStackTrace();
                System.exit(-1);

            }

        }
    });

}

From source file:UserInterface.JFreeChart.java

/**
 * @param args the command line arguments
 *//*from  w  w w .  j  ava 2  s.c om*/
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(JFreeChart.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(JFreeChart.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(JFreeChart.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(JFreeChart.class.getName()).log(java.util.logging.Level.SEVERE, null,
                ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {

        }
    });
}

From source file:ChooseDropActionDemo.java

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            // Turn off metal's use of bold fonts
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            createAndShowGUI();/*from   w ww .ja va2  s  .c  om*/
        }
    });
}

From source file:at.co.malli.relpm.RelPM.java

/**
 * @param args the command line arguments
 *//*from   w w w . j a va  2  s .  com*/
public static void main(String[] args) {
    //<editor-fold defaultstate="collapsed" desc=" Create config & log directory ">
    String userHome = System.getProperty("user.home");
    File relPm = new File(userHome + "/.RelPM");
    if (!relPm.exists()) {
        boolean worked = relPm.mkdir();
        if (!worked) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not create directory "
                    + relPm.getAbsolutePath() + " to store user-settings and logs"));
            System.exit(-1);
        }
    }
    File userConfig = new File(relPm.getAbsolutePath() + "/RelPM-userconfig.xml"); //should be created...
    if (!userConfig.exists()) {
        try {
            URL resource = RelPM.class.getResource("/at/co/malli/relpm/RelPM-defaults.xml");
            FileUtils.copyURLToFile(resource, userConfig);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not copy default config. Reason:\n"
                    + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    if (!userConfig.canWrite() || !userConfig.canRead()) {
        ExceptionDisplayer.showErrorMessage(new Exception(
                "Can not read or write " + userConfig.getAbsolutePath() + "to store user-settings"));
        System.exit(-1);
    }
    if (System.getProperty("os.name").toLowerCase().contains("win")) {
        Path relPmPath = Paths.get(relPm.toURI());
        try {
            Files.setAttribute(relPmPath, "dos:hidden", true);
        } catch (IOException ex) {
            ExceptionDisplayer.showErrorMessage(new Exception("Could not set " + relPm.getAbsolutePath()
                    + " hidden. " + "Reason:\n" + ex.getClass().getName() + ": " + ex.getMessage()));
            System.exit(-1);
        }
    }
    //</editor-fold>

    logger.trace("Environment setup sucessfull");

    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code ">
    try {
        String wantedLookAndFeel = SettingsProvider.getInstance().getString("gui.lookAndFeel");
        UIManager.LookAndFeelInfo[] installed = UIManager.getInstalledLookAndFeels();
        boolean found = false;
        for (UIManager.LookAndFeelInfo info : installed) {
            if (info.getClassName().equals(wantedLookAndFeel))
                found = true;
        }
        if (found)
            UIManager.setLookAndFeel(wantedLookAndFeel);
        else
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (ClassNotFoundException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (InstantiationException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (IllegalAccessException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        logger.error(ex.getMessage());
        ExceptionDisplayer.showErrorMessage(ex);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc=" Add GUI start to awt EventQue ">
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new MainGUI().setVisible(true);
        }
    });
    //</editor-fold>
}

From source file:ExtendedParagraphExample.java

public static void main(String[] args) {
    try {//w  w  w .j a  v a 2  s. co  m
        UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch (Exception evt) {
    }

    JFrame f = new JFrame("Extended Paragraph Example");

    // Create the StyleContext, the document and the pane
    final StyleContext sc = new StyleContext();
    final DefaultStyledDocument doc = new DefaultStyledDocument(sc);
    final JTextPane pane = new JTextPane(doc);
    pane.setEditorKit(new ExtendedStyledEditorKit());

    try {
        // Add the text and apply the styles
        SwingUtilities.invokeAndWait(new Runnable() {
            public void run() {
                // Build the styles
                createDocumentStyles(sc);

                // Add the text
                addText(pane, sc, sc.getStyle(mainStyleName), content);
            }
        });
    } catch (Exception e) {
        System.out.println("Exception when constructing document: " + e);
        System.exit(1);
    }

    f.getContentPane().add(new JScrollPane(pane));
    f.setSize(400, 300);
    f.setVisible(true);
}

From source file:com.enjoyxstudy.selenium.autoexec.AutoExecServer.java

/**
 * @param args/*from  ww w  .  j  a v  a  2s .c  o  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String command = null;
    if (args.length == 0) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_STARTUP)) {
        command = COMMAND_STARTUP;
    } else if (args[0].equals(COMMAND_SHUTDOWN)) {
        command = COMMAND_SHUTDOWN;
    }

    if (command == null) {
        throw new IllegalArgumentException();
    }

    String propertyFile = DEFAULT_PROPERTY_FILE_NAME; // default
    if (args.length == 2) {
        propertyFile = args[1];
    }
    final Properties properties = new Properties();
    FileInputStream inputStream = new FileInputStream(propertyFile);
    try {
        properties.load(inputStream);
    } finally {
        inputStream.close();
    }

    if (command.equals(COMMAND_STARTUP)) {

        new Thread(new Runnable() {
            public void run() {
                try {

                    AutoExecServer autoExecServer = new AutoExecServer();

                    autoExecServer.startup(properties);
                    autoExecServer.runningLoop();
                    autoExecServer.destroy();

                } catch (Exception e) {
                    log.error("Error", e);
                    e.printStackTrace();
                } finally {
                    System.exit(0);
                }
            }
        }).start();

    } else {

        StringBuilder commandURL = new StringBuilder("http://localhost:");
        commandURL.append(
                PropertiesUtils.getInt(properties, "port", RemoteControlConfiguration.getDefaultPort()));
        commandURL.append(CONTEXT_PATH_COMMAND);

        RemoteControlClient client = new RemoteControlClient(commandURL.toString());

        client.stopServer();
    }
}