Example usage for java.util Timer schedule

List of usage examples for java.util Timer schedule

Introduction

In this page you can find the example usage for java.util Timer schedule.

Prototype

public void schedule(TimerTask task, Date time) 

Source Link

Document

Schedules the specified task for execution at the specified time.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {

    Date timeToRun = new Date(System.currentTimeMillis() + numberOfMillisecondsInTheFuture);
    Timer timer = new Timer();

    timer.schedule(new TimerTask() {
        public void run() {
            System.out.println("doing");
        }/*www. j a  va  2  s  .  c o m*/
    }, timeToRun);
}

From source file:MyTimerTask.java

public static void main(String[] args) {
    // creating timer task, timer
    TimerTask tasknew = new MyTimerTask();
    Timer timer = new Timer();

    // scheduling the task
    timer.schedule(tasknew, new Date());
}

From source file:MyTimerTask.java

public static void main(String[] args) {
    // creating timer task, timer
    TimerTask tasknew = new MyTimerTask();
    Timer timer = new Timer();

    // scheduling the task at interval
    timer.schedule(tasknew, 100);
}

From source file:Main.java

public static void main(String args[]) {
    final JFrame frame = new JFrame();
    Container contentPane = frame.getContentPane();
    JButton b = new JButton("Hide for 5");
    ActionListener action = new ActionListener() {
        public void actionPerformed(ActionEvent actionEvent) {
            frame.setVisible(false);// w  w  w. ja va 2 s  . c  om
            TimerTask task = new TimerTask() {
                public void run() {
                    frame.setVisible(true);
                }
            };
            Timer timer = new Timer();
            timer.schedule(task, 5000);
        }
    };
    b.addActionListener(action);
    AncestorListener ancestor = new AncestorListener() {
        public void ancestorAdded(AncestorEvent e) {
            System.out.println("Added");
            dumpInfo(e);
        }

        public void ancestorMoved(AncestorEvent e) {
            System.out.println("Moved");
            dumpInfo(e);
        }

        public void ancestorRemoved(AncestorEvent e) {
            System.out.println("Removed");
            dumpInfo(e);
        }

        private void dumpInfo(AncestorEvent e) {
            System.out.println("\tAncestor: " + name(e.getAncestor()));
            System.out.println("\tAncestorParent: " + name(e.getAncestorParent()));
            System.out.println("\tComponent: " + name(e.getComponent()));
        }

        private String name(Container c) {
            return (c == null) ? null : c.getName();
        }
    };
    b.addAncestorListener(ancestor);
    contentPane.add(b, BorderLayout.NORTH);
    frame.setSize(300, 200);
    frame.setVisible(true);
}

From source file:org.apache.bookkeeper.benchmark.TestClient.java

/**
 * First says if entries should be written to BookKeeper (0) or to the local
 * disk (1). Second parameter is an integer defining the length of a ledger entry.
 * Third parameter is the number of writes.
 *
 * @param args//from  w w w. j a  v a  2  s  .c  om
 */
public static void main(String[] args) throws ParseException {
    Options options = new Options();
    options.addOption("length", true, "Length of packets being written. Default 1024");
    options.addOption("target", true, "Target medium to write to. Options are bk, fs & hdfs. Default fs");
    options.addOption("runfor", true, "Number of seconds to run for. Default 60");
    options.addOption("path", true, "Path to write to. fs & hdfs only. Default /foobar");
    options.addOption("zkservers", true,
            "ZooKeeper servers, comma separated. bk only. Default localhost:2181.");
    options.addOption("bkensemble", true, "BookKeeper ledger ensemble size. bk only. Default 3");
    options.addOption("bkquorum", true, "BookKeeper ledger quorum size. bk only. Default 2");
    options.addOption("bkthrottle", true, "BookKeeper throttle size. bk only. Default 10000");
    options.addOption("sync", false, "Use synchronous writes with BookKeeper. bk only.");
    options.addOption("numconcurrent", true, "Number of concurrently clients. Default 1");
    options.addOption("timeout", true, "Number of seconds after which to give up");
    options.addOption("help", false, "This message");

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

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("TestClient <options>", options);
        System.exit(-1);
    }

    int length = Integer.parseInt(cmd.getOptionValue("length", "1024"));
    String target = cmd.getOptionValue("target", "fs");
    long runfor = Long.parseLong(cmd.getOptionValue("runfor", "60")) * 1000;

    StringBuilder sb = new StringBuilder();
    while (length-- > 0) {
        sb.append('a');
    }

    Timer timeouter = new Timer();
    if (cmd.hasOption("timeout")) {
        final long timeout = Long.parseLong(cmd.getOptionValue("timeout", "360")) * 1000;

        timeouter.schedule(new TimerTask() {
            public void run() {
                System.err.println("Timing out benchmark after " + timeout + "ms");
                System.exit(-1);
            }
        }, timeout);
    }

    BookKeeper bkc = null;
    try {
        int numFiles = Integer.parseInt(cmd.getOptionValue("numconcurrent", "1"));
        int numThreads = Math.min(numFiles, 1000);
        byte[] data = sb.toString().getBytes(UTF_8);
        long runid = System.currentTimeMillis();
        List<Callable<Long>> clients = new ArrayList<Callable<Long>>();

        if (target.equals("bk")) {
            String zkservers = cmd.getOptionValue("zkservers", "localhost:2181");
            int bkensemble = Integer.parseInt(cmd.getOptionValue("bkensemble", "3"));
            int bkquorum = Integer.parseInt(cmd.getOptionValue("bkquorum", "2"));
            int bkthrottle = Integer.parseInt(cmd.getOptionValue("bkthrottle", "10000"));

            ClientConfiguration conf = new ClientConfiguration();
            conf.setThrottleValue(bkthrottle);
            conf.setZkServers(zkservers);

            bkc = new BookKeeper(conf);
            List<LedgerHandle> handles = new ArrayList<LedgerHandle>();
            for (int i = 0; i < numFiles; i++) {
                handles.add(bkc.createLedger(bkensemble, bkquorum, DigestType.CRC32, new byte[] { 'a', 'b' }));
            }
            for (int i = 0; i < numFiles; i++) {
                clients.add(new BKClient(handles, data, runfor, cmd.hasOption("sync")));
            }
        } else if (target.equals("hdfs")) {
            FileSystem fs = FileSystem.get(new Configuration());
            LOG.info("Default replication for HDFS: {}", fs.getDefaultReplication());

            List<FSDataOutputStream> streams = new ArrayList<FSDataOutputStream>();
            for (int i = 0; i < numFiles; i++) {
                String path = cmd.getOptionValue("path", "/foobar");
                streams.add(fs.create(new Path(path + runid + "_" + i)));
            }

            for (int i = 0; i < numThreads; i++) {
                clients.add(new HDFSClient(streams, data, runfor));
            }
        } else if (target.equals("fs")) {
            List<FileOutputStream> streams = new ArrayList<FileOutputStream>();
            for (int i = 0; i < numFiles; i++) {
                String path = cmd.getOptionValue("path", "/foobar " + i);
                streams.add(new FileOutputStream(path + runid + "_" + i));
            }

            for (int i = 0; i < numThreads; i++) {
                clients.add(new FileClient(streams, data, runfor));
            }
        } else {
            LOG.error("Unknown option: " + target);
            throw new IllegalArgumentException("Unknown target " + target);
        }

        ExecutorService executor = Executors.newFixedThreadPool(numThreads);
        long start = System.currentTimeMillis();

        List<Future<Long>> results = executor.invokeAll(clients, 10, TimeUnit.MINUTES);
        long end = System.currentTimeMillis();
        long count = 0;
        for (Future<Long> r : results) {
            if (!r.isDone()) {
                LOG.warn("Job didn't complete");
                System.exit(2);
            }
            long c = r.get();
            if (c == 0) {
                LOG.warn("Task didn't complete");
            }
            count += c;
        }
        long time = end - start;
        LOG.info("Finished processing writes (ms): {} TPT: {} op/s", time, count / ((double) time / 1000));
        executor.shutdown();
    } catch (ExecutionException ee) {
        LOG.error("Exception in worker", ee);
    } catch (KeeperException ke) {
        LOG.error("Error accessing zookeeper", ke);
    } catch (BKException e) {
        LOG.error("Error accessing bookkeeper", e);
    } catch (IOException ioe) {
        LOG.error("I/O exception during benchmark", ioe);
    } catch (InterruptedException ie) {
        LOG.error("Benchmark interrupted", ie);
    } finally {
        if (bkc != null) {
            try {
                bkc.close();
            } catch (BKException bke) {
                LOG.error("Error closing bookkeeper client", bke);
            } catch (InterruptedException ie) {
                LOG.warn("Interrupted closing bookkeeper client", ie);
            }
        }
    }
    timeouter.cancel();
}

From source file:org.apache.bookkeeper.benchmark.BenchThroughputLatency.java

@SuppressWarnings("deprecation")
public static void main(String[] args)
        throws KeeperException, IOException, InterruptedException, ParseException, BKException {
    Options options = new Options();
    options.addOption("time", true, "Running time (seconds), default 60");
    options.addOption("entrysize", true, "Entry size (bytes), default 1024");
    options.addOption("ensemble", true, "Ensemble size, default 3");
    options.addOption("quorum", true, "Quorum size, default 2");
    options.addOption("ackQuorum", true, "Ack quorum size, default is same as quorum");
    options.addOption("throttle", true, "Max outstanding requests, default 10000");
    options.addOption("ledgers", true, "Number of ledgers, default 1");
    options.addOption("zookeeper", true, "Zookeeper ensemble, default \"localhost:2181\"");
    options.addOption("password", true, "Password used to create ledgers (default 'benchPasswd')");
    options.addOption("coordnode", true, "Coordination znode for multi client benchmarks (optional)");
    options.addOption("timeout", true, "Number of seconds after which to give up");
    options.addOption("sockettimeout", true, "Socket timeout for bookkeeper client. In seconds. Default 5");
    options.addOption("skipwarmup", false, "Skip warm up, default false");
    options.addOption("sendlimit", true, "Max number of entries to send. Default 20000000");
    options.addOption("latencyFile", true, "File to dump latencies. Default is latencyDump.dat");
    options.addOption("help", false, "This message");

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

    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("BenchThroughputLatency <options>", options);
        System.exit(-1);/*from w  w  w . j  a  v a  2  s. com*/
    }

    long runningTime = Long.parseLong(cmd.getOptionValue("time", "60"));
    String servers = cmd.getOptionValue("zookeeper", "localhost:2181");
    int entrysize = Integer.parseInt(cmd.getOptionValue("entrysize", "1024"));

    int ledgers = Integer.parseInt(cmd.getOptionValue("ledgers", "1"));
    int ensemble = Integer.parseInt(cmd.getOptionValue("ensemble", "3"));
    int quorum = Integer.parseInt(cmd.getOptionValue("quorum", "2"));
    int ackQuorum = quorum;
    if (cmd.hasOption("ackQuorum")) {
        ackQuorum = Integer.parseInt(cmd.getOptionValue("ackQuorum"));
    }
    int throttle = Integer.parseInt(cmd.getOptionValue("throttle", "10000"));
    int sendLimit = Integer.parseInt(cmd.getOptionValue("sendlimit", "20000000"));

    final int sockTimeout = Integer.parseInt(cmd.getOptionValue("sockettimeout", "5"));

    String coordinationZnode = cmd.getOptionValue("coordnode");
    final byte[] passwd = cmd.getOptionValue("password", "benchPasswd").getBytes(UTF_8);

    String latencyFile = cmd.getOptionValue("latencyFile", "latencyDump.dat");

    Timer timeouter = new Timer();
    if (cmd.hasOption("timeout")) {
        final long timeout = Long.parseLong(cmd.getOptionValue("timeout", "360")) * 1000;

        timeouter.schedule(new TimerTask() {
            public void run() {
                System.err.println("Timing out benchmark after " + timeout + "ms");
                System.exit(-1);
            }
        }, timeout);
    }

    LOG.warn("(Parameters received) running time: " + runningTime + ", entry size: " + entrysize
            + ", ensemble size: " + ensemble + ", quorum size: " + quorum + ", throttle: " + throttle
            + ", number of ledgers: " + ledgers + ", zk servers: " + servers + ", latency file: "
            + latencyFile);

    long totalTime = runningTime * 1000;

    // Do a warmup run
    Thread thread;

    byte data[] = new byte[entrysize];
    Arrays.fill(data, (byte) 'x');

    ClientConfiguration conf = new ClientConfiguration();
    conf.setThrottleValue(throttle).setReadTimeout(sockTimeout).setZkServers(servers);

    if (!cmd.hasOption("skipwarmup")) {
        long throughput;
        LOG.info("Starting warmup");

        throughput = warmUp(data, ledgers, ensemble, quorum, passwd, conf);
        LOG.info("Warmup tp: " + throughput);
        LOG.info("Warmup phase finished");
    }

    // Now do the benchmark
    BenchThroughputLatency bench = new BenchThroughputLatency(ensemble, quorum, ackQuorum, passwd, ledgers,
            sendLimit, conf);
    bench.setEntryData(data);
    thread = new Thread(bench);
    ZooKeeper zk = null;

    if (coordinationZnode != null) {
        final CountDownLatch connectLatch = new CountDownLatch(1);
        zk = new ZooKeeper(servers, 15000, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getState() == KeeperState.SyncConnected) {
                    connectLatch.countDown();
                }
            }
        });
        if (!connectLatch.await(10, TimeUnit.SECONDS)) {
            LOG.error("Couldn't connect to zookeeper at " + servers);
            zk.close();
            System.exit(-1);
        }

        final CountDownLatch latch = new CountDownLatch(1);
        LOG.info("Waiting for " + coordinationZnode);
        if (zk.exists(coordinationZnode, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                if (event.getType() == EventType.NodeCreated) {
                    latch.countDown();
                }
            }
        }) != null) {
            latch.countDown();
        }
        latch.await();
        LOG.info("Coordination znode created");
    }
    thread.start();
    Thread.sleep(totalTime);
    thread.interrupt();
    thread.join();

    LOG.info("Calculating percentiles");

    int numlat = 0;
    for (int i = 0; i < bench.latencies.length; i++) {
        if (bench.latencies[i] > 0) {
            numlat++;
        }
    }
    int numcompletions = numlat;
    numlat = Math.min(bench.sendLimit, numlat);
    long[] latency = new long[numlat];
    int j = 0;
    for (int i = 0; i < bench.latencies.length && j < numlat; i++) {
        if (bench.latencies[i] > 0) {
            latency[j++] = bench.latencies[i];
        }
    }
    Arrays.sort(latency);

    long tp = (long) ((double) (numcompletions * 1000.0) / (double) bench.getDuration());

    LOG.info(numcompletions + " completions in " + bench.getDuration() + " milliseconds: " + tp + " ops/sec");

    if (zk != null) {
        zk.create(coordinationZnode + "/worker-",
                ("tp " + tp + " duration " + bench.getDuration()).getBytes(UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT_SEQUENTIAL);
        zk.close();
    }

    // dump the latencies for later debugging (it will be sorted by entryid)
    OutputStream fos = new BufferedOutputStream(new FileOutputStream(latencyFile));

    for (Long l : latency) {
        fos.write((Long.toString(l) + "\t" + (l / 1000000) + "ms\n").getBytes(UTF_8));
    }
    fos.flush();
    fos.close();

    // now get the latencies
    LOG.info("99th percentile latency: {}", percentile(latency, 99));
    LOG.info("95th percentile latency: {}", percentile(latency, 95));

    bench.close();
    timeouter.cancel();
}

From source file:edu.stanford.epadd.launcher.Main.java

public static void main(String args[]) throws Exception {
    setupLogging();/*from ww  w .ja  v  a 2 s .  c om*/
    basicSetup(args);
    setupResources();

    out.println("Starting up ePADD on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running ePADD without enough memory. \nIf you launched ePADD from the command line, you can increase memory with an option like java -Xmx1g",
                2000);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! ePADD is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running ePADD still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of ePADD, please go to " + BASE_URL;
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching ePADD again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting ePADD at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill ePADD if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for ePADD shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            System.err.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(System.err);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                link = "http://localhost:" + PORT + "/epadd/index.jsp";

                if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/epadd/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent ePADD from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!noShutdown) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("ePADD will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:edu.stanford.muse.launcher.Main.java

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

    // set javawebstart.version to a dummy value if not already set (might happen when running with java -jar from cmd line)
    // exit.jsp doesn't allow us to showdown unless this prop is set
    if (System.getProperty("javawebstart.version") == null)
        System.setProperty("javawebstart.version", "UNKNOWN");

    final int TIMEOUT_SECS = 60;
    if (args.length > 0) {
        out.print(args.length + " argument(s): ");
        for (int i = 0; i < args.length; i++)
            out.print(args[i] + " ");
        out.println();//from  w  w  w .  ja v  a  2s.  c o m
    }

    Options options = getOpt();
    CommandLineParser parser = new PosixParser();
    CommandLine cmd = parser.parse(options, args);
    if (cmd.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("Muse batch mode", options);
        return;
    }

    boolean debug = false;
    if (cmd.hasOption("debug")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = true;
    } else if (cmd.hasOption("debug-address-book")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.ab");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    } else if (cmd.hasOption("debug-groups")) {
        URL url = ClassLoader.getSystemResource("log4j.properties.debug.groups");
        out.println("Loading logging configuration from url: " + url);
        PropertyConfigurator.configure(url);
        debug = false;
    }

    if (cmd.hasOption("no-browser-open"))
        browserOpen = false;

    if (cmd.hasOption("port")) {
        String portStr = cmd.getOptionValue('p');
        try {
            PORT = Integer.parseInt(portStr);
            String mesg = " Running on port: " + PORT;
            out.println(mesg);
        } catch (NumberFormatException nfe) {
            out.println("invalid port number " + portStr);
        }
    }

    if (cmd.hasOption("start-page"))
        startPage = cmd.getOptionValue("start-page");
    if (cmd.hasOption("base-dir"))
        baseDir = cmd.getOptionValue("base-dir");
    if (cmd.hasOption("search-mode"))
        searchMode = true;
    if (cmd.hasOption("amuse-mode"))
        amuseMode = true;

    System.setSecurityManager(null); // this is important
    WebAppContext webapp0 = null; // deployWarAt("root.war", "/"); // for redirecting
    String path = "/muse";
    WebAppContext webapp1 = deployWarAt("muse.war", path);
    if (webapp1 == null) {
        System.err.println("Aborting... no webapp");
        return;
    }

    // if in any debug mode, turn blurring off
    if (debug)
        webapp1.setAttribute("noblur", true);

    // we set this and its read by JSPHelper within the webapp 
    System.setProperty("muse.container", "jetty");

    // need to copy crossdomain.xml file for
    String tmp = System.getProperty("java.io.tmpdir");
    final URL url = Main.class.getClassLoader().getResource("crossdomain.xml");
    try {
        InputStream is = url.openStream();
        String file = tmp + File.separatorChar + "crossdomain.xml";
        copy_stream_to_file(is, file);
    } catch (Exception e) {
        System.err.println("Aborting..." + e);
        return;
    }
    server = new Server(PORT);
    ResourceHandler resource_handler = new ResourceHandler();
    //        resource_handler.setWelcomeFiles(new String[]{ "index.html" });
    resource_handler.setResourceBase(tmp);

    // set the header buffer size in the connectors, default is a ridiculous 4K, which causes failures any time there is
    // is a large request, such as selecting a few hundred folders. (even for posts!)
    // usually there is only one SocketConnector, so we just put the setHeaderBufferSize in a loop.
    Connector conns[] = server.getConnectors();
    for (Connector conn : conns) {
        int NEW_BUFSIZE = 1000000;
        // out.println ("Connector " + conn + " buffer size is " + conn.getHeaderBufferSize() + " setting to " + NEW_BUFSIZE);
        conn.setHeaderBufferSize(NEW_BUFSIZE);
    }

    BASE_URL = "http://localhost:" + PORT + path;
    String MUSE_CHECK_URL = BASE_URL + "/js/muse.js"; // for quick check of existing muse or successful start up. BASE_URL may take some time to run and may not always be available now that we set dirAllowed to false and public mode does not serve /muse.
    String debugFile = tmp + File.separatorChar + "debug.txt";

    HandlerList hl = new HandlerList();
    if (webapp0 != null)
        hl.setHandlers(new Handler[] { webapp1, webapp0, resource_handler });
    else
        hl.setHandlers(new Handler[] { webapp1, resource_handler });
    out.println("Starting up Muse on the local computer at " + BASE_URL + ", "
            + formatDateLong(new GregorianCalendar()));
    out.println("***For troubleshooting information, see this file: " + debugFile + "***\n");
    out.println("Current directory = " + System.getProperty("user.dir") + ", home directory = "
            + System.getProperty("user.home"));
    out.println("Memory status at the beginning: " + getMemoryStats());
    if (Runtime.getRuntime().maxMemory() / MB < 512)
        aggressiveWarn(
                "You are probably running Muse without enough memory. \nIf you launched Muse from the command line, you can increase memory with an option like java -Xmx1g",
                2000);
    server.setHandler(hl);

    // handle frequent error of user trying to launch another server when its already on
    // server.start() usually takes a few seconds to return
    // after that it takes a few seconds for the webapp to deploy
    // ignore any exceptions along the way and assume not if we can't prove it is alive
    boolean urlAlive = false;
    try {
        urlAlive = isURLAlive(MUSE_CHECK_URL);
    } catch (Exception e) {
        out.println("Exception: e");
        e.printStackTrace(out);
    }

    boolean disableStart = false;
    if (urlAlive) {
        out.println("Oh! Muse is already running at the URL: " + BASE_URL + ", will have to kill it!");
        killRunningServer(BASE_URL);
        Thread.sleep(3000);
        try {
            urlAlive = isURLAlive(MUSE_CHECK_URL);
        } catch (Exception e) {
            out.println("Exception: e");
            e.printStackTrace(out);
        }
        if (!urlAlive)
            out.println("Good. Kill succeeded, will restart");
        else {
            String message = "Previously running Muse still alive despite attempt to kill it, disabling fresh restart!\n";
            message += "If you just want to use the previous instance of Muse, please go to http://localhost:9099/muse\n";
            message += "\nTo kill this instance, please go to your computer's task manager and kill running java or javaw processes.\nThen try launching Muse again.\n";
            aggressiveWarn(message, 2000);
            return;
        }
    }
    //        else
    //          out.println ("Muse not already alive at URL: ..." + URL);

    if (!disableStart) {
        out.println("Starting Muse at URL: ..." + BASE_URL);
        try {
            server.start();
        } catch (BindException be) {
            out.println("port busy, but webapp not alive: " + BASE_URL + "\n" + be);
            throw new RuntimeException("Error: Port in use (Please kill Muse if its already running!)\n" + be);
        }
    }

    //      webapp1.start(); -- not needed
    PrintStream debugOut1 = System.err;
    try {
        File f = new File(debugFile);
        if (f.exists())
            f.delete(); // particular problem on windows :-(
        debugOut1 = new PrintStream(new FileOutputStream(debugFile), false, "UTF-8");
    } catch (IOException ioe) {
        System.err.println("Warning: failed to delete debug file " + debugFile + " : " + ioe);
    }

    final PrintStream debugOut = debugOut1;

    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        public void run() {
            try {
                server.stop();
                server.destroy();
                debugOut.close();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }));

    //        InfoFrame frame = new InfoFrame();
    //        frame.doShow();

    boolean success = waitTillPageAlive(MUSE_CHECK_URL, TIMEOUT_SECS);
    //        frame.updateText ("Opening a browser window");

    if (success) {
        // best effort to start shutdown thread
        //           out.println ("Starting Muse shutdown listener at port " + JettyShutdownThread.SHUTDOWN_PORT);

        try {
            int shutdownPort = PORT + 1; // shut down port is arbitrarily set to port + 1. it is ASSUMED to be free. 

            new JettyShutdownThread(server, shutdownPort).start();
            out.println("Listening for Muse shutdown message on port " + shutdownPort);
        } catch (Exception e) {
            out.println(
                    "Unable to start shutdown listener, you will have to stop the server manually using Cmd-Q on Mac OS or kill javaw processes on Windows");
        }

        try {
            setupSystemTrayIcon();
        } catch (Exception e) {
            out.println("Unable to setup system tray icon: " + e);
            e.printStackTrace(out);
        }

        // open browser window
        if (browserOpen) {
            preferredBrowser = null;
            // launch a browser here
            try {

                String link;
                if (System.getProperty("muse.mode.public") != null)
                    link = "http://localhost:" + PORT + "/muse/archives/";
                else
                    link = "http://localhost:" + PORT + "/muse/index.jsp";

                if (searchMode) {
                    String u = "http://localhost:" + PORT + "/muse/search";
                    out.println("Launching URL in browser: " + u);
                    link += "?mode=search";
                } else if (amuseMode) {
                    String u = "http://localhost:" + PORT + "/muse/amuse.jsp";
                    out.println("Launching URL in browser: " + u);
                    link = u;
                } else if (startPage != null) {
                    // startPage has to be absolute
                    link = "http://localhost:" + PORT + "/muse/" + startPage;
                }

                if (baseDir != null)
                    link = link + "?cacheDir=" + baseDir; // typically this is used when starting from command line. note: still using name, cacheDir

                out.println("Launching URL in browser: " + link);
                launchBrowser(link);

            } catch (Exception e) {
                out.println(
                        "Warning: Unable to launch browser due to exception (use the -n option to prevent Muse from trying to launch a browser):");
                e.printStackTrace(out);
            }
        }

        if (!cmd.hasOption("no-shutdown")) {
            // arrange to kill Muse after a period of time, we don't want the server to run forever

            // i clearly have too much time on my hands right now...
            long secs = KILL_AFTER_MILLIS / 1000;
            long hh = secs / 3600;
            long mm = (secs % 3600) / 60;
            long ss = secs % (60);
            out.print("Muse will shut down automatically after ");
            if (hh != 0)
                out.print(hh + " hours ");
            if (mm != 0 || (hh != 0 && ss != 0))
                out.print(mm + " minutes");
            if (ss != 0)
                out.print(ss + " seconds");
            out.println();

            Timer timer = new Timer();
            TimerTask tt = new ShutdownTimerTask();
            timer.schedule(tt, KILL_AFTER_MILLIS);
        }
    } else {
        out.println("\n\n\nSORRY!!! UNABLE TO DEPLOY WEBAPP, EXITING\n\n\n");
        //          frame.updateText("Sorry, looks like we are having trouble starting the jetty server\n");
    }

    savedSystemOut = out;
    savedSystemErr = System.err;
    System.setOut(debugOut);
    System.setErr(debugOut);
}

From source file:org.apache.metron.performance.load.LoadGenerator.java

public static void main(String[] args) throws Exception {
    CommandLine cli = LoadOptions.parse(new PosixParser(), args);
    EnumMap<LoadOptions, Optional<Object>> evaluatedArgs = LoadOptions.createConfig(cli);
    Map<String, Object> kafkaConfig = new HashMap<>();
    kafkaConfig.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    kafkaConfig.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
    kafkaConfig.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    kafkaConfig.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
    if (LoadOptions.ZK.has(cli)) {
        String zkQuorum = (String) evaluatedArgs.get(LoadOptions.ZK).get();
        kafkaConfig.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,
                Joiner.on(",").join(KafkaUtils.INSTANCE.getBrokersFromZookeeper(zkQuorum)));
    }//from   w  w w .  ja va  2 s .  c  om
    String groupId = evaluatedArgs.get(LoadOptions.CONSUMER_GROUP).get().toString();
    System.out.println("Consumer Group: " + groupId);
    kafkaConfig.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
    if (LoadOptions.KAFKA_CONFIG.has(cli)) {
        kafkaConfig.putAll((Map<String, Object>) evaluatedArgs.get(LoadOptions.KAFKA_CONFIG).get());
    }
    kafkaProducer = ThreadLocal.withInitial(() -> new KafkaProducer<>(kafkaConfig));
    int numThreads = (int) evaluatedArgs.get(LoadOptions.NUM_THREADS).get();
    System.out.println("Thread pool size: " + numThreads);
    pool = Executors.newFixedThreadPool(numThreads);
    Optional<Object> eps = evaluatedArgs.get(LoadOptions.EPS);

    Optional<Object> outputTopic = evaluatedArgs.get(LoadOptions.OUTPUT_TOPIC);
    Optional<Object> monitorTopic = evaluatedArgs.get(LoadOptions.MONITOR_TOPIC);
    long sendDelta = (long) evaluatedArgs.get(LoadOptions.SEND_DELTA).get();
    long monitorDelta = (long) evaluatedArgs.get(LoadOptions.MONITOR_DELTA).get();
    if ((eps.isPresent() && outputTopic.isPresent()) || monitorTopic.isPresent()) {
        Timer timer = new Timer(false);
        long startTimeMs = System.currentTimeMillis();
        if (outputTopic.isPresent() && eps.isPresent()) {
            List<String> templates = (List<String>) evaluatedArgs.get(LoadOptions.TEMPLATE).get();
            if (templates.isEmpty()) {
                System.out.println("Empty templates, so nothing to do.");
                return;
            }
            Optional<Object> biases = evaluatedArgs.get(LoadOptions.BIASED_SAMPLE);
            Sampler sampler = new UnbiasedSampler();
            if (biases.isPresent()) {
                sampler = new BiasedSampler((List<Map.Entry<Integer, Integer>>) biases.get(), templates.size());
            }
            MessageGenerator generator = new MessageGenerator(templates, sampler);
            Long targetLoad = (Long) eps.get();
            int periodsPerSecond = (int) (1000 / sendDelta);
            long messagesPerPeriod = targetLoad / periodsPerSecond;
            String outputTopicStr = (String) outputTopic.get();
            System.out.println(
                    "Generating data to " + outputTopicStr + " at " + targetLoad + " events per second");
            System.out.println("Sending " + messagesPerPeriod + " messages to " + outputTopicStr + " every "
                    + sendDelta + "ms");
            timer.scheduleAtFixedRate(new SendToKafka(outputTopicStr, messagesPerPeriod, numThreads, generator,
                    pool, numSent, kafkaProducer), 0, sendDelta);
        }
        List<AbstractMonitor> monitors = new ArrayList<>();
        if (outputTopic.isPresent() && monitorTopic.isPresent()) {
            System.out.println("Monitoring " + monitorTopic.get() + " every " + monitorDelta + " ms");
            monitors.add(new EPSGeneratedMonitor(outputTopic, numSent));
            monitors.add(new EPSThroughputWrittenMonitor(monitorTopic, kafkaConfig));
        } else if (outputTopic.isPresent() && !monitorTopic.isPresent()) {
            System.out.println("Monitoring " + outputTopic.get() + " every " + monitorDelta + " ms");
            monitors.add(new EPSGeneratedMonitor(outputTopic, numSent));
            monitors.add(new EPSThroughputWrittenMonitor(outputTopic, kafkaConfig));
        } else if (!outputTopic.isPresent() && monitorTopic.isPresent()) {
            System.out.println("Monitoring " + monitorTopic.get() + " every " + monitorDelta + " ms");
            monitors.add(new EPSThroughputWrittenMonitor(monitorTopic, kafkaConfig));
        } else if (!outputTopic.isPresent() && !monitorTopic.isPresent()) {
            System.out.println(
                    "You have not specified an output topic or a monitoring topic, so I have nothing to do here.");
        }
        int lookback = (int) evaluatedArgs.get(LoadOptions.SUMMARY_LOOKBACK).get();
        if (lookback > 0) {
            System.out.println("Summarizing over the last " + lookback + " monitoring periods ("
                    + lookback * monitorDelta + "ms)");
        } else {
            System.out.println("Turning off summarization.");
        }
        final CSVWriter csvWriter = new CSVWriter((File) evaluatedArgs.get(LoadOptions.CSV).orElse(null));
        Writer writer = new Writer(monitors, lookback, new ArrayList<Consumer<Writable>>() {
            {
                add(new ConsoleWriter());
                add(csvWriter);
            }
        });
        timer.scheduleAtFixedRate(new MonitorTask(writer), 0, monitorDelta);
        Optional<Object> timeLimit = evaluatedArgs.get(LoadOptions.TIME_LIMIT);
        if (timeLimit.isPresent()) {
            System.out.println("Ending in " + timeLimit.get() + " ms.");
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    timer.cancel();
                    long durationS = (System.currentTimeMillis() - startTimeMs) / 1000;
                    System.out.println("\nGenerated " + numSent.get() + " in " + durationS + " seconds.");
                    csvWriter.close();
                    System.exit(0);
                }
            }

                    , (Long) timeLimit.get());
        }
    }
}

From source file:Main.java

public static void doLater(long delay, final Runnable runnable) {
    Timer t = new Timer();
    t.schedule(new TimerTask() {
        @Override/*from   w  w w .  j a va 2  s .co  m*/
        public void run() {
            SwingUtilities.invokeLater(runnable);
        }
    }, delay);
}