Example usage for java.lang Thread Thread

List of usage examples for java.lang Thread Thread

Introduction

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

Prototype

public Thread(String name) 

Source Link

Document

Allocates a new Thread object.

Usage

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

/**
 * @param args/* w  w w  . j  ava  2  s.  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();
    }
}

From source file:com.rabbitmq.examples.MulticastMain.java

public static void main(String[] args) {
    Options options = getOptions();// ww w  . j a  v a2 s . co m
    CommandLineParser parser = new GnuParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption('?')) {
            usage(options);
            System.exit(0);
        }

        String exchangeType = strArg(cmd, 't', "direct");
        String exchangeName = strArg(cmd, 'e', exchangeType);
        String queueName = strArg(cmd, 'u', "");
        int samplingInterval = intArg(cmd, 'i', 1);
        int rateLimit = intArg(cmd, 'r', 0);
        int producerCount = intArg(cmd, 'x', 1);
        int consumerCount = intArg(cmd, 'y', 1);
        int producerTxSize = intArg(cmd, 'm', 0);
        int consumerTxSize = intArg(cmd, 'n', 0);
        long confirm = intArg(cmd, 'c', -1);
        boolean autoAck = cmd.hasOption('a');
        int prefetchCount = intArg(cmd, 'q', 0);
        int minMsgSize = intArg(cmd, 's', 0);
        int timeLimit = intArg(cmd, 'z', 0);
        List<?> flags = lstArg(cmd, 'f');
        int frameMax = intArg(cmd, 'M', 0);
        int heartbeat = intArg(cmd, 'b', 0);
        String uri = strArg(cmd, 'h', "amqp://localhost");

        boolean exclusive = "".equals(queueName);
        boolean autoDelete = !exclusive;

        //setup
        String id = UUID.randomUUID().toString();
        Stats stats = new Stats(1000L * samplingInterval);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUri(uri);
        factory.setRequestedFrameMax(frameMax);
        factory.setRequestedHeartbeat(heartbeat);

        Thread[] consumerThreads = new Thread[consumerCount];
        Connection[] consumerConnections = new Connection[consumerCount];
        for (int i = 0; i < consumerCount; i++) {
            System.out.println("starting consumer #" + i);
            Connection conn = factory.newConnection();
            consumerConnections[i] = conn;
            Channel channel = conn.createChannel();
            if (consumerTxSize > 0)
                channel.txSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            String qName = channel
                    .queueDeclare(queueName, flags.contains("persistent"), exclusive, autoDelete, null)
                    .getQueue();
            if (prefetchCount > 0)
                channel.basicQos(prefetchCount);
            channel.queueBind(qName, exchangeName, id);
            Thread t = new Thread(new Consumer(channel, id, qName, consumerTxSize, autoAck, stats, timeLimit));
            consumerThreads[i] = t;
            t.start();
        }
        Thread[] producerThreads = new Thread[producerCount];
        Connection[] producerConnections = new Connection[producerCount];
        Channel[] producerChannels = new Channel[producerCount];
        for (int i = 0; i < producerCount; i++) {
            System.out.println("starting producer #" + i);
            Connection conn = factory.newConnection();
            producerConnections[i] = conn;
            Channel channel = conn.createChannel();
            producerChannels[i] = channel;
            if (producerTxSize > 0)
                channel.txSelect();
            if (confirm >= 0)
                channel.confirmSelect();
            channel.exchangeDeclare(exchangeName, exchangeType);
            final Producer p = new Producer(channel, exchangeName, id, flags, producerTxSize,
                    1000L * samplingInterval, rateLimit, minMsgSize, timeLimit, confirm);
            channel.addReturnListener(p);
            channel.addConfirmListener(p);
            Thread t = new Thread(p);
            producerThreads[i] = t;
            t.start();
        }

        for (int i = 0; i < producerCount; i++) {
            producerThreads[i].join();
            producerChannels[i].clearReturnListeners();
            producerChannels[i].clearConfirmListeners();
            producerConnections[i].close();
        }

        for (int i = 0; i < consumerCount; i++) {
            consumerThreads[i].join();
            consumerConnections[i].close();
        }

    } catch (ParseException exp) {
        System.err.println("Parsing failed. Reason: " + exp.getMessage());
        usage(options);
    } catch (Exception e) {
        System.err.println("Main thread caught exception: " + e);
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:com.aerospike.load.AerospikeLoad.java

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

    Thread statPrinter = new Thread(new PrintStat(counters));
    try {/* ww w .  j  a  va 2s .c o  m*/
        log.info("Aerospike loader started");
        Options options = new Options();
        options.addOption("h", "host", true, "Server hostname (default: localhost)");
        options.addOption("p", "port", true, "Server port (default: 3000)");
        options.addOption("n", "namespace", true, "Namespace (default: test)");
        options.addOption("s", "set", true, "Set name. (default: null)");
        options.addOption("c", "config", true, "Column definition file name");
        options.addOption("wt", "write-threads", true,
                "Number of writer threads (default: Number of cores * 5)");
        options.addOption("rt", "read-threads", true,
                "Number of reader threads (default: Number of cores * 1)");
        options.addOption("l", "rw-throttle", true, "Throttling of reader to writer(default: 10k) ");
        options.addOption("tt", "transaction-timeout", true,
                "write transaction timeout in miliseconds(default: No timeout)");
        options.addOption("et", "expiration-time", true,
                "Expiration time of records in seconds (default: never expire)");
        options.addOption("T", "timezone", true,
                "Timezone of source where data dump is taken (default: local timezone)");
        options.addOption("ec", "abort-error-count", true, "Error count to abort (default: 0)");
        options.addOption("wa", "write-action", true, "Write action if key already exists (default: update)");
        options.addOption("v", "verbose", false, "Logging all");
        options.addOption("u", "usage", false, "Print usage.");

        CommandLineParser parser = new PosixParser();
        CommandLine cl = parser.parse(options, args, false);

        if (args.length == 0 || cl.hasOption("u")) {
            logUsage(options);
            return;
        }

        if (cl.hasOption("l")) {
            rwThrottle = Integer.parseInt(cl.getOptionValue("l"));
        } else {
            rwThrottle = Constants.READLOAD;
        }
        // Get all command line options
        params = Utils.parseParameters(cl);

        //Get client instance
        AerospikeClient client = new AerospikeClient(params.host, params.port);
        if (!client.isConnected()) {
            log.error("Client is not able to connect:" + params.host + ":" + params.port);
            return;
        }

        if (params.verbose) {
            log.setLevel(Level.DEBUG);
        }

        // Get available processors to calculate default number of threads
        int cpus = Runtime.getRuntime().availableProcessors();
        nWriterThreads = cpus * scaleFactor;
        nReaderThreads = cpus;

        // Get writer thread count
        if (cl.hasOption("wt")) {
            nWriterThreads = Integer.parseInt(cl.getOptionValue("wt"));
            nWriterThreads = (nWriterThreads > 0
                    ? (nWriterThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nWriterThreads)
                    : 1);
            log.debug("Using writer Threads: " + nWriterThreads);
        }
        writerPool = Executors.newFixedThreadPool(nWriterThreads);

        // Get reader thread count
        if (cl.hasOption("rt")) {
            nReaderThreads = Integer.parseInt(cl.getOptionValue("rt"));
            nReaderThreads = (nReaderThreads > 0
                    ? (nReaderThreads > Constants.MAX_THREADS ? Constants.MAX_THREADS : nReaderThreads)
                    : 1);
            log.debug("Using reader Threads: " + nReaderThreads);
        }

        String columnDefinitionFileName = cl.getOptionValue("c", null);

        log.debug("Column definition files/directory: " + columnDefinitionFileName);
        if (columnDefinitionFileName == null) {
            log.error("Column definition files/directory not specified. use -c <file name>");
            return;
        }

        File columnDefinitionFile = new File(columnDefinitionFileName);
        if (!columnDefinitionFile.exists()) {
            log.error("Column definition files/directory does not exist: "
                    + Utils.getFileName(columnDefinitionFileName));
            return;
        }

        // Get data file list
        String[] files = cl.getArgs();
        if (files.length == 0) {
            log.error("No data file Specified: add <file/dir name> to end of the command ");
            return;
        }
        List<String> allFileNames = new ArrayList<String>();
        allFileNames = Utils.getFileNames(files);
        if (allFileNames.size() == 0) {
            log.error("Given datafiles/directory does not exist");
            return;
        }
        for (int i = 0; i < allFileNames.size(); i++) {
            log.debug("File names:" + Utils.getFileName(allFileNames.get(i)));
            File file = new File(allFileNames.get(i));
            counters.write.recordTotal = counters.write.recordTotal + file.length();
        }

        //remove column definition file from list
        allFileNames.remove(columnDefinitionFileName);

        log.info("Number of data files:" + allFileNames.size());

        /**
         * Process column definition file to get meta data and bin mapping.
         */
        metadataColumnDefs = new ArrayList<ColumnDefinition>();
        binColumnDefs = new ArrayList<ColumnDefinition>();
        metadataConfigs = new HashMap<String, String>();

        if (Parser.processJSONColumnDefinitions(columnDefinitionFile, metadataConfigs, metadataColumnDefs,
                binColumnDefs, params)) {
            log.info("Config file processed.");
        } else {
            throw new Exception("Config file parsing Error");
        }

        // Add metadata of config to parameters
        String metadata;
        if ((metadata = metadataConfigs.get(Constants.INPUT_TYPE)) != null) {
            params.fileType = metadata;
            if (params.fileType.equals(Constants.CSV_FILE)) {

                // Version check
                metadata = metadataConfigs.get(Constants.VERSION);
                String[] vNumber = metadata.split("\\.");
                int v1 = Integer.parseInt(vNumber[0]);
                int v2 = Integer.parseInt(vNumber[1]);
                if ((v1 <= Constants.MajorV) && (v2 <= Constants.MinorV)) {
                    log.debug("Config version used:" + metadata);
                } else
                    throw new Exception("\"" + Constants.VERSION + ":" + metadata + "\" is not Supported");

                // Set delimiter 
                if ((metadata = metadataConfigs.get(Constants.DELIMITER)) != null && metadata.length() == 1) {
                    params.delimiter = metadata.charAt(0);
                } else {
                    log.warn("\"" + Constants.DELIMITER + ":" + metadata
                            + "\" is not properly specified in config file. Default is ','");
                }

                if ((metadata = metadataConfigs.get(Constants.IGNORE_FIRST_LINE)) != null) {
                    params.ignoreFirstLine = metadata.equals("true");
                } else {
                    log.warn("\"" + Constants.IGNORE_FIRST_LINE + ":" + metadata
                            + "\" is not properly specified in config file. Default is false");
                }

                if ((metadata = metadataConfigs.get(Constants.COLUMNS)) != null) {
                    counters.write.colTotal = Integer.parseInt(metadata);
                } else {
                    throw new Exception("\"" + Constants.COLUMNS + ":" + metadata
                            + "\" is not properly specified in config file");
                }
            } else {
                throw new Exception("\"" + params.fileType + "\" is not supported in config file");
            }
        } else {
            throw new Exception("\"" + Constants.INPUT_TYPE + "\" is not specified in config file");
        }

        // add config input to column definitions
        if (params.fileType.equals(Constants.CSV_FILE)) {
            List<String> binName = null;
            if (params.ignoreFirstLine) {
                String line;
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(new FileInputStream(allFileNames.get(0)), "UTF8"));
                if ((line = br.readLine()) != null) {
                    binName = Parser.getCSVRawColumns(line, params.delimiter);
                    br.close();
                    if (binName.size() != counters.write.colTotal) {
                        throw new Exception("Number of column in config file and datafile are mismatch."
                                + " Datafile: " + Utils.getFileName(allFileNames.get(0)) + " Configfile: "
                                + Utils.getFileName(columnDefinitionFileName));
                    }
                }
            }

            //update columndefs for metadata
            for (int i = 0; i < metadataColumnDefs.size(); i++) {
                if (metadataColumnDefs.get(i).staticValue) {

                } else {
                    if (metadataColumnDefs.get(i).binValuePos < 0) {
                        if (metadataColumnDefs.get(i).columnName == null) {
                            if (metadataColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic metadata having improper info"
                                        + metadataColumnDefs.toString()); //TODO
                            } else {
                                //TODO check for json_path   
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.indexOf(metadataColumnDefs.get(i).binValueHeader) != -1) {
                                    metadataColumnDefs.get(i).binValuePos = binName
                                            .indexOf(metadataColumnDefs.get(i).binValueHeader);
                                } else {
                                    throw new Exception("binName missing in data file:"
                                            + metadataColumnDefs.get(i).binValueHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            metadataColumnDefs.get(i).binValueHeader = binName
                                    .get(metadataColumnDefs.get(i).binValuePos);
                    }
                }
                if ((!metadataColumnDefs.get(i).staticValue) && (metadataColumnDefs.get(i).binValuePos < 0)) {
                    throw new Exception("Information for bin mapping is missing in config file:"
                            + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).srcType == null) {
                    throw new Exception(
                            "Source data type is not properly mentioned:" + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).binNameHeader == Constants.SET
                        && !metadataColumnDefs.get(i).srcType.equals(SrcColumnType.STRING)) {
                    throw new Exception("Set name should be string type:" + metadataColumnDefs.get(i));
                }

                if (metadataColumnDefs.get(i).binNameHeader.equalsIgnoreCase(Constants.SET)
                        && params.set != null) {
                    throw new Exception(
                            "Set name is given both in config file and commandline. Provide only once.");
                }
            }

            //update columndefs for bins
            for (int i = 0; i < binColumnDefs.size(); i++) {
                if (binColumnDefs.get(i).staticName) {

                } else {
                    if (binColumnDefs.get(i).binNamePos < 0) {
                        if (binColumnDefs.get(i).columnName == null) {
                            if (binColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic bin having improper info"); //TODO
                            } else {
                                //TODO check for json_path
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.indexOf(binColumnDefs.get(i).binNameHeader) != -1) {
                                    binColumnDefs.get(i).binNamePos = binName
                                            .indexOf(binColumnDefs.get(i).binNameHeader);
                                } else {
                                    throw new Exception("binName missing in data file:"
                                            + binColumnDefs.get(i).binNameHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            binColumnDefs.get(i).binNameHeader = binName.get(binColumnDefs.get(i).binNamePos);
                    }
                }

                if (binColumnDefs.get(i).staticValue) {

                } else {
                    if (binColumnDefs.get(i).binValuePos < 0) {
                        if (binColumnDefs.get(i).columnName == null) {
                            if (binColumnDefs.get(i).jsonPath == null) {
                                log.error("dynamic bin having improper info"); //TODO
                            } else {
                                //TODO check for json_path
                            }
                        } else {
                            if (params.ignoreFirstLine) {
                                if (binName.contains(binColumnDefs.get(i).binValueHeader)) {
                                    binColumnDefs.get(i).binValuePos = binName
                                            .indexOf(binColumnDefs.get(i).binValueHeader);
                                } else if (!binColumnDefs.get(i).binValueHeader.toLowerCase()
                                        .equals(Constants.SYSTEM_TIME)) {
                                    throw new Exception("Wrong column name mentioned in config file:"
                                            + binColumnDefs.get(i).binValueHeader);
                                }
                            }
                        }
                    } else {
                        if (params.ignoreFirstLine)
                            binColumnDefs.get(i).binValueHeader = binName.get(binColumnDefs.get(i).binValuePos);
                    }

                    //check for missing entries in config file
                    if (binColumnDefs.get(i).binValuePos < 0 && binColumnDefs.get(i).binValueHeader == null) {
                        throw new Exception("Information missing(Value header or bin mapping) in config file:"
                                + binColumnDefs.get(i));
                    }

                    //check for proper data type in config file.
                    if (binColumnDefs.get(i).srcType == null) {
                        throw new Exception(
                                "Source data type is not properly mentioned:" + binColumnDefs.get(i));
                    }

                    //check for valid destination type
                    if ((binColumnDefs.get(i).srcType.equals(SrcColumnType.TIMESTAMP)
                            || binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB))
                            && binColumnDefs.get(i).dstType == null) {
                        throw new Exception("Destination type is not mentioned: " + binColumnDefs.get(i));
                    }

                    //check for encoding
                    if (binColumnDefs.get(i).dstType != null && binColumnDefs.get(i).encoding == null) {
                        throw new Exception(
                                "Encoding is not given for src-dst type conversion:" + binColumnDefs.get(i));
                    }

                    //check for valid encoding
                    if (binColumnDefs.get(i).srcType.equals(SrcColumnType.BLOB)
                            && !binColumnDefs.get(i).encoding.equals(Constants.HEX_ENCODING)) {
                        throw new Exception("Wrong encoding for blob data:" + binColumnDefs.get(i));
                    }
                }

                //Check static bin name mapped to dynamic bin value
                if ((binColumnDefs.get(i).binNamePos == binColumnDefs.get(i).binValuePos)
                        && (binColumnDefs.get(i).binNamePos != -1)) {
                    throw new Exception("Static bin name mapped to dynamic bin value:" + binColumnDefs.get(i));
                }

                //check for missing entries in config file
                if (binColumnDefs.get(i).binNameHeader == null
                        && binColumnDefs.get(i).binNameHeader.length() > Constants.BIN_NAME_LENGTH) {
                    throw new Exception("Information missing binName or large binName in config file:"
                            + binColumnDefs.get(i));
                }
            }
        }

        log.info(params.toString());
        log.debug("MetadataConfig:" + metadataColumnDefs);
        log.debug("BinColumnDefs:" + binColumnDefs);

        // Start PrintStat thread
        statPrinter.start();

        // Reader pool size
        ExecutorService readerPool = Executors.newFixedThreadPool(
                nReaderThreads > allFileNames.size() ? allFileNames.size() : nReaderThreads);
        log.info("Reader pool size : " + nReaderThreads);

        // Submit all tasks to writer threadpool.
        for (String aFile : allFileNames) {
            log.debug("Submitting task for: " + aFile);
            readerPool.submit(new AerospikeLoad(aFile, client, params));
        }

        // Wait for reader pool to complete
        readerPool.shutdown();
        log.info("Shutdown down reader thread pool");

        while (!readerPool.isTerminated())
            ;
        //readerPool.awaitTermination(20, TimeUnit.MINUTES);
        log.info("Reader thread pool terminated");

        // Wait for writer pool to complete after getting all tasks from reader pool
        writerPool.shutdown();
        log.info("Shutdown down writer thread pool");

        while (!writerPool.isTerminated())
            ;
        log.info("Writer thread pool terminated");

        // Print final statistic of aerospike-loader.
        log.info("Final Statistics of importer: (Succesfull Writes = " + counters.write.writeCount.get() + ", "
                + "Errors="
                + (counters.write.writeErrors.get() + counters.write.readErrors.get()
                        + counters.write.processingErrors.get())
                + "(" + (counters.write.writeErrors.get()) + "-Write," + counters.write.readErrors.get()
                + "-Read," + counters.write.processingErrors.get() + "-Processing)");
    } catch (Exception e) {
        log.error(e);
        if (log.isDebugEnabled()) {
            e.printStackTrace();
        }
    } finally {
        // Stop statistic printer thread.
        statPrinter.interrupt();
        log.info("Aerospike loader completed");
    }
}

From source file:com.sshtools.j2ssh.agent.SshAgentSocketListener.java

/**
 * The main entry point for the application. This method currently accepts
 * the -start parameter which will look for the sshtools.agent system
 * property. To configure the agent and to get a valid location call with
 * -configure, set the system sshtools.home system property and start.
 *
 * @param args the programs arguments// w w w  .  j  a v  a2s  .c  o  m
 */
public static void main(String[] args) {
    if (args.length > 0) {
        if (args[0].equals("-start")) {
            Thread thread = new Thread(new Runnable() {
                public void run() {
                    try {
                        SshAgentSocketListener agent = new SshAgentSocketListener(
                                System.getProperty("sshtools.agent"), new KeyStore());
                        agent.start();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });

            thread.start();
        }

        if (args[0].equals("-configure")) {
            System.out.println("SET SSHTOOLS_AGENT=localhost:" + String.valueOf(configureNewLocation()));
        }
    }
}

From source file:org.eclipse.ecf.provider.filetransfer.httpcore.NHttpClient.java

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

    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
    //CountDownLatch requestCount = new CountDownLatch(3);
    CountDownLatch requestCount = new CountDownLatch(1);

    BufferingHttpClientHandler handler = new MyBufferingHttpClientHandler(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());
            }//from   w  w w .j  a  va  2  s.c o m
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[1];
    reqs[0] = ioReactor.connect(new InetSocketAddress("ftp.osuosl.org", 80), null,
            new HttpHost("ftp.osuosl.org"), new MySessionRequestCallback(requestCount));
    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

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

    ioReactor.shutdown();

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

From source file:collabedit.Telnet.java

/***
 * Main for the TelnetClientExample./*from   w  w w  .  j a v  a2s. c o  m*/
 ***/
public static void main(String[] args) throws Exception {
    FileOutputStream fout = null;

    String remoteip = "23.102.136.121";

    int remoteport = 8888;

    try {
        fout = new FileOutputStream("spy.log", true);
    } catch (IOException e) {
        System.err.println("Exception while opening the spy file: " + e.getMessage());
    }

    tc = new TelnetClient();

    TerminalTypeOptionHandler ttopt = new TerminalTypeOptionHandler("VT100", false, false, true, false);
    EchoOptionHandler echoopt = new EchoOptionHandler(true, false, true, false);
    SuppressGAOptionHandler gaopt = new SuppressGAOptionHandler(true, true, true, true);

    try {
        tc.addOptionHandler(ttopt);
        tc.addOptionHandler(echoopt);
        tc.addOptionHandler(gaopt);
    } catch (InvalidTelnetOptionException e) {
        System.err.println("Error registering option handlers: " + e.getMessage());
    }

    try {
        tc.connect(remoteip, remoteport);

        Thread reader = new Thread(new Telnet());
        tc.registerNotifHandler(new Telnet());
        System.out.println("TelnetClientExample");
        System.out.println("Type AYT to send an AYT telnet command");
        System.out.println("Type OPT to print a report of status of options (0-24)");
        System.out.println("Type REGISTER to register a new SimpleOptionHandler");
        System.out.println("Type UNREGISTER to unregister an OptionHandler");
        System.out.println("Type SPY to register the spy (connect to port 3333 to spy)");
        System.out.println("Type UNSPY to stop spying the connection");

        reader.start();
        OutputStream outstr = tc.getOutputStream();

        byte[] buff = new byte[1024];
        int ret_read = 0;
        /*
         * do { try { ret_read = System.in.read(buff); if (ret_read > 0) {
         * if ((new String(buff, 0, ret_read)) .startsWith("AYT")) { try {
         * System.out.println("Sending AYT");
         * 
         * System.out.println("AYT response:" + tc.sendAYT(5000)); } catch
         * (IOException e) { System.err
         * .println("Exception waiting AYT response: " + e.getMessage()); }
         * } else if ((new String(buff, 0, ret_read)) .startsWith("OPT")) {
         * System.out.println("Status of options:"); for (int ii = 0; ii <
         * 25; ii++) { System.out.println("Local Option " + ii + ":" +
         * tc.getLocalOptionState(ii) + " Remote Option " + ii + ":" +
         * tc.getRemoteOptionState(ii)); } } else if ((new String(buff, 0,
         * ret_read)) .startsWith("REGISTER")) { StringTokenizer st = new
         * StringTokenizer( new String(buff)); try { st.nextToken(); int
         * opcode = Integer.parseInt(st .nextToken()); boolean initlocal =
         * Boolean.parseBoolean(st .nextToken()); boolean initremote =
         * Boolean .parseBoolean(st.nextToken()); boolean acceptlocal =
         * Boolean .parseBoolean(st.nextToken()); boolean acceptremote =
         * Boolean .parseBoolean(st.nextToken()); SimpleOptionHandler
         * opthand = new SimpleOptionHandler( opcode, initlocal, initremote,
         * acceptlocal, acceptremote); tc.addOptionHandler(opthand); } catch
         * (Exception e) { if (e instanceof InvalidTelnetOptionException) {
         * System.err .println("Error registering option: " +
         * e.getMessage()); } else { System.err
         * .println("Invalid REGISTER command."); System.err .println(
         * "Use REGISTER optcode initlocal initremote acceptlocal acceptremote"
         * ); System.err .println("(optcode is an integer.)"); System.err
         * .println
         * ("(initlocal, initremote, acceptlocal, acceptremote are boolean)"
         * ); } } } else if ((new String(buff, 0, ret_read))
         * .startsWith("UNREGISTER")) { StringTokenizer st = new
         * StringTokenizer( new String(buff)); try { st.nextToken(); int
         * opcode = (new Integer(st.nextToken())) .intValue();
         * tc.deleteOptionHandler(opcode); } catch (Exception e) { if (e
         * instanceof InvalidTelnetOptionException) { System.err
         * .println("Error unregistering option: " + e.getMessage()); } else
         * { System.err .println("Invalid UNREGISTER command."); System.err
         * .println("Use UNREGISTER optcode"); System.err
         * .println("(optcode is an integer)"); } } } else if ((new
         * String(buff, 0, ret_read)) .startsWith("SPY")) {
         * tc.registerSpyStream(fout); } else if ((new String(buff, 0,
         * ret_read)) .startsWith("UNSPY")) { tc.stopSpyStream(); } else {
         * post("hi"); } } } catch (IOException e) {
         * System.err.println("Exception while reading keyboard:" +
         * e.getMessage()); end_loop = true; } } while ((ret_read > 0) &&
         * (end_loop == false));
         */
    } catch (IOException e) {
        System.err.println("Exception while connecting:" + e.getMessage());
        System.exit(1);
    }
}

From source file:com.salaboy.rolo.hardware.test.HardwareSerialTestCommandServer.java

public static void main(String[] args) throws Exception {
    Weld weld = new Weld();

    WeldContainer container = weld.initialize();

    HardwareSerialTestCommandServer roloCommandServer = container.instance()
            .select(HardwareSerialTestCommandServer.class).get();

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("t", true, "sensors latency");
    options.addOption("ip", true, "host");
    options.addOption("port", true, "port");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String sensorLatency = cmd.getOptionValue("t");
    if (sensorLatency == null) {
        System.out.println(" The Default Latency will be used: " + defaultLatency);
    } else {//from   w w  w .  j  a  va2s  .co m
        System.out.println(" The Latency will be set to: " + sensorLatency);
        defaultLatency = new Long(sensorLatency);
    }

    String ip = cmd.getOptionValue("ip");
    if (ip == null) {
        System.out.println(" The Default IP will be used: 127.0.0.1");
        roloCommandServer.setHost("127.0.0.1");

    } else {
        System.out.println(" The IP will be set to: " + ip);
        roloCommandServer.setHost(ip);
    }

    String port = cmd.getOptionValue("port");
    if (port == null) {
        System.out.println(" The Default Port will be used: 5445");
        roloCommandServer.setPort(5445);

    } else {
        System.out.println(" The Port will be set to: " + port);
        roloCommandServer.setPort(Integer.parseInt(port));
    }

    System.out.println("Starting Rolo ...");

    Thread thread = new Thread(roloCommandServer);
    thread.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            System.out.println("Shutdown Hook is running !");

        }
    });

}

From source file:NHttpClient.java

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

    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
    CountDownLatch requestCount = new CountDownLatch(3);

    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());
            }/* w w w .  j a va 2  s .co  m*/
            System.out.println("Shutdown");
        }

    });
    t.start();

    SessionRequest[] reqs = new SessionRequest[3];
    reqs[0] = ioReactor.connect(new InetSocketAddress("www.yahoo.com", 80), null, new HttpHost("www.yahoo.com"),
            new MySessionRequestCallback(requestCount));
    reqs[1] = ioReactor.connect(new InetSocketAddress("www.google.com", 80), null,
            new HttpHost("www.google.ch"), new MySessionRequestCallback(requestCount));
    reqs[2] = ioReactor.connect(new InetSocketAddress("www.apache.org", 80), null,
            new HttpHost("www.apache.org"), new MySessionRequestCallback(requestCount));

    // Block until all connections signal
    // completion of the request execution
    requestCount.await();

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

    ioReactor.shutdown();

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

From source file:com.salaboy.rolo.server.RoloCommandServer.java

public static void main(String[] args) throws Exception {
    final Weld weld = new Weld();

    WeldContainer container = weld.initialize();

    RoloCommandServer roloCommandServer = container.instance().select(RoloCommandServer.class).get();

    // create Options object
    Options options = new Options();

    // add t option
    options.addOption("t", true, "sensors latency");
    options.addOption("ip", true, "host");
    options.addOption("port", true, "port");
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);

    String sensorLatency = cmd.getOptionValue("t");
    if (sensorLatency == null) {
        System.out.println(" The Default Latency will be used: " + defaultLatency);
    } else {//  w w w  .  jav a  2  s . co m
        System.out.println(" The Latency will be set to: " + sensorLatency);
        defaultLatency = new Long(sensorLatency);
    }

    String ip = cmd.getOptionValue("ip");
    if (ip == null) {
        System.out.println(" The Default IP will be used: 127.0.0.1");
        roloCommandServer.setHost("127.0.0.1");

    } else {
        System.out.println(" The IP will be set to: " + ip);
        roloCommandServer.setHost(ip);
    }

    String port = cmd.getOptionValue("port");
    if (port == null) {
        System.out.println(" The Default Port will be used: 5445");
        roloCommandServer.setPort(5445);

    } else {
        System.out.println(" The Port will be set to: " + port);
        roloCommandServer.setPort(Integer.parseInt(port));
    }

    System.out.println("Starting Server Rolo ...");

    Thread thread = new Thread(roloCommandServer);
    thread.start();

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            System.out.println("Shutdown Hook is running !");
            readSensors = false;
            weld.shutdown();
        }
    });

}

From source file:ch.ethz.dcg.jukefox.cli.CliJukefoxApplication.java

public static void main(String[] args) {

    CommandLineParser parser = new PosixParser();
    LogLevel logLevel = LogLevel.ERROR;//from  w  w  w .  ja v a 2 s  .co m
    try {
        CommandLine line = parser.parse(getCliOptions(), args);
        if (line.hasOption(VERBOSE_OPTION)) {
            logLevel = LogLevel.VERBOSE;
        }
    } catch (ParseException e1) {
        Log.e(TAG, "Unexpected exception: " + e1.getMessage());
    }

    printWelcome();

    Log.setLogLevel(logLevel);

    // Send logs async
    new Thread(new Runnable() {

        @Override
        public void run() {
            playerModel.getLogManager().sendLogs();
        }
    }).start();

    CliJukefoxApplication application = new CliJukefoxApplication();

    try {
        scanner = new Scanner(System.in);
        application.start();

        ImportState importState = libraryImportManager.getImportState();
        importState.addListener(application);
        //System.out.println(importState.getProgress().getStatusMessage());

        while (running) {
            String next = scanner.nextLine();
            if (next.isEmpty()) {
                continue;
            }
            try {
                application.getCommandLineInterface().execute(next);
            } catch (ExecutionException e) {
                System.out.println("Invalid input, please use following commands: ");
                application.getCommandLineInterface().execute("help");
            }

        }
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}