Example usage for java.lang Thread start

List of usage examples for java.lang Thread start

Introduction

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

Prototype

public synchronized void start() 

Source Link

Document

Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.

Usage

From source file:ca.uqac.info.monitor.BeepBeepMonitor.java

public static void main(String[] args) {
    int verbosity = 1, slowdown = 0, tcp_port = 0;
    boolean show_stats = false, to_stdout = false;
    String trace_filename = "", pipe_filename = "", event_name = "message";
    final MonitorFactory mf = new MonitorFactory();

    // In case we open a socket
    ServerSocket m_serverSocket = null;
    Socket m_connection = null;//from  w  ww .ja  va 2s. com

    // Parse command line arguments
    Options options = setupOptions();
    CommandLine c_line = setupCommandLine(args, options);
    assert c_line != null;
    if (c_line.hasOption("verbosity")) {
        verbosity = Integer.parseInt(c_line.getOptionValue("verbosity"));
    }
    if (verbosity > 0) {
        showHeader();
    }
    if (c_line.hasOption("version")) {
        System.err.println("(C) 2008-2013 Sylvain Hall et al., Universit du Qubec  Chicoutimi");
        System.err.println("This program comes with ABSOLUTELY NO WARRANTY.");
        System.err.println("This is a free software, and you are welcome to redistribute it");
        System.err.println("under certain conditions. See the file COPYING for details.\n");
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("h")) {
        showUsage(options);
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("version")) {
        System.exit(ERR_OK);
    }
    if (c_line.hasOption("slowdown")) {
        slowdown = Integer.parseInt(c_line.getOptionValue("slowdown"));
        if (verbosity > 0)
            System.err.println("Slowdown factor: " + slowdown + " ms");
    }
    if (c_line.hasOption("stats")) {
        show_stats = true;
    }
    if (c_line.hasOption("csv")) {
        // Will output data in CSV format to stdout
        to_stdout = true;
    }
    if (c_line.hasOption("eventname")) {
        // Set event name
        event_name = c_line.getOptionValue("eventname");
    }
    if (c_line.hasOption("t")) {
        // Read events from a trace
        trace_filename = c_line.getOptionValue("t");
    }
    if (c_line.hasOption("p")) {
        // Read events from a pipe
        pipe_filename = c_line.getOptionValue("p");
    }
    if (c_line.hasOption("k")) {
        // Read events from a TCP port
        tcp_port = Integer.parseInt(c_line.getOptionValue("k"));
    }
    if (!trace_filename.isEmpty() && !pipe_filename.isEmpty()) {
        System.err.println("ERROR: you must specify at most one of trace file or named pipe");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    @SuppressWarnings("unchecked")
    List<String> remaining_args = c_line.getArgList();
    if (remaining_args.isEmpty()) {
        System.err.println("ERROR: no input formula specified");
        showUsage(options);
        System.exit(ERR_ARGUMENTS);
    }
    // Instantiate the event notifier
    boolean notify = (verbosity > 0);
    EventNotifier en = new EventNotifier(notify);
    en.m_slowdown = slowdown;
    en.m_csvToStdout = to_stdout;
    // Create one monitor for each input file and add it to the notifier 
    for (String formula_filename : remaining_args) {
        try {
            String formula_contents = FileReadWrite.readFile(formula_filename);
            Operator op = Operator.parseFromString(formula_contents);
            op.accept(mf);
            Monitor mon = mf.getMonitor();
            Map<String, String> metadata = getMetadata(formula_contents);
            metadata.put("Filename", formula_filename);
            en.addMonitor(mon, metadata);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(ERR_IO);
        } catch (Operator.ParseException e) {
            System.err.println("Error parsing input formula");
            System.exit(ERR_PARSE);
        }
    }

    // Read trace and iterate
    // Opens file
    PipeReader pr = null;
    try {
        if (!pipe_filename.isEmpty()) {
            // We tell the pipe reader we read a pipe
            File f = new File(pipe_filename);
            if (verbosity > 0)
                System.err.println("Reading from pipe named " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, false);
        } else if (!trace_filename.isEmpty()) {
            // We tell the pipe reader we read a regular file
            File f = new File(trace_filename);
            if (verbosity > 0)
                System.err.println("Reading from file " + f.getName());
            pr = new PipeReader(new FileInputStream(f), en, true);
        } else if (tcp_port > 0) {
            // We tell the pipe reader we read from a socket
            if (verbosity > 0)
                System.err.println("Reading from TCP port " + tcp_port);
            m_serverSocket = new ServerSocket(tcp_port);
            m_connection = m_serverSocket.accept();
            pr = new PipeReader(m_connection.getInputStream(), en, false);
        } else {
            // We tell the pipe reader we read from standard input
            if (verbosity > 0)
                System.err.println("Reading from standard input");
            pr = new PipeReader(System.in, en, false);
        }
    } catch (FileNotFoundException ex) {
        // We print both trace and pipe since one of them must be empty
        System.err.println("ERROR: file not found " + trace_filename + pipe_filename);
        System.exit(ERR_IO);
    } catch (IOException e) {
        // Caused by socket error
        e.printStackTrace();
        System.exit(ERR_IO);
    }
    pr.setSeparator("<" + event_name + ">", "</" + event_name + ">");

    // Check parameters for the event notifier
    if (c_line.hasOption("no-trigger")) {
        en.m_notifyOnVerdict = false;
    } else {
        en.m_notifyOnVerdict = true;
    }
    if (c_line.hasOption("mirror")) {
        en.m_mirrorEventsOnStdout = true;
    }

    // Start event notifier
    en.reset();
    Thread th = new Thread(pr);
    long clock_start = System.nanoTime();
    th.start();
    try {
        th.join(); // Wait for thread to finish
    } catch (InterruptedException e1) {
        // Thread is finished
    }
    if (tcp_port > 0 && m_serverSocket != null) {
        // We opened a socket; now we close it
        try {
            m_serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    long clock_end = System.nanoTime();
    int ret_code = pr.getReturnCode();
    switch (ret_code) {
    case PipeReader.ERR_EOF:
        if (verbosity > 0)
            System.err.println("\nEnd of file reached");
        break;
    case PipeReader.ERR_EOT:
        if (verbosity > 0)
            System.err.println("\nEOT received on pipe: closing");
        break;
    case PipeReader.ERR_OK:
        // Do nothing
        break;
    default:
        // An error
        System.err.println("Runtime error");
        System.exit(ERR_RUNTIME);
        break;
    }
    if (show_stats) {
        if (verbosity > 0) {
            System.out.println("Messages:   " + en.m_numEvents);
            System.out.println("Time:       " + (int) (en.m_totalTime / 1000000f) + " ms");
            System.out.println("Clock time: " + (int) ((clock_end - clock_start) / 1000000f) + " ms");
            System.out.println("Max heap:   " + (int) (en.heapSize / 1048576f) + " MB");
        } else {
            // If stats are asked but verbosity = 0, only show time value
            // (both monitor and wall clock) 
            System.out.print((int) (en.m_totalTime / 1000000f));
            System.out.print(",");
            System.out.print((int) ((clock_end - clock_start) / 1000000f));
        }
    }
    System.exit(ERR_OK);
}

From source file:ffx.numerics.fft.RowMajorComplex3DCuda.java

/**
 * <p>//  w  w  w.j  a v  a 2 s  .c om
 * main</p>
 *
 * @param args an array of {@link java.lang.String} objects.
 * @throws java.lang.Exception if any.
 */
public static void main(String[] args) throws Exception {
    int dimNotFinal = 64;
    int reps = 10;
    if (args != null) {
        try {
            dimNotFinal = Integer.parseInt(args[0]);
            if (dimNotFinal < 1) {
                dimNotFinal = 64;
            }
            reps = Integer.parseInt(args[2]);
            if (reps < 1) {
                reps = 5;
            }
        } catch (Exception e) {
        }
    }
    final int dim = dimNotFinal;

    System.out.println(String.format(
            " Initializing a %d cubed grid.\n" + " The best timing out of %d repititions will be used.", dim,
            reps));

    final int dimCubed = dim * dim * dim;

    /**
     * Create an array to save the initial input and result.
     */
    double orig[] = new double[dimCubed];
    double answer[] = new double[dimCubed];

    double data[] = new double[dimCubed * 2];
    double recip[] = new double[dimCubed];

    Random random = new Random(1);
    for (int x = 0; x < dim; x++) {
        for (int y = 0; y < dim; y++) {
            for (int z = 0; z < dim; z++) {
                int index = RowMajorComplex3D.iComplex3D(x, y, z, dim, dim);
                orig[index / 2] = random.nextDouble();
                recip[index / 2] = orig[index / 2];
            }
        }
    }

    RowMajorComplex3D complex3D = new RowMajorComplex3D(dim, dim, dim);
    RowMajorComplex3DParallel complex3DParallel = new RowMajorComplex3DParallel(dim, dim, dim,
            new ParallelTeam(), IntegerSchedule.fixed());
    RowMajorComplex3DCuda complex3DCUDA = new RowMajorComplex3DCuda(dim, dim, dim, data, recip);
    Thread cudaThread = new Thread(complex3DCUDA);

    cudaThread.setPriority(Thread.MAX_PRIORITY);
    cudaThread.start();

    double toSeconds = 0.000000001;
    long parTime = Long.MAX_VALUE;
    long seqTime = Long.MAX_VALUE;
    long clTime = Long.MAX_VALUE;

    complex3D.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3D.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Sequential: %8.3f", i + 1, toSeconds * time));
        if (time < seqTime) {
            seqTime = time;
        }
    }

    for (int j = 0; j < dimCubed; j++) {
        answer[j] = data[j * 2];
    }

    complex3DParallel.setRecip(recip);
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DParallel.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d Parallel:   %8.3f", i + 1, toSeconds * time));
        if (time < parTime) {
            parTime = time;
        }
    }

    double maxError = Double.MIN_VALUE;
    double rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs(answer[i] - data[2 * i]);
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" Parallel RMSE:   %12.10f, Max: %12.10f", rmse, maxError));
    for (int i = 0; i < reps; i++) {
        for (int j = 0; j < dimCubed; j++) {
            data[j * 2] = orig[j];
            data[j * 2 + 1] = 0.0;
        }
        long time = System.nanoTime();
        complex3DCUDA.convolution(data);
        time = (System.nanoTime() - time);
        System.out.println(String.format(" %2d CUDA:     %8.3f", i + 1, toSeconds * time));
        if (time < clTime) {
            clTime = time;
        }
    }

    maxError = Double.MIN_VALUE;
    double avg = 0.0;
    rmse = 0.0;
    for (int i = 0; i < dimCubed; i++) {
        double error = Math.abs((answer[i] - data[2 * i]) / dimCubed);
        avg += error;
        if (error > maxError) {
            maxError = error;
        }
        rmse += error * error;
    }
    rmse /= dimCubed;
    avg /= dimCubed;
    rmse = Math.sqrt(rmse);
    logger.info(String.format(" CUDA RMSE:   %12.10f, Max: %12.10f, Avg: %12.10f", rmse, maxError, avg));

    complex3DCUDA.free();
    complex3DCUDA = null;

    System.out.println(String.format(" Best Sequential Time:  %8.3f", toSeconds * seqTime));
    System.out.println(String.format(" Best Parallel Time:    %8.3f", toSeconds * parTime));
    System.out.println(String.format(" Best CUDA Time:        %8.3f", toSeconds * clTime));
    System.out.println(String.format(" Parallel Speedup: %15.5f", (double) seqTime / parTime));
    System.out.println(String.format(" CUDA Speedup:     %15.5f", (double) seqTime / clTime));
}

From source file:javarestart.JavaRestartLauncher.java

public static void main(String[] args) throws Exception {
    if (args.length < 1) {
        System.out.println("Usage: <URL> {<MainClass>}");
        return;// w  ww  .  ja v  a  2 s .c  o  m
    }

    if (args[0].equals("fork")) {
        String[] args2 = new String[args.length - 1];
        for (int i = 0; i < args.length - 1; i++) {
            args2[i] = args[i + 1];
        }
        fork(args2);
        return;
    }

    AppClassloader loader = new AppClassloader(args[0]);
    Thread.currentThread().setContextClassLoader(loader);
    String main;
    JSONObject obj = getJSON(args[0]);
    if (args.length < 2) {
        main = (String) obj.get("main");
    } else {
        main = args[1];
    }

    String splash = (String) obj.get("splash");
    if (splash != null) {
        SplashScreen scr = SplashScreen.getSplashScreen();
        if (scr != null) {
            URL url = loader.getResource(splash);
            scr.setImageURL(url);
        }
    }

    //auto close splash after 45 seconds
    Thread splashClose = new Thread() {
        @Override
        public void run() {
            try {
                sleep(45000);
            } catch (InterruptedException e) {
            }
            SplashScreen scr = SplashScreen.getSplashScreen();
            if ((scr != null) && (scr.isVisible())) {
                scr.close();
            }
        }
    };
    splashClose.setDaemon(true);
    splashClose.start();

    Class mainClass = loader.loadClass(main);
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.setAccessible(true);
    mainMethod.invoke(null, new Object[] { new String[0] });
}

From source file:Main.java

public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p = new JPanel();
    p.setOpaque(true);//  w  ww  .j  a v  a2 s.c  o m
    p.setLayout(new FlowLayout());
    p.add(good);

    f.add(p, BorderLayout.CENTER);
    f.add(resultLabel, BorderLayout.SOUTH);
    good.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ev) {
            resultLabel.setText("Working . . .");
            good.setEnabled(false);
            Thread worker = new Thread() {
                public void run() {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException ex) {
                    }
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            resultLabel.setText("Ready");
                            good.setEnabled(true);
                        }
                    });
                }
            };
            worker.start(); // So we don't hold up the dispatch thread.
        }
    });
    f.setSize(300, 100);
    f.setVisible(true);
}

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.j  a  v  a 2s . c om
    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:org.opencastproject.loadtest.engage.Main.java

/** Runs the load testing against an engage server. **/
public static void main(String[] args) throws Exception {
    // Create the default settings for the GUI interaction such as user/pass and field names.
    GuiSettings guiSettings = new GuiSettings();
    // Set the default browser to use as Firefox.
    BrowserToUse browserToUse = BrowserToUse.Firefox;
    // Create command line options.
    Options options = createOptions();//w ww  .j av  a 2  s .com
    // Parse the command line options.
    CommandLineParser parser = new PosixParser();
    CommandLine line = null;
    try {
        line = parser.parse(options, args);
    } catch (ParseException e) {
        System.err.println("Parsing commandline failed: " + e.getMessage());
        System.exit(1);
    }

    if (line.hasOption(ENGAGE_URL_KEY)) {
        engageServerURL = line.getOptionValue(ENGAGE_URL_KEY);
    }
    if (line.hasOption(DIGEST_USERNAME_KEY)) {
        digestUsername = line.getOptionValue(DIGEST_USERNAME_KEY);
    }
    if (line.hasOption(DIGEST_PASSWORD_KEY)) {
        digestPassword = line.getOptionValue(DIGEST_PASSWORD_KEY);
    }

    // Get settings for interacting with the gui.
    if (line.hasOption(GUI_USERNAME_KEY)) {
        guiSettings.setUsername(line.getOptionValue(GUI_USERNAME_KEY));
    }
    if (line.hasOption(GUI_PASSWORD_KEY)) {
        guiSettings.setPassword(line.getOptionValue(GUI_PASSWORD_KEY));
    }
    if (line.hasOption(GUI_USERNAME_FIELDNAME_KEY)) {
        guiSettings.setUsernameFieldName(line.getOptionValue(GUI_USERNAME_FIELDNAME_KEY));
    }
    if (line.hasOption(GUI_PASSWORD_FIELDNAME_KEY)) {
        guiSettings.setPasswordFieldName(line.getOptionValue(GUI_PASSWORD_FIELDNAME_KEY));
    }

    if (line.hasOption(BROWSER_NUMBER_KEY)) {
        numberOfBrowsers = Integer.parseInt(line.getOptionValue(BROWSER_NUMBER_KEY));
    }
    if (line.hasOption(WATCH_TIME_KEY)) {
        timeToWatchVideo = Integer.parseInt(line.getOptionValue(WATCH_TIME_KEY));
    }

    if (line.hasOption(WITH_CHROME_KEY)) {
        browserToUse = BrowserToUse.Chrome;
    }
    if (line.hasOption(WITH_IE_KEY)) {
        browserToUse = BrowserToUse.IE;
    }
    if (line.hasOption(WITH_SAFARI_KEY)) {
        browserToUse = BrowserToUse.Safari;
    }
    if (line.hasOption(WITH_FIREFOX_KEY)) {
        browserToUse = BrowserToUse.Firefox;
    }

    if (line.hasOption(HELP_KEY)) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("java -jar matterhorn-load-test-engage-<version>-jar-with-dependencies.jar>",
                options);
        System.exit(0);
    }

    LinkedList<String> episodeList = getListOfEpisodes();

    if (episodeList == null || episodeList.size() <= 0) {
        logger.error("You need at least one episode in the engage player to run this load test. ");
        System.exit(0);
    }

    // Create browsers to run test.
    LoadTestEngage loadTestEngage = null;
    Thread thread = null;
    for (int i = 0; i < numberOfBrowsers; i++) {
        loadTestEngage = new LoadTestEngage("Browser " + i, engageServerURL, episodeList, timeToWatchVideo,
                guiSettings, browserToUse);
        thread = new Thread(loadTestEngage);
        thread.start();
    }
}

From source file:org.sourcepit.docker.watcher.Main.java

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

    final HttpClientFactory clientFactory = new HttpClientFactory() {
        @Override/*from   w  ww  .  j a  v  a2 s.  co m*/
        public CloseableHttpClient createHttpClient() {
            return HttpClients.createDefault();
        }
    };

    final String dockerDaemonUri = "http://192.168.56.101:2375";
    final String consulAgentUri = "http://192.168.56.101:8500";

    final BlockingQueue<List<JsonObject>> queue = new LinkedBlockingQueue<>();

    final ConsulForwarder consulForwarder = new ConsulForwarder(clientFactory.createHttpClient(),
            consulAgentUri);

    final Thread containerStateDispatcher = new Thread("Consul Forwarder") {
        @Override
        public void run() {
            while (true) {
                try {
                    consulForwarder.forward(queue.take());
                } catch (InterruptedException e) {
                    break;
                } catch (Exception e) {
                    LOG.error("Error while forwarding Docker container state to Consul.", e);
                }
            }
        }
    };
    containerStateDispatcher.start();

    final DockerWatcher watcher = new DockerWatcher(clientFactory, dockerDaemonUri) {
        @Override
        protected void handle(List<JsonObject> containerState) {
            queue.add(containerState);
        }
    };

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            watcher.stop();
            while (containerStateDispatcher.isAlive()) {
                containerStateDispatcher.interrupt();
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                }
            }
        }
    });

    watcher.start();
}

From source file:TableFillThread.java

public static void main(String[] args) {
    final Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setText("Lazy Table");
    shell.setLayout(new FillLayout());
    final Table table = new Table(shell, SWT.BORDER | SWT.MULTI);
    table.setSize(200, 200);//from  w ww .j av a2s . c om

    Thread thread = new Thread() {
        public void run() {
            for (int i = 0; i < 20000; i++) {
                final int[] index = new int[] { i };
                display.syncExec(new Runnable() {
                    public void run() {
                        if (table.isDisposed())
                            return;
                        TableItem item = new TableItem(table, SWT.NONE);
                        item.setText("Table Item " + index[0]);
                    }
                });
            }
        }
    };
    thread.start();
    shell.setSize(200, 200);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:asl.seedscan.SeedScan.java

public static void main(String args[]) {
    // Default locations of config and schema files
    File configFile = new File("config.xml");
    File schemaFile = new File("schemas/SeedScanConfig.xsd");
    boolean parseConfig = true;

    ArrayList<File> schemaFiles = new ArrayList<File>();
    schemaFiles.add(schemaFile);//  w  ww. ja  va2 s .  c  o  m

    // ==== Command Line Parsing ====
    Options options = new Options();
    Option opConfigFile = new Option("c", "config-file", true,
            "The config file to use for seedscan. XML format according to SeedScanConfig.xsd.");
    Option opSchemaFile = new Option("s", "schema-file", true,
            "The xsd schema file which should be used to verify the config file format. ");

    OptionGroup ogConfig = new OptionGroup();
    ogConfig.addOption(opConfigFile);

    OptionGroup ogSchema = new OptionGroup();
    ogConfig.addOption(opSchemaFile);

    options.addOptionGroup(ogConfig);
    options.addOptionGroup(ogSchema);

    PosixParser optParser = new PosixParser();
    CommandLine cmdLine = null;
    try {
        cmdLine = optParser.parse(options, args, true);
    } catch (org.apache.commons.cli.ParseException e) {
        logger.error("Error while parsing command-line arguments.");
        System.exit(1);
    }

    Option opt;
    Iterator<?> iter = cmdLine.iterator();
    while (iter.hasNext()) {
        opt = (Option) iter.next();
        if (opt.getOpt().equals("c")) {
            configFile = new File(opt.getValue());
        } else if (opt.getOpt().equals("s")) {
            schemaFile = new File(opt.getValue());
        }
    }

    // ==== Configuration Read and Parse Actions ====
    ConfigParser parser = new ConfigParser(schemaFiles);
    ConfigT config = parser.parseConfig(configFile);

    // Print out configuration file contents
    Formatter formatter = new Formatter(new StringBuilder(), Locale.US);

    // ===== CONFIG: LOCK FILE =====
    File lockFile = new File(config.getLockfile());
    logger.info("SeedScan lock file is '" + lockFile + "'");
    LockFile lock = new LockFile(lockFile);
    if (!lock.acquire()) {
        logger.error("Could not acquire lock.");
        System.exit(1);
    }

    // ===== CONFIG: LOGGING =====
    // MTH: This is now done in log4j.properties file

    // ===== CONFIG: DATABASE =====
    MetricDatabase readDB = new MetricDatabase(config.getDatabase());
    MetricDatabase writeDB = new MetricDatabase(config.getDatabase());
    MetricReader reader = new MetricReader(readDB);
    MetricInjector injector = new MetricInjector(writeDB);

    // ===== CONFIG: SCANS =====
    Hashtable<String, Scan> scans = new Hashtable<String, Scan>();
    if (config.getScans().getScan() == null) {
        logger.error("No scans in configuration.");
        System.exit(1);
    } else {
        for (ScanT scanCfg : config.getScans().getScan()) {
            String name = scanCfg.getName();
            if (scans.containsKey(name)) {
                logger.error("Duplicate scan name '" + name + "' encountered.");
                System.exit(1);
            }

            // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd
            if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) {
                logger.error(
                        "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!");
                System.exit(1);
            }

            // Configure this Scan
            Scan scan = new Scan(scanCfg.getName());
            scan.setPathPattern(scanCfg.getPath());
            scan.setDatalessDir(scanCfg.getDatalessDir());
            scan.setEventsDir(scanCfg.getEventsDir());
            scan.setPlotsDir(scanCfg.getPlotsDir());
            scan.setDaysToScan(scanCfg.getDaysToScan().intValue());
            if (scanCfg.getStartDay() != null) {
                scan.setStartDay(scanCfg.getStartDay().intValue());
            }
            if (scanCfg.getStartDate() != null) {
                scan.setStartDate(scanCfg.getStartDate().intValue());
            }

            if (scanCfg.getNetworkSubset() != null) {
                logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset());
                Filter filter = new Filter(false);
                for (String network : scanCfg.getNetworkSubset().split(",")) {
                    logger.debug("Network =[{}]", network);
                    filter.addFilter(network);
                }
                scan.setNetworks(filter);
            }
            if (scanCfg.getStationSubset() != null) {
                logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset());
                Filter filter = new Filter(false);
                for (String station : scanCfg.getStationSubset().split(",")) {
                    logger.debug("Station =[{}]", station);
                    filter.addFilter(station);
                }
                scan.setStations(filter);
            }
            if (scanCfg.getLocationSubset() != null) {
                logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset());
                Filter filter = new Filter(false);
                for (String location : scanCfg.getLocationSubset().split(",")) {
                    logger.debug("Location =[{}]", location);
                    filter.addFilter(location);
                }
                scan.setLocations(filter);
            }
            if (scanCfg.getChannelSubset() != null) {
                logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset());
                Filter filter = new Filter(false);
                for (String channel : scanCfg.getChannelSubset().split(",")) {
                    logger.debug("Channel =[{}]", channel);
                    filter.addFilter(channel);
                }
                scan.setChannels(filter);
            }

            for (MetricT met : scanCfg.getMetrics().getMetric()) {
                try {
                    Class<?> metricClass = Class.forName(met.getClassName());
                    MetricWrapper wrapper = new MetricWrapper(metricClass);
                    for (ArgumentT arg : met.getArgument()) {
                        wrapper.add(arg.getName(), arg.getValue());
                    }
                    scan.addMetric(wrapper);
                } catch (ClassNotFoundException ex) {
                    logger.error("No such metric class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (InstantiationException ex) {
                    logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (IllegalAccessException ex) {
                    logger.error("Illegal access while loading class '" + met.getClassName() + "'");
                    System.exit(1);
                } catch (NoSuchFieldException ex) {
                    logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'");
                    System.exit(1);
                }

            }
            scans.put(name, scan);
        }
    }

    // ==== Establish Database Connection ====
    // TODO: State Tracking in the Database
    // - Record scan started in database.
    // - Track our progress as we go so a new process can pick up where
    //   we left off if our process dies.
    // - Mark when each date-station-channel-operation is complete
    //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get

    // For each day ((yesterday - scanDepth) to yesterday)
    // scan for these channel files, only process them if
    // they have not yet been scanned, or if changes have
    // occurred to the file since its last scan. Do this for
    // each scan type. Do not re-scan data for each type,
    // launch processes for each scan and use the same data set
    // for each. If we can pipe the data as it is read, do so.
    // If we need to push all of it at once, do these in sequence
    // in order to preserve overall system memory resources.

    Scan scan = null;

    // ==== Perform Scans ====

    scan = scans.get("daily");

    //MTH: This part could/should be moved up higher except that we need to know datalessDir, which,
    //     at this point, is configured on a per scan basis ... so we need to know what scan we're doing
    MetaServer metaServer = null;
    if (config.getMetaserver() != null) {
        if (config.getMetaserver().getUseRemote().equals("yes")
                || config.getMetaserver().getUseRemote().equals("true")) {
            String remoteServer = config.getMetaserver().getRemoteUri();
            try {
                metaServer = new MetaServer(new URI(remoteServer));
            } catch (Exception e) {
                logger.error("caught URI exception:" + e.getMessage());
            }
        } else {
            metaServer = new MetaServer(scan.getDatalessDir());
        }
    } else { // Use local MetaServer
        metaServer = new MetaServer(scan.getDatalessDir());
    }

    List<Station> stations = null;

    if (config.getStationList() == null) { // get StationList from MetaServer
        logger.info("Get StationList from MetaServer");
        stations = metaServer.getStationList();
    } else { // read StationList from config.xml
        logger.info("Read StationList from config.xml");
        List<String> stationList = config.getStationList().getStation();
        if (stationList.size() > 0) {
            stations = new ArrayList<Station>();
            for (String station : stationList) {
                String[] words = station.split("_");
                if (words.length != 2) {
                    logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip",
                            station));
                } else {
                    stations.add(new Station(words[0], words[1]));
                    logger.info("config.xml: Read station:" + station);
                }
            }
        } else {
            logger.error("Error: No valid stations read from config.xml");
        }
    }

    if (stations == null) {
        logger.error("Found NO stations to scan --> EXITTING SeedScan");
        System.exit(1);
    }

    Thread readerThread = new Thread(reader);
    readerThread.start();
    logger.info("Reader thread started.");

    Thread injectorThread = new Thread(injector);
    injectorThread.start();
    logger.info("Injector thread started.");

    // Loop over scans and hand each one to a ScanManager
    logger.info("Hand scan to ScanManager");
    for (String key : scans.keySet()) {
        scan = scans.get(key);
        logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(),
                scan.getStartDate(), scan.getDaysToScan()));
        ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer);
    }

    logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads");

    try {
        injector.halt();
        logger.info("All stations processed. Waiting for injector thread to finish...");
        synchronized (injectorThread) {
            //injectorThread.wait();
            injectorThread.interrupt();
        }
        logger.info("Injector thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The injector thread was interrupted while attempting to complete requests.");
    }

    try {
        reader.halt();
        logger.info("All stations processed. Waiting for reader thread to finish...");
        synchronized (readerThread) {
            //readerThread.wait();
            readerThread.interrupt();
        }
        logger.info("Reader thread halted.");
    } catch (InterruptedException ex) {
        logger.warn("The reader thread was interrupted while attempting to complete requests.");
    }

    try {
        lock.release();
    } catch (IOException e) {
        ;
    } finally {
        logger.info("Release seedscan lock and quit metaServer");
        lock = null;
        metaServer.quit();
    }
}

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

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

    WeldContainer container = weld.initialize();

    HardwareTestCommandServer roloCommandServer = container.instance().select(HardwareTestCommandServer.class)
            .get();/*from w  ww.  ja  va2s  .c om*/

    // 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 {
        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 !");
            readDistanceSensors = false;
            readLightSensors = false;
            readTouchSensors = false;
        }
    });

}