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:clientpaxos.ClientPaxos.java

/**
 * @param args the command line arguments
 *///from   w  w w.j a va2s .  c  o m
public static void main(String[] args) throws IOException, InterruptedException, Exception {
    // TODO code application logic here

    String host = "";
    int port = 0;

    try (BufferedReader br = new BufferedReader(new FileReader("ipserver.txt"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        if (line != null) {
            host = line;
            line = br.readLine();
            if (line != null) {
                port = Integer.parseInt(line);
            }
        }
    }

    scanner = new Scanner(System.in);

    //System.out.print("Input server IP hostname : ");
    //host = scan.nextLine();
    //System.out.print("Input server Port : ");
    //port = scan.nextInt();
    //scan.nextLine();
    tcpSocket = new Socket(host, port);
    System.out.println("Connected");
    Thread t = new Thread(new StringGetter());
    t.start();
    while (true) {
        sleep(100);
        if (!voteInput) {
            System.out.print("COMMAND : ");
        }
        //send msg to server
        String msg = scanner.next();
        //if ((day && isAlive == 1) || (!day && role.equals("werewolf") && isAlive == 1)) {
        ParseCommand(msg);
        //}
    }
}

From source file:com.yulore.demo.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("Test/1.1")).add(new RequestExpectContinue(true)).build();
    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();
    // Create client-side I/O event dispatch
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);/*from  ww  w. j av  a  2s .c o m*/
    // Create client-side I/O reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();
    // Create HTTP connection pool
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);
    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);
    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();
    // Create HTTP requester
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);
    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.apache.org", 80, "http"),
            new HttpHost("www.verisign.com", 443, "https"), new HttpHost("www.google.com", 80, "http") };
    final CountDownLatch latch = new CountDownLatch(targets.length);
    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.out.println(target + "->" + ex);
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");

}

From source file:com.linkedin.pinot.server.starter.FileBasedServer.java

public static void main(String[] args) throws Exception {
    //Process Command Line to get config and port
    processCommandLineArgs(args);//from w  ww .j a  v  a  2  s  .co  m

    LOGGER.info("Trying to build server config");
    MetricsRegistry metricsRegistry = new MetricsRegistry();
    ServerBuilder serverBuilder = new ServerBuilder(new File(_serverConfigPath), metricsRegistry);

    LOGGER.info("Trying to build InstanceDataManager");
    final DataManager instanceDataManager = serverBuilder.buildInstanceDataManager();
    LOGGER.info("Trying to start InstanceDataManager");
    instanceDataManager.start();
    //    bootstrapSegments(instanceDataManager);

    LOGGER.info("Trying to build QueryExecutor");
    final QueryExecutor queryExecutor = serverBuilder.buildQueryExecutor(instanceDataManager);
    final QueryScheduler queryScheduler = serverBuilder.buildQueryScheduler(queryExecutor);
    LOGGER.info("Trying to build RequestHandlerFactory");
    RequestHandlerFactory simpleRequestHandlerFactory = serverBuilder
            .buildRequestHandlerFactory(queryScheduler);
    LOGGER.info("Trying to build NettyServer");

    NettyServer nettyServer = new NettyTCPServer(_serverPort, simpleRequestHandlerFactory, null);
    Thread serverThread = new Thread(nettyServer);
    ShutdownHook shutdownHook = new ShutdownHook(nettyServer);
    serverThread.start();
    Runtime.getRuntime().addShutdownHook(shutdownHook);
}

From source file:com.amazonaws.services.iot.demo.danbo.rpi.Danbo.java

public static void main(String[] args) throws Exception {
    log.debug("starting");

    // uses pin 6 for the red Led
    final Led redLed = new Led(6);
    // uses pin 26 for the green Led
    final Led greenLed = new Led(26);

    // turns the red led on initially
    redLed.on();/*from  w  ww.ja  v a  2 s.c  om*/

    // turns the green led off initially
    greenLed.off();

    // loads properties from danbo.properties file - make sure this file is
    // available on the pi's home directory
    InputStream input = new FileInputStream("/home/pi/danbo/danbo.properties");
    Properties properties = new Properties();
    properties.load(input);
    endpoint = properties.getProperty("awsiot.endpoint");
    rootCA = properties.getProperty("awsiot.rootCA");
    privateKey = properties.getProperty("awsiot.privateKey");
    certificate = properties.getProperty("awsiot.certificate");
    url = protocol + endpoint + ":" + port;

    log.debug("properties loaded");

    // turns off both eyes
    RGBLed rgbLed = new RGBLed("RGBLed1", Danbo.pinLayout1, Danbo.pinLayout2, new Color(0, 0, 0),
            new Color(0, 0, 0), 0, 100);
    new Thread(rgbLed).start();

    // resets servo to initial positon
    Servo servo = new Servo("Servo", 1);
    new Thread(servo).start();

    // gets the Pi serial number and uses it as part of the thing
    // registration name
    clientId = clientId + getSerialNumber();

    // AWS IoT things shadow topics
    updateTopic = "$aws/things/" + clientId + "/shadow/update";
    deltaTopic = "$aws/things/" + clientId + "/shadow/update/delta";
    rejectedTopic = "$aws/things/" + clientId + "/shadow/update/rejected";

    // AWS IoT controller things shadow topic (used to register new things)
    controllerUpdateTopic = "$aws/things/Controller/shadow/update";

    // defines an empty danbo shadow POJO
    final DanboShadow danboShadow = new DanboShadow();
    DanboShadow.State state = danboShadow.new State();
    final DanboShadow.State.Reported reported = state.new Reported();
    reported.setEyes("readyToBlink");
    reported.setHead("readyToMove");
    reported.setMouth("readyToSing");
    reported.setName(clientId);
    state.setReported(reported);
    danboShadow.setState(state);

    // defines an empty controller shadow POJO
    final ControllerShadow controllerShadow = new ControllerShadow();
    ControllerShadow.State controllerState = controllerShadow.new State();
    final ControllerShadow.State.Reported controllerReported = controllerState.new Reported();
    controllerReported.setThingName(clientId);
    controllerState.setReported(controllerReported);
    controllerShadow.setState(controllerState);

    try {
        log.debug("registering");

        // registers the thing (creates a new thing) by updating the
        // controller
        String message = gson.toJson(controllerShadow);
        MQTTPublisher controllerUpdatePublisher = new MQTTPublisher(controllerUpdateTopic, qos, message, url,
                clientId + "-controllerupdate" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(controllerUpdatePublisher).start();

        log.debug("registered");

        // clears the thing status (in case the thing already existed)
        Danbo.deleteStatus("initialDelete");

        // creates an MQTT subscriber to the things shadow delta topic
        // (command execution notification)
        MQTTSubscriber deltaSubscriber = new MQTTSubscriber(new DanboShadowDeltaCallback(), deltaTopic, qos,
                url, clientId + "-delta" + rand.nextInt(100000), cleanSession, rootCA, privateKey, certificate);
        new Thread(deltaSubscriber).start();

        // creates an MQTT subscriber to the things shadow error topic
        MQTTSubscriber errorSubscriber = new MQTTSubscriber(new DanboShadowRejectedCallback(), rejectedTopic,
                qos, url, clientId + "-rejected" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                certificate);
        new Thread(errorSubscriber).start();

        // turns the red LED off
        redLed.off();

        ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
        exec.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                // turns the green LED on
                greenLed.on();

                log.debug("running publish state thread");

                int temp = -300;
                int humid = -300;

                reported.setTemperature(new Integer(temp).toString());
                reported.setHumidity(new Integer(humid).toString());

                try {
                    // reads the temperature and humidity data
                    Set<Sensor> sensors = Sensors.getSensors();
                    log.debug(sensors.size());

                    for (Sensor sensor : sensors) {
                        log.debug(sensor.getPhysicalQuantity());
                        log.debug(sensor.getValue());
                        if (sensor.getPhysicalQuantity().toString().equals("Temperature")) {
                            temp = sensor.getValue().intValue();
                        }
                        if (sensor.getPhysicalQuantity().toString().equals("Humidity")) {
                            humid = sensor.getValue().intValue();
                        }
                    }

                    log.debug("temperature: " + temp);
                    log.debug("humidity: " + humid);
                    reported.setTemperature(new Integer(temp).toString());
                    reported.setHumidity(new Integer(humid).toString());
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                try {
                    // reports current state - last temperature and humidity
                    // read
                    String message = gson.toJson(danboShadow);
                    MQTTPublisher updatePublisher = new MQTTPublisher(updateTopic, qos, message, url,
                            clientId + "-update" + rand.nextInt(100000), cleanSession, rootCA, privateKey,
                            certificate);
                    new Thread(updatePublisher).start();
                } catch (Exception e) {
                    log.error("an error has ocurred: " + e.getMessage());
                    e.printStackTrace();
                }

                // turns the green LED off
                greenLed.off();
            }
        }, 0, 5, TimeUnit.SECONDS); // runs this thread every 5 seconds,
        // with an initial delay of 5 seconds
    } catch (MqttException me) {
        // Display full details of any exception that occurs
        log.error("reason " + me.getReasonCode());
        log.error("msg " + me.getMessage());
        log.error("loc " + me.getLocalizedMessage());
        log.error("cause " + me.getCause());
        log.error("excep " + me);
        me.printStackTrace();
    } catch (Throwable th) {
        log.error("msg " + th.getMessage());
        log.error("loc " + th.getLocalizedMessage());
        log.error("cause " + th.getCause());
        log.error("excep " + th);
        th.printStackTrace();
    }
}

From source file:br.com.estudogrupo.principal.Principal.java

public static void main(String[] args) throws ParseException {
    Dicionario dicionario = new Dicionario();
    Dicionario1 dicionario1 = new Dicionario1();
    Dicionario2 dicionario2 = new Dicionario2();
    Dicionario3 dicionario3 = new Dicionario3();
    Dicionario4 dicionario4 = new Dicionario4();
    Dicionario5 dicionario5 = new Dicionario5();
    Dicionario6 dicionario6 = new Dicionario6();
    Dicionario7 dicionario7 = new Dicionario7();
    DicionarioSha1 dicionarioSha1 = new DicionarioSha1();
    DicionarioSha2 dicionarioSha2 = new DicionarioSha2();
    DicionarioSha3 dicionarioSha3 = new DicionarioSha3();
    DicionarioSha4 dicionarioSha4 = new DicionarioSha4();
    DicionarioSha5 dicionarioSha5 = new DicionarioSha5();
    DicionarioSha6 dicionarioSha6 = new DicionarioSha6();
    DicionarioSha7 dicionarioSha7 = new DicionarioSha7();
    DicionarioSha8 dicionarioSha8 = new DicionarioSha8();
    CommandLineParser parser = new PosixParser();
    Options options = new Options();
    options.addOption("m", "MD5", true, "Md5 hash");
    options.addOption("s", "SHA1", true, "Sha1 hash");
    options.addOption("b", "BASE64", true, "Base64 hash");
    options.addOption("l1", "Lista 1", true, "WordList");
    options.addOption("l2", "Lista 2", true, "WordList");
    options.addOption("l3", "Lista 3", true, "WordList");
    options.addOption("l4", "Lista 4", true, "WordList");
    options.addOption("l5", "Lista 5", true, "WordList");
    options.addOption("l6", "Lista 6", true, "WordList");
    options.addOption("l7", "Lista 7", true, "WordList");
    options.addOption("l8", "Lista 8", true, "WordList");
    options.addOption("oM", "ONLINE", true, "Busca md5 hash Online");
    int contador = 0;
    int contadodorSha = 0;
    CommandLine line = null;/* w  ww. ja  v a  2s  .  c  o m*/
    try {
        line = parser.parse(options, args);
    } catch (Exception e) {

    }

    try {
        if (line.hasOption("oM")) {
            String pegar = line.getOptionValue("oM");
            DicionarioOnline01 dicionarioOnline01 = new DicionarioOnline01();
            dicionarioOnline01.setRecebe(pegar);
            Thread t1Online = new Thread(dicionarioOnline01);
            t1Online.start();

            //Segunda Thread
            DicionarioOnline02 dicionarioOnline02 = new DicionarioOnline02();
            dicionarioOnline02.setRecebe(pegar);
            Thread t2Online = new Thread(dicionarioOnline02);
            t2Online.start();

            //Terceira Thread
            DicionarioOnline03 dicionarioOnline03 = new DicionarioOnline03();
            dicionarioOnline03.setRecebe(pegar);
            Thread t3Online = new Thread(dicionarioOnline03);
            t3Online.start();

            //Quarta Thread
            DicionarioOnline04 dicionarioOnline04 = new DicionarioOnline04();
            dicionarioOnline04.setRecebe(pegar);
            Thread t4Online = new Thread(dicionarioOnline04);
            t4Online.start();
            //Quinta Thread
            DicionarioOnline05 dicionarioOnline05 = new DicionarioOnline05();
            dicionarioOnline05.setRecebe(pegar);
            Thread t5Online = new Thread(dicionarioOnline05);
            t5Online.start();

            System.out.println(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                    + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                    + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n"
                    + "                                \n" + "            ");
            System.out.println("Executando...");

        } else if (line.hasOption('m')) {
            if (line.hasOption("l1")) {
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l1");
                dicionario.setRecebe(recebe);
                dicionario.setLista(lista);
                contador++;
                Thread t1 = new Thread(dicionario);

                t1.start();

            }
            if (line.hasOption("l2")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l2");
                dicionario1.setRecebe(recebe);
                dicionario1.setLista(lista);
                Thread t2 = new Thread(dicionario1);

                t2.start();

            }
            if (line.hasOption("l3")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l3");
                dicionario2.setRecebe(recebe);
                dicionario2.setLista(lista);
                Thread t3 = new Thread(dicionario2);

                t3.start();
            }
            if (line.hasOption("l4")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l3");
                dicionario3.setRecebe(recebe);
                dicionario3.setLista(lista);
                Thread t4 = new Thread(dicionario3);

                t4.start();

            }
            if (line.hasOption("l5")) {
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l5");
                dicionario4.setRecebe(recebe);
                dicionario4.setLista(lista);
                Thread t5 = new Thread(dicionario4);
                contador++;

                t5.start();

            }
            if (line.hasOption("l6")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l6");
                dicionario5.setRecebe(recebe);
                dicionario5.setLista(lista);
                Thread t6 = new Thread(dicionario5);

                t6.start();
            }
            if (line.hasOption("l7")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l7");
                dicionario6.setRecebe(recebe);
                dicionario6.setLista(lista);
                Thread t6 = new Thread(dicionario6);

                t6.start();
            }
            if (line.hasOption("l8")) {
                contador++;
                String recebe = line.getOptionValue('m');
                String lista = line.getOptionValue("l8");
                dicionario7.setRecebe(recebe);
                dicionario7.setLista(lista);
                Thread t7 = new Thread(dicionario7);

                t7.start();

            }
            if (contador > 0) {
                System.out.println(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n" + "                                \n"
                        + "            ");
                System.out.println("Executando...");
                contador = 0;

            }
        } else if (line.hasOption('s')) {
            if (line.hasOption("l1")) {
                contadodorSha++;
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l1");
                dicionarioSha1.setRecebe(pegar);
                dicionarioSha1.setLista(lista);
                Thread t1 = new Thread(dicionarioSha1);

                t1.start();
            } else if (line.hasOption("l2")) {
                contadodorSha++;
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l2");
                dicionarioSha2.setRecebe(pegar);
                dicionarioSha2.setLista(lista);
                Thread t2 = new Thread(dicionarioSha2);

                t2.start();
            } else if (line.hasOption("l3")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l3");
                dicionarioSha3.setRecebe(pegar);
                dicionarioSha3.setLista(lista);
                Thread t3 = new Thread(dicionarioSha3);
                contadodorSha++;
                t3.start();
            } else if (line.hasOption("l4")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l4");
                dicionarioSha4.setRecebe(pegar);
                dicionarioSha4.setLista(lista);
                Thread t4 = new Thread(dicionarioSha4);
                contadodorSha++;
                t4.start();
            } else if (line.hasOption("l5")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l5");
                dicionarioSha5.setRecebe(pegar);
                dicionarioSha5.setLista(lista);
                Thread t5 = new Thread(dicionarioSha5);
                contador++;
                t5.start();
            } else if (line.hasOption("l6")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l6");
                dicionarioSha6.setRecebe(pegar);
                dicionarioSha6.setLista(lista);
                Thread t6 = new Thread(dicionarioSha6);
                contadodorSha++;
                t6.start();
            } else if (line.hasOption("l7")) {
                String pegar = line.getOptionValue('s');
                String lista = line.getOptionValue("l7");
                dicionarioSha7.setRecebe(pegar);
                dicionarioSha7.setLista(lista);
                Thread t7 = new Thread(dicionarioSha7);
                contadodorSha++;
                t7.start();
            } else {
                HelpFormatter formatter = new HelpFormatter();
                formatter.printHelp(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n" + "                                \n"
                        + "   \n" + "                              \n" + "\n" + "\n" + "\n " + "\n", options);
            }
            if (contadodorSha > 0) {
                System.out.println(" _____        _____ _____ _   _ \n"
                        + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n" + "| |__) /  \\  | |  | || | |  \\| |\n"
                        + "|  ___/ /\\ \\ | |  | || | | . ` |\n" + "| |  / ____ \\| |__| || |_| |\\  |\n"
                        + "|_| /_/    \\_\\_____/_____|_| \\_|\n" + "                                \n"
                        + "            ");
                System.out.println("Executando...");
                contadodorSha = 0;
            }

        } else if (line.hasOption('b')) {
            String pegar = line.getOptionValue('b');
            System.out.println(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                    + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                    + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n"
                    + "                                \n" + "            ");
            System.out.println("executando...");
            byte[] decoder = Base64.decodeBase64(pegar.getBytes());
            System.out.println("Senha : " + new String(decoder));

        } else {
            HelpFormatter formatter = new HelpFormatter();
            formatter.printHelp(
                    " _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                            + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                            + "| |  / ____ \\| |__| || |_| |\\  |\n"
                            + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n" + "                                \n"
                            + "   \n" + "                              \n" + "\n" + "\n" + "\n " + "\n",
                    options);
        }

    } catch (NullPointerException e) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(" _____        _____ _____ _   _ \n" + "|  __ \\ /\\   |  __ \\_   _| \\ | |\n"
                + "| |__) /  \\  | |  | || | |  \\| |\n" + "|  ___/ /\\ \\ | |  | || | | . ` |\n"
                + "| |  / ____ \\| |__| || |_| |\\  |\n" + "|_| /_/    \\_\\_____/_____|_| \\_|\n\n\n"
                + "                                \n" + "   \n" + "                              \n" + "\n"
                + "\n" + "\n " + "\n", options);
    }

}

From source file:com.cloud.test.utils.TestClient.java

public static void main(String[] args) {
    String host = "http://localhost";
    String port = "8080";
    String testUrl = "/client/test";
    int numThreads = 1;

    try {//from w  w  w . j  a  v  a2  s  . c  o m
        // Parameters
        List<String> argsList = Arrays.asList(args);
        Iterator<String> iter = argsList.iterator();
        while (iter.hasNext()) {
            String arg = iter.next();
            // host
            if (arg.equals("-h")) {
                host = "http://" + iter.next();
            }

            if (arg.equals("-p")) {
                port = iter.next();
            }

            if (arg.equals("-t")) {
                numThreads = Integer.parseInt(iter.next());
            }

            if (arg.equals("-s")) {
                sleepTime = Long.parseLong(iter.next());
            }

            if (arg.equals("-c")) {
                cleanUp = Boolean.parseBoolean(iter.next());
                if (!cleanUp)
                    sleepTime = 0L; // no need to wait if we don't ever cleanup
            }

            if (arg.equals("-r")) {
                repeat = Boolean.parseBoolean(iter.next());
            }

            if (arg.equals("-u")) {
                numOfUsers = Integer.parseInt(iter.next());
            }

            if (arg.equals("-i")) {
                internet = Boolean.parseBoolean(iter.next());
            }
        }

        final String server = host + ":" + port + testUrl;
        s_logger.info("Starting test against server: " + server + " with " + numThreads + " thread(s)");
        if (cleanUp)
            s_logger.info("Clean up is enabled, each test will wait " + sleepTime + " ms before cleaning up");

        if (numOfUsers > 0) {
            s_logger.info("Pre-generating users for test of size : " + numOfUsers);
            users = new String[numOfUsers];
            Random ran = new Random();
            for (int i = 0; i < numOfUsers; i++) {
                users[i] = Math.abs(ran.nextInt()) + "-user";
            }
        }

        for (int i = 0; i < numThreads; i++) {
            new Thread(new Runnable() {
                public void run() {
                    do {
                        String username = null;
                        try {
                            long now = System.currentTimeMillis();
                            Random ran = new Random();
                            if (users != null) {
                                username = users[Math.abs(ran.nextInt()) % numOfUsers];
                            } else {
                                username = Math.abs(ran.nextInt()) + "-user";
                            }
                            NDC.push(username);

                            String url = server + "?email=" + username + "&password=" + username
                                    + "&command=deploy";
                            s_logger.info("Launching test for user: " + username + " with url: " + url);
                            HttpClient client = new HttpClient();
                            HttpMethod method = new GetMethod(url);
                            int responseCode = client.executeMethod(method);
                            boolean success = false;
                            String reason = null;
                            if (responseCode == 200) {
                                if (internet) {
                                    s_logger.info("Deploy successful...waiting 5 minute before SSH tests");
                                    Thread.sleep(300000L); // Wait 60 seconds so the linux VM can boot up.

                                    s_logger.info("Begin Linux SSH test");
                                    reason = sshTest(method.getResponseHeader("linuxIP").getValue());

                                    if (reason == null) {
                                        s_logger.info("Linux SSH test successful");
                                        s_logger.info("Begin Windows SSH test");
                                        reason = sshWinTest(method.getResponseHeader("windowsIP").getValue());
                                    }
                                }
                                if (reason == null) {
                                    if (internet) {
                                        s_logger.info("Windows SSH test successful");
                                    } else {
                                        s_logger.info("deploy test successful....now cleaning up");
                                        if (cleanUp) {
                                            s_logger.info(
                                                    "Waiting " + sleepTime + " ms before cleaning up vms");
                                            Thread.sleep(sleepTime);
                                        } else {
                                            success = true;
                                        }
                                    }
                                    if (users == null) {
                                        s_logger.info("Sending cleanup command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=cleanup";
                                    } else {
                                        s_logger.info("Sending stop DomR / destroy VM command");
                                        url = server + "?email=" + username + "&password=" + username
                                                + "&command=stopDomR";
                                    }
                                    method = new GetMethod(url);
                                    responseCode = client.executeMethod(method);
                                    if (responseCode == 200) {
                                        success = true;
                                    } else {
                                        reason = method.getStatusText();
                                    }
                                } else {
                                    // Just stop but don't destroy the VMs/Routers
                                    s_logger.info("SSH test failed with reason '" + reason + "', stopping VMs");
                                    url = server + "?email=" + username + "&password=" + username
                                            + "&command=stop";
                                    responseCode = client.executeMethod(new GetMethod(url));
                                }
                            } else {
                                // Just stop but don't destroy the VMs/Routers
                                reason = method.getStatusText();
                                s_logger.info("Deploy test failed with reason '" + reason + "', stopping VMs");
                                url = server + "?email=" + username + "&password=" + username + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            }

                            if (success) {
                                s_logger.info("***** Completed test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L) + " seconds");
                            } else {
                                s_logger.info("##### FAILED test for user : " + username + " in "
                                        + ((System.currentTimeMillis() - now) / 1000L)
                                        + " seconds with reason : " + reason);
                            }
                        } catch (Exception e) {
                            s_logger.warn("Error in thread", e);
                            try {
                                HttpClient client = new HttpClient();
                                String url = server + "?email=" + username + "&password=" + username
                                        + "&command=stop";
                                client.executeMethod(new GetMethod(url));
                            } catch (Exception e1) {
                            }
                        } finally {
                            NDC.clear();
                        }
                    } while (repeat);
                }
            }).start();
        }
    } catch (Exception e) {
        s_logger.error(e);
    }
}

From source file:framework.httpclient.nio.NHttpClient.java

public static void main(String[] args) throws Exception {
    // Create HTTP protocol processing chain
    HttpProcessor httpproc = HttpProcessorBuilder.create()
            // Use standard client-side protocol interceptors
            .add(new RequestContent()).add(new RequestTargetHost()).add(new RequestConnControl())
            .add(new RequestUserAgent("LinkedHashSetVsTreeSet/1.1")).add(new RequestExpectContinue(true))
            .build();/*w  w w.j a v a  2 s.c  om*/

    // Create client-side HTTP protocol handler
    HttpAsyncRequestExecutor protocolHandler = new HttpAsyncRequestExecutor();

    // Create client-side I/O event dispatch
    //   IO 
    final IOEventDispatch ioEventDispatch = new DefaultHttpClientIODispatch(protocolHandler,
            ConnectionConfig.DEFAULT);

    // Create client-side I/O reactor
    //   IO reactor
    final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor();

    // Create HTTP connection pool
    //  HTTP 
    BasicNIOConnPool pool = new BasicNIOConnPool(ioReactor, ConnectionConfig.DEFAULT);

    // Limit total number of connections to just two
    pool.setDefaultMaxPerRoute(2);
    pool.setMaxTotal(2);

    // Run the I/O reactor in a separate thread
    Thread t = new Thread(new Runnable() {

        public void run() {
            try {
                // Ready to go!
                ioReactor.execute(ioEventDispatch);
            } catch (InterruptedIOException ex) {
                System.err.println("Interrupted");
            } catch (IOException e) {
                System.err.println("I/O error: " + e.getMessage());
            }
            System.out.println("Shutdown");
        }

    });
    // Start the client thread
    t.start();

    // Create HTTP requester
    //  HTTP 
    HttpAsyncRequester requester = new HttpAsyncRequester(httpproc);

    // Execute HTTP GETs to the following hosts and
    HttpHost[] targets = new HttpHost[] { new HttpHost("www.baidu.org", -1, "https"),
            //            new HttpHost("www.zhihu.com", -1, "https"),
            new HttpHost("www.bilibili.com", -1, "https") };

    final CountDownLatch latch = new CountDownLatch(targets.length);

    for (final HttpHost target : targets) {
        BasicHttpRequest request = new BasicHttpRequest("GET", "/");
        HttpCoreContext coreContext = HttpCoreContext.create();
        requester.execute(new BasicAsyncRequestProducer(target, request), new BasicAsyncResponseConsumer(),
                pool, coreContext,
                // Handle HTTP response from a callback
                new FutureCallback<HttpResponse>() {

                    public void completed(final HttpResponse response) {
                        latch.countDown();
                        System.out.println(target + "->" + response.getStatusLine());
                    }

                    public void failed(final Exception ex) {
                        latch.countDown();
                        System.err.println(target + "->" + ex);
                        ex.printStackTrace();
                    }

                    public void cancelled() {
                        latch.countDown();
                        System.out.println(target + " cancelled");
                    }

                });
    }
    latch.await();
    System.out.println("Shutting down I/O reactor");
    ioReactor.shutdown();
    System.out.println("Done");
}

From source file:com.oberasoftware.robo.container.ServiceContainer.java

public static void main(String[] args) {
    LOG.info("Starting Robot Service Application container");

    SpringApplication springApplication = new SpringApplication(ServiceContainer.class);
    ConfigurableApplicationContext context = springApplication.run(args);

    Robot robot = new SpringAwareRobotBuilder("max", context).motionEngine(RoboPlusMotionEngine.class,
            //                        new RoboPlusClassPathResource("/bio_prm_humanoidtypea_en.mtn")
            new JsonMotionResource("/basic-animations.json"))
            //"/dev/ttyACM0
            //"/dev/tty.usbmodem1411
            .servoDriver(DynamixelServoDriver.class,
                    ImmutableMap.<String, String>builder()
                            .put(DynamixelServoDriver.PORT, "/dev/tty.usbmodem1431").build())
            .sensor(new ServoSensor("Test", "6"), ServoSensorDriver.class)
            .sensor(new ServoSensor("Hand", "5"), ServoSensorDriver.class)
            .sensor(new ServoSensor("HandYaw", "2"), ServoSensorDriver.class)
            .sensor(new ServoSensor("Walk", "17"), ServoSensorDriver.class)
            .sensor(new ServoSensor("WalkDirection", "13"), ServoSensorDriver.class)
            //                .sensor(new DistanceSensor("distance", "A0"), ADS1115Driver.class)
            //                .sensor(new GyroSensor("gyro", adsDriver.getPort("A2"), adsDriver.getPort("A3"), new AnalogToPercentageConverter()))
            .remote(RemoteCloudDriver.class).build();

    RobotEventHandler eventHandler = new RobotEventHandler(robot);
    robot.listen(eventHandler);//from  w w w .j  a  v a2  s  . c  om

    //        robot.getMotionEngine().runMotion("ArmInit");

    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOG.info("Killing the robot gracefully on shutdown");
        robot.shutdown();
    }));
}

From source file:com.heliosdecompiler.helios.bootloader.Bootloader.java

public static void main(String[] args) {
    try {//from   w  w  w  .j ava  2  s  .  c om
        if (!Constants.DATA_DIR.exists() && !Constants.DATA_DIR.mkdirs())
            throw new RuntimeException("Could not create data directory");
        if (!Constants.ADDONS_DIR.exists() && !Constants.ADDONS_DIR.mkdirs())
            throw new RuntimeException("Could not create addons directory");
        if (!Constants.SETTINGS_FILE.exists() && !Constants.SETTINGS_FILE.createNewFile())
            throw new RuntimeException("Could not create settings file");
        if (Constants.DATA_DIR.isFile())
            throw new RuntimeException("Data directory is file");
        if (Constants.ADDONS_DIR.isFile())
            throw new RuntimeException("Addons directory is file");
        if (Constants.SETTINGS_FILE.isDirectory())
            throw new RuntimeException("Settings file is directory");

        try {
            Class<?> clazz = Class.forName("org.eclipse.swt.widgets.Event");
            Object location = clazz.getProtectionDomain() != null
                    && clazz.getProtectionDomain().getCodeSource() != null
                            ? clazz.getProtectionDomain().getCodeSource().getLocation()
                            : "";
            throw new RuntimeException("SWT should not be loaded. Instead, it was loaded from " + location);
        } catch (ClassNotFoundException ignored) {
            loadSWTLibrary();
        }

        DisplayPumper displayPumper = new DisplayPumper();

        if (System.getProperty("os.name").toLowerCase().contains("mac")) {
            System.out.println("Attemting to force main thread");
            Executor executor;
            try {
                Class<?> dispatchClass = Class.forName("com.apple.concurrent.Dispatch");
                Object dispatchInstance = dispatchClass.getMethod("getInstance").invoke(null);
                executor = (Executor) dispatchClass.getMethod("getNonBlockingMainQueueExecutor")
                        .invoke(dispatchInstance);
            } catch (Throwable throwable) {
                throw new RuntimeException("Could not reflectively access Dispatch", throwable);
            }
            if (executor != null) {
                executor.execute(displayPumper);
            } else {
                throw new RuntimeException("Could not load executor");
            }
        } else {
            Thread pumpThread = new Thread(displayPumper);
            pumpThread.setName("Display Pumper");
            pumpThread.start();
        }
        while (!displayPumper.isReady())
            ;

        Display display = displayPumper.getDisplay();
        Shell shell = displayPumper.getShell();
        Splash splashScreen = new Splash(display);
        splashScreen.updateState(BootSequence.CHECKING_LIBRARIES);
        checkPackagedLibrary(splashScreen, "enjarify", Constants.ENJARIFY_VERSION,
                BootSequence.CHECKING_ENJARIFY, BootSequence.CLEANING_ENJARIFY, BootSequence.MOVING_ENJARIFY);
        checkPackagedLibrary(splashScreen, "Krakatau", Constants.KRAKATAU_VERSION,
                BootSequence.CHECKING_KRAKATAU, BootSequence.CLEANING_KRAKATAU, BootSequence.MOVING_KRAKATAU);

        try {
            if (!System.getProperty("os.name").toLowerCase().contains("linux")) {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            }
        } catch (Exception exception) { //Not important. No point notifying the user
        }

        Helios.main(args, shell, splashScreen);
        synchronized (displayPumper.getSynchronizer()) {
            displayPumper.getSynchronizer().wait();
        }
        System.exit(0);
    } catch (Throwable t) {
        displayError(t);
        System.exit(1);
    }
}

From source file:com.github.sdnwiselab.sdnwise.mote.standalone.Loader.java

/**
 * @param args the command line arguments
 *//*from   w w  w.  j a  v a  2 s . c o m*/
public static void main(final String[] args) {
    Options options = new Options();
    options.addOption(Option.builder("n").argName("net").hasArg().required().desc("Network ID of the node")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("a").argName("address").hasArg().required()
            .desc("Address of the node <0-65535>").numberOfArgs(1).build());
    options.addOption(Option.builder("p").argName("port").hasArg().required().desc("Listening UDP port")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("t").argName("filename").hasArg().required()
            .desc("Use given file for neighbors discovery").numberOfArgs(1).build());
    options.addOption(Option.builder("c").argName("ip:port").hasArg()
            .desc("IP address and TCP port of the controller. (SINK ONLY)").numberOfArgs(1).build());
    options.addOption(Option.builder("sp").argName("port").hasArg()
            .desc("Port number of the switch. (SINK ONLY)").numberOfArgs(1).build());
    options.addOption(Option.builder("sm").argName("mac").hasArg()
            .desc("MAC address of the switch. Example: <00:00:00:00:00:00>." + " (SINK ONLY)").numberOfArgs(1)
            .build());
    options.addOption(Option.builder("sd").argName("dpid").hasArg().desc("DPID of the switch (SINK ONLY)")
            .numberOfArgs(1).build());
    options.addOption(Option.builder("l").argName("level").hasArg()
            .desc("Use given log level. Values: SEVERE, WARNING, INFO, " + "CONFIG, FINE, FINER, FINEST.")
            .numberOfArgs(1).optionalArg(true).build());

    // create the parser
    CommandLineParser parser = new DefaultParser();
    try {
        CommandLine line = parser.parse(options, args);
        Thread th;

        byte cmdNet = (byte) Integer.parseInt(line.getOptionValue("n"));
        NodeAddress cmdAddress = new NodeAddress(Integer.parseInt(line.getOptionValue("a")));
        int cmdPort = Integer.parseInt(line.getOptionValue("p"));
        String cmdTopo = line.getOptionValue("t");

        String cmdLevel;

        if (!line.hasOption("l")) {
            cmdLevel = "SEVERE";
        } else {
            cmdLevel = line.getOptionValue("l");
        }

        if (line.hasOption("c")) {

            if (!line.hasOption("sd")) {
                throw new ParseException("-sd option missing");
            }
            if (!line.hasOption("sp")) {
                throw new ParseException("-sp option missing");
            }
            if (!line.hasOption("sm")) {
                throw new ParseException("-sm option missing");
            }

            String cmdSDpid = line.getOptionValue("sd");
            String cmdSMac = line.getOptionValue("sm");
            long cmdSPort = Long.parseLong(line.getOptionValue("sp"));
            String[] ipport = line.getOptionValue("c").split(":");
            th = new Thread(new Sink(cmdNet, cmdAddress, cmdPort,
                    new InetSocketAddress(ipport[0], Integer.parseInt(ipport[1])), cmdTopo, cmdLevel, cmdSDpid,
                    cmdSMac, cmdSPort));
        } else {
            th = new Thread(new Mote(cmdNet, cmdAddress, cmdPort, cmdTopo, cmdLevel));
        }
        th.start();
        th.join();
    } catch (InterruptedException | ParseException ex) {
        System.out.println("Parsing failed.  Reason: " + ex.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sdn-wise-data -n id -a address -p port"
                + " -t filename [-l level] [-sd dpid -sm mac -sp port]", options);
    }
}