Example usage for java.lang InterruptedException printStackTrace

List of usage examples for java.lang InterruptedException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.openteach.diamond.container.Container.java

public static void main(String[] args) {
    try {/*from  w  w w  .j a  v  a  2 s . c o  m*/
        start(new String[] { "E:\\diamond" });
        Thread.sleep(60 * 1000);
        stop();
    } catch (InterruptedException e) {
        e.printStackTrace();
        Thread.currentThread().interrupt();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

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

    final Arguments arguments = Arguments.parse(args);

    try {//from   www .j  a va  2  s  . c om
        LOG.debug("Trying to set client InboundThreadPool queue size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        final ThreadsConfig threadsConfig = ConfigManager.getConfig().getThreads();
        final ThreadPoolConfig inboundPool = threadsConfig.addPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        inboundPool.setQueueSize(CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        inboundPool.setCoreSize(CLIENT_INBOUND_QUEUE_CORE_SIZE);
        inboundPool.setMaximumSize(CLIENT_INBOUND_QUEUE_MAX_SIZE);
        threadsConfig.setInboundPool(CLIENT_INBOUND_THREAD_POOL_NAME);
        LOG.debug("Successfully set client InboundThreadPool queue size to '{}'",
                CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
    } catch (APIException ex) {
        LOG.error("Failed to set client inbound pool size to '{}'", CLIENT_INBOUND_QUEUE_QUEUE_SIZE);
        ex.printStackTrace();
    }

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

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

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

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

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

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

    RUNNING_LATCH.await();

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

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

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

From source file:org.wso2.carbon.appmgt.sampledeployer.main.ApplicationPublisher.java

public static void main(String[] args) {
    tomcatPort = args[0];/*from   w  w  w.  j av a  2 s .c o  m*/
    appmPath = args[1];
    username = args[2];
    password = args[3];
    tomcatPath = args[4];
    lampPath = args[5];
    ipAddress = args[6];
    hitCount = Integer.parseInt(args[7]);
    System.setProperty("javax.net.ssl.trustStore", appmPath + "/repository/resources/security/wso2carbon.jks");
    System.setProperty("javax.net.ssl.trustStorePassword", "wso2carbon");
    System.setProperty("javax.net.ssl.trustStoreType", "JKS");
    log.info("initialising properties");
    log.info("Tomcat port : " + tomcatPort);
    log.info("APPM path : " + appmPath);
    log.info("Username : " + username);
    log.info("Password : " + password);
    log.info("Tomcat path : " + tomcatPath);
    log.info("LAMP path : " + lampPath);
    log.info("IP Address : " + ipAddress);
    log.info("Hit count : " + hitCount);
    trackingCodes = new ConcurrentHashMap<String, String>();
    configure();
    //startServers();
    try {
        log.info("Starting Servers.....");
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    /*trackingCodes.put("/notifi","AM_995364166653157224");
    trackingCodes.put("/travelBooking","AM_14359451055881852910");
    trackingCodes.put("/travel","AM_10574531036724348945");*/
    for (String key : trackingCodes.keySet()) {
        accsesWebPages(key, trackingCodes.get(key), hitCount);
    }
}

From source file:de.prozesskraft.pkraft.Waitinstance.java

public static void main(String[] args) throws org.apache.commons.cli.ParseException, IOException {

    /*----------------------------
      get options from ini-file/*from   w  w  w  .j ava 2s .c  o  m*/
    ----------------------------*/
    java.io.File inifile = new java.io.File(WhereAmI.getInstallDirectoryAbsolutePath(Waitinstance.class) + "/"
            + "../etc/pkraft-waitinstance.ini");

    if (inifile.exists()) {
        try {
            ini = new Ini(inifile);
        } catch (InvalidFileFormatException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    } else {
        System.err.println("ini file does not exist: " + inifile.getAbsolutePath());
        System.exit(1);
    }

    /*----------------------------
      create boolean options
    ----------------------------*/
    Option ohelp = new Option("help", "print this message");
    Option ov = new Option("v", "prints version and build-date");

    /*----------------------------
      create argument options
    ----------------------------*/
    Option oinstance = OptionBuilder.withArgName("FILE").hasArg().withDescription(
            "[mandatory if no -scandir] instance file (process.pmb) that this program will wait till its status is 'error' or 'finished'")
            //            .isRequired()
            .create("instance");

    Option oscandir = OptionBuilder.withArgName("DIR").hasArg().withDescription(
            "[mandatory if no -instance] directory tree with instances (process.pmb). the first instance found will be tracked.")
            //            .isRequired()
            .create("scandir");

    Option omaxrun = OptionBuilder.withArgName("INTEGER").hasArg().withDescription(
            "[optional, default: 4320] time period (in minutes, default: 3 days) this program waits till it aborts further waiting.")
            //            .isRequired()
            .create("maxrun");

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

    options.addOption(ohelp);
    options.addOption(ov);
    options.addOption(oinstance);
    options.addOption(oscandir);
    options.addOption(omaxrun);

    /*----------------------------
      create the parser
    ----------------------------*/
    CommandLineParser parser = new GnuParser();
    // parse the command line arguments
    commandline = parser.parse(options, args);

    /*----------------------------
      usage/help
    ----------------------------*/
    if (commandline.hasOption("help")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("waitinstance", options);
        System.exit(0);
    }

    if (commandline.hasOption("v")) {
        System.out.println("author:  alexander.vogel@caegroup.de");
        System.out.println("version: [% version %]");
        System.out.println("date:    [% date %]");
        System.exit(0);
    }
    /*----------------------------
      ueberpruefen ob eine schlechte kombination von parametern angegeben wurde
    ----------------------------*/
    Integer maxrun = new Integer(4320);
    String pathInstance = null;
    String pathScandir = null;

    // instance & scandir
    if (!(commandline.hasOption("instance")) && !(commandline.hasOption("scandir"))) {
        System.err.println("one of the options -instance/-scandir is mandatory");
        exiter();
    } else if ((commandline.hasOption("instance")) && (commandline.hasOption("scandir"))) {
        System.err.println("both options -instance/-scandir are not allowed");
        exiter();
    } else if (commandline.hasOption("instance")) {
        pathInstance = commandline.getOptionValue("instance");
    } else if (commandline.hasOption("scandir")) {
        pathScandir = commandline.getOptionValue("scandir");
    }

    // maxrun
    if (commandline.hasOption("maxrun")) {
        maxrun = new Integer(commandline.getOptionValue("maxrun"));
    }
    /*----------------------------
      die lizenz ueberpruefen und ggf abbrechen
    ----------------------------*/

    // check for valid license
    ArrayList<String> allPortAtHost = new ArrayList<String>();
    allPortAtHost.add(ini.get("license-server", "license-server-1"));
    allPortAtHost.add(ini.get("license-server", "license-server-2"));
    allPortAtHost.add(ini.get("license-server", "license-server-3"));

    MyLicense lic = new MyLicense(allPortAtHost, "1", "user-edition", "0.1");

    // lizenz-logging ausgeben
    for (String actLine : (ArrayList<String>) lic.getLog()) {
        System.err.println(actLine);
    }

    // abbruch, wenn lizenz nicht valide
    if (!lic.isValid()) {
        System.exit(1);
    }

    /*----------------------------
      die eigentliche business logic
    ----------------------------*/

    // scannen nach dem ersten process.pmb 
    if ((pathScandir != null) && (pathInstance == null)) {
        String[] allBinariesOfScanDir = getProcessBinaries(pathScandir);

        if (allBinariesOfScanDir.length == 0) {
            System.err.println("no instance (process.pmb) found in directory tree " + pathScandir);
            exiter();
        } else {
            pathInstance = allBinariesOfScanDir[0];
            System.err.println("found instance: " + pathInstance);
        }
    }

    // ueberpruefen ob instance file existiert
    java.io.File fileInstance = new java.io.File(pathInstance);

    if (!fileInstance.exists()) {
        System.err.println("instance file does not exist: " + fileInstance.getAbsolutePath());
        exiter();
    }

    if (!fileInstance.isFile()) {
        System.err.println("instance file is not a file: " + fileInstance.getAbsolutePath());
        exiter();
    }

    // zeitpunkt wenn spaetestens beendet werden soll
    long runTill = System.currentTimeMillis() + (maxrun * 60 * 1000);

    // logging
    System.err.println("waiting for instance: " + fileInstance.getAbsolutePath());
    System.err.println("checking its status every 5 minutes");
    System.err.println("now is: " + new Timestamp(startInMillis).toString());
    System.err.println("maxrun till: " + new Timestamp(runTill).toString());

    // instanz einlesen
    Process p1 = new Process();
    p1.setInfilebinary(fileInstance.getAbsolutePath());
    Process p2 = p1.readBinary();

    // schleife, die prozess einliest und ueberprueft ob er noch laeuft
    while (!(p2.getStatus().equals("error") || p2.getStatus().equals("finished"))) {
        // logging
        System.err.println(new Timestamp(System.currentTimeMillis()) + " instance status: " + p2.getStatus());

        // 5 minuten schlafen: 300000 millis
        try {
            Thread.sleep(300000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        // ist die maximale laufzeit von this erreicht, dann soll beendet werden (3 tage)
        if (System.currentTimeMillis() > runTill) {
            System.err
                    .println("exiting because of maxrun. now is: " + new Timestamp(System.currentTimeMillis()));
            System.exit(2);
        }

        // den prozess frisch einlesen
        p2 = p1.readBinary();
    }

    System.err.println("exiting because instance status is: " + p2.getStatus());
    System.err.println("now is: " + new Timestamp(System.currentTimeMillis()).toString());
    System.exit(0);

}

From source file:it.unipr.ce.dsg.s2p.example.peer.FullPeer.java

public static void main(String[] args) {

    boolean active = true;

    if (args.length != 0) {
        FullPeer peer = null;//  w  ww.  j av a  2s.c  om
        if (args.length == 3) {
            //args[0]=file peer configuration args[1]=key
            peer = new FullPeer(args[0], args[1]);

        } else if (args.length == 5) {
            //args[0]=file peer configuration args[1]=key args[2]=peer name args[3]=peer port
            peer = new FullPeer(args[0], args[1], args[2], new Integer(args[3]));

        }
        for (int i = 0; i < args.length; i++) {

            /*
             * join to bootstrapPeer
             */
            if (args[i].equals("-j")) {
                peer.joinToBootstrapPeer();

            }
            /*
             * request public address from SBC
             */
            else if (args[i].equals("-s")) {
                peer.contactSBC();
            }
            /*
             * join to bootstrapPeer, wait and send ping message to random peer
             */
            else if (args[i].equals("-jp")) {

                peer.joinToBootstrapPeer();
                //wait for 3 seconds
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.pingToPeerRandomFromList();
            }
            /*
             * join to bootstrapPeer, wait and send ping message to random peer recursively
             */
            else if (args[i].equals("-jr")) {

                peer.joinToBootstrapPeer();

                while (active) {

                    //wait for 15 seconds
                    try {
                        Thread.sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //ping to random peer
                    peer.pingToPeerRandomFromList();
                }
            }

            else if (args[i].equals("-p")) {

                peer.pingToPeer(args[5]);
            }

            else if (args[i].equals("-sd")) {

                peer.contactSBC();
                try {
                    Thread.sleep(7000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                peer.disconnectGWP();

            }
            /*
             * contact SBC, wait, join to bootstrapPeer, wait and send ping message to random peer recursively
             */
            else if (args[i].equals("-a")) {

                peer.contactSBC();

                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.joinToBootstrapPeer();

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.pingToPeerRandomFromList();
            }

        }

    }
}

From source file:com.zytan.sdpn.peer.FullPeer.java

public static void main(String[] args) {

    boolean active = true;

    if (args.length != 0) {
        FullPeer peer = null;/* w ww. j  a  va 2 s  .  com*/
        if (args.length == 3) {
            //args[0]=file peer configuration args[1]=key
            peer = new FullPeer(args[0], args[1]);

        } else if (args.length == 5) {
            //args[0]=file peer configuration args[1]=key args[2]=peer name args[3]=peer port
            peer = new FullPeer(args[0], args[1], args[2], new Integer(args[3]));

        }
        for (int i = 0; i < args.length; i++) {

            /*
             * join to bootstrapPeer
             */
            if (args[i].equals("-j")) {
                peer.joinToBootstrapPeer();

            }
            /*
             * request public address from SBC
             */
            else if (args[i].equals("-s")) {
                peer.contactSBC();
            }
            /*
             * join to bootstrapPeer, wait and send ping message to random peer
             */
            else if (args[i].equals("-jp")) {

                peer.joinToBootstrapPeer();
                //wait for 3 seconds
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.pingToPeerRandomFromList();
            }
            /*
             * join to bootstrapPeer, wait and send ping message to random peer recursively
             */
            else if (args[i].equals("-jr")) {

                peer.joinToBootstrapPeer();

                while (active) {

                    //wait for 15 seconds
                    try {
                        Thread.sleep(15000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //ping to bootstrap peer
                    peer.pingToPeer(peer.peerConfig.bootstrap_peer);

                }
            }

            else if (args[i].equals("-p")) {

                peer.pingToPeer(args[5]);
            }

            else if (args[i].equals("-sd")) {

                peer.contactSBC();
                try {
                    Thread.sleep(7000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                peer.disconnectGWP();

            }
            /*
             * contact SBC, wait, join to bootstrapPeer, wait and send ping message to random peer recursively
             */
            else if (args[i].equals("-a")) {

                peer.contactSBC();

                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.joinToBootstrapPeer();

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                peer.pingToPeerRandomFromList();
            }

        }

    }
}

From source file:edu.umn.cs.sthadoop.hdfs.KNNJoin.java

public static void main(String[] args) throws IOException, InterruptedException {
    //      args = new String[5];
    //      args[0] = "/home/louai/nyc-taxi/taxiIndex/yyyy-MM-dd/2015-01-01"; 
    //      args[1] = "/home/louai/nyc-taxi/taxiIndex/yyyy-MM-dd/2015-01-02";
    //      args[2] = "/home/louai/nyc-taxi/outputRami";
    //      args[3] = "shape:edu.umn.cs.sthadoop.core.STPoint";
    //      args[4] = "-overwrite";

    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));

    /*/*from  ww  w.j a v a  2  s  .c o m*/
     * String property = params.get("namenodes");
     * System.out.println(property);
     */

    Path[] paths = params.getPaths();
    if (paths.length <= 2 && !params.checkInput()) {
        printUsage();
        System.exit(1);
    }
    final Path[] inputPaths = params.getInputPaths();
    LOG.info("Number of input paths: " + inputPaths.length);

    final Path userOutputPath = paths.length > 2 ? paths[2] : null;
    if (userOutputPath != null) {
        String newOutputPathStr = userOutputPath.toString() + "/" + inputPaths[0].getName() + "."
                + inputPaths[1].getName();
        params.setOutputPath(newOutputPathStr);
        params.checkInputOutput();
    } else {
        printUsage();
        System.exit(1);
    }

    final int k = params.getInt("k", 1);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (!isInputIndexed(params, inputPaths)) {
        System.out.println("There is no index file in one or both inputs");
        if (params.getBoolean("local", false)) {
            //            localKNNJoin(inputPaths, params.getOutputPath(), params);
        } else {
            System.exit(1);
        }
    } else {
        long t1 = System.currentTimeMillis();
        try {
            knnJoinMapReduce(params);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();
        LOG.info("[stat:time:overall=" + (t2 - t1) + "]");
    }
}

From source file:edu.umn.cs.sthadoop.operations.STJoins.java

public static void main(String[] args) throws IOException, InterruptedException {
    //      args = new String[5];
    //      args[0] = "/home/louai/nyc-taxi/taxiIndex/yyyy-MM-dd/2015-01-01"; 
    //      args[1] = "/home/louai/nyc-taxi/taxiIndex/yyyy-MM-dd/2015-01-02";
    //      args[2] = "/home/louai/nyc-taxi/outputRami";
    //      args[3] = "shape:edu.umn.cs.sthadoop.core.STPoint";
    //      args[4] = "-overwrite";

    final OperationsParams params = new OperationsParams(new GenericOptionsParser(args));

    /*/*from  w w  w  . jav  a  2  s . c o m*/
     * String property = params.get("namenodes");
     * System.out.println(property);
     */

    Path[] paths = params.getPaths();
    if (paths.length <= 2 && !params.checkInput()) {
        printUsage();
        System.exit(1);
    }
    final Path[] inputPaths = params.getInputPaths();
    LOG.info("Number of input paths: " + inputPaths.length);

    final Path userOutputPath = paths.length > 2 ? paths[2] : null;
    if (userOutputPath != null) {
        String newOutputPathStr = userOutputPath.toString() + "/" + inputPaths[0].getName() + "."
                + inputPaths[1].getName();
        params.setOutputPath(newOutputPathStr);
        params.checkInputOutput();
    } else {
        printUsage();
        System.exit(1);
    }

    final int k = params.getInt("k", 1);
    if (k == 0) {
        LOG.warn("k = 0");
    }

    if (!isInputIndexed(params, inputPaths)) {
        System.out.println("There is no index file in one or both inputs");
        if (params.getBoolean("local", false)) {
            //            localKNNJoin(inputPaths, params.getOutputPath(), params);
        } else {
            System.exit(1);
        }
    } else {
        long t1 = System.currentTimeMillis();
        try {
            JoinMapReduce(params);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        long t2 = System.currentTimeMillis();
        LOG.info("[stat:time:overall=" + (t2 - t1) + "]");
    }
}

From source file:edu.umass.cs.reconfiguration.deprecated.ReconfigurableClient.java

/**
 * Simple test client for the reconfiguration package. Clients only know the
 * set of all reconfigurators, not active replicas for any name. All
 * information about active replicas for a name is obtained from
 * reconfigurators. Any request can be sent to any reconfigurator and it
 * will forward to the appropriate reconfigurator if necessary and relay
 * back the response.//from   w w  w.  j  av  a  2s.c o  m
 * 
 * @param args
 */
public static void main(String[] args) {
    ReconfigurableClient client = null;
    try {
        /*
         * Client can only send/receive clear text or do server-only
         * authentication
         */
        JSONMessenger<?> messenger = new JSONMessenger<String>((new MessageNIOTransport<String, JSONObject>(
                null, null, new PacketDemultiplexerDefault(), true, ReconfigurationConfig.getClientSSLMode())));
        client = new ReconfigurableClient(ReconfigurationConfig.getReconfiguratorAddresses(), messenger);
        int numRequests = 2;
        String requestValuePrefix = "request_value";
        long nameReqInterArrivalTime = 200;
        long NCReqInterArrivalTime = 1000;
        String initValue = "initial_value";
        int numIterations = 10000;
        boolean testReconfigureRC = true;

        for (int j = 0; j < numIterations; j++) {
            String namePrefix = "name" + (int) (Math.random() * Integer.MAX_VALUE);
            String reconfiguratorID = "RC" + (int) (Math.random() * 64000);
            long t0 = System.currentTimeMillis();

            // /////////////request active replicas////////////////////
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeRequestActiveReplicas(namePrefix));
            while (!client.waitForFailure(namePrefix));
            DelayProfiler.updateDelay("requestActives", t0);

            // active replicas for name initially don't exist
            assert (client.getActiveReplicas() == null || client.getActiveReplicas().isEmpty());
            // ////////////////////////////////////////////////////////

            // ////////////////////create name/////////////////////////
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeCreateNameRequest(namePrefix, initValue));
            while (!client.waitForSuccess(namePrefix));
            DelayProfiler.updateDelay("createName", t0);
            // ////////////////////////////////////////////////////////

            /*
             * Verify that active replicas for name now exist. The only
             * reason the query is repeated is because it is possible to
             * find the name non-existent briefly if the query is sent to a
             * different reconfigurator that hasn't yet caught up with the
             * creation (but will eventually do so).
             */
            // ////////////////////////////////////////////////////////
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeRequestActiveReplicas(namePrefix));
            while (!client.waitForSuccess(namePrefix));
            DelayProfiler.updateDelay("requestActives", t0);

            assert (client.getActiveReplicas() != null && !client.getActiveReplicas().isEmpty());
            // ////////////////////////////////////////////////////////

            // ///////send a stream of app requests sequentially///////
            for (int i = 0; i < numRequests; i++) {
                t0 = System.currentTimeMillis();
                do
                    client.sendRequest(client.makeRequest(namePrefix, requestValuePrefix + i));
                while (!client.rcvdAppReply(namePrefix));
                DelayProfiler.updateDelay("appPaxosRequest", t0);
                Thread.sleep(nameReqInterArrivalTime);
            }
            // ////////////////////////////////////////////////////////

            // ////////////////////////////////////////////////////////
            // request current active replicas (possibly reconfigured)
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeRequestActiveReplicas(namePrefix));
            while (!client.waitForSuccess(namePrefix));
            DelayProfiler.updateDelay("requestActives", t0);
            // ////////////////////////////////////////////////////////

            // ///////////////delete name, retransmit if error////////////
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeDeleteNameRequest(namePrefix));
            while (!client.waitForSuccess(namePrefix));
            DelayProfiler.updateDelay("deleteName", t0);

            Thread.sleep(nameReqInterArrivalTime);
            // ////////////////////////////////////////////////////////

            // ////////////////////////////////////////////////////////
            // verify that active replicas for name now don't exist. The
            t0 = System.currentTimeMillis();
            do
                client.sendRequest(client.makeRequestActiveReplicas(namePrefix));
            while (!client.waitForFailure(namePrefix));
            DelayProfiler.updateDelay("requestActives", t0);

            assert (client.getActiveReplicas() == null || client.getActiveReplicas().isEmpty());
            // ////////////////////////////////////////////////////////

            if (!testReconfigureRC)
                continue;

            // ////////////////////////////////////////////////////////
            // add RC node; the port below does not matter in this test
            t0 = System.currentTimeMillis();
            // do
            client.sendRequest(new ReconfigureRCNodeConfig<String>(null, reconfiguratorID,
                    new InetSocketAddress(InetAddress.getByName("localhost"), TEST_PORT)));
            while (!client
                    .waitForReconfigureRCSuccess(AbstractReconfiguratorDB.RecordNames.RC_NODES.toString()))
                ;
            DelayProfiler.updateDelay("addReconfigurator", t0);
            // ////////////////////////////////////////////////////////

            Thread.sleep(NCReqInterArrivalTime);

            // //////////////// delete just added RC node//////////////////
            HashSet<String> deleted = new HashSet<String>();
            deleted.add(reconfiguratorID);
            t0 = System.currentTimeMillis();
            // do
            client.sendRequest(new ReconfigureRCNodeConfig<String>(null, null, deleted));
            while (!client
                    .waitForReconfigureRCSuccess(AbstractReconfiguratorDB.RecordNames.RC_NODES.toString())) {
            }
            DelayProfiler.updateDelay("removeReconfigurator", t0);
            // ////////////////////////////////////////////////////////

            Thread.sleep(NCReqInterArrivalTime);

            client.log.info("\n\n\n\n==================Successfully completed iteration " + j + ":\n"
                    + DelayProfiler.getStats() + "\n\n\n\n");
        }

        // client.messenger.stop();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (JSONException je) {
        je.printStackTrace();
    } catch (InterruptedException ie) {
        ie.printStackTrace();
    } catch (RequestParseException e) {
        e.printStackTrace();
    }
}

From source file:mase.MaseEvolve.java

public static void main(String[] args) throws Exception {
    File outDir = getOutDir(args);
    boolean force = Arrays.asList(args).contains(FORCE);
    if (!outDir.exists()) {
        outDir.mkdirs();/*  ww  w.jav a 2 s .  c o  m*/
    } else if (!force) {
        System.out.println("Folder already exists: " + outDir.getAbsolutePath() + ". Waiting 5 sec.");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
        }
    }

    // Get config file
    Map<String, String> pars = readParams(args);

    // Copy config to outdir
    try {
        File rawConfig = writeConfig(args, pars, outDir, false);
        File destiny = new File(outDir, DEFAULT_CONFIG);
        destiny.delete();
        FileUtils.moveFile(rawConfig, new File(outDir, DEFAULT_CONFIG));
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    // JBOT INTEGRATION: copy jbot config file to the outdir
    // Does nothing when jbot is not used
    if (pars.containsKey("problem.jbot-config")) {
        File jbot = new File(pars.get("problem.jbot-config"));
        FileUtils.copyFile(jbot, new File(outDir, jbot.getName()));
    }

    // Write config to system temp file
    File config = writeConfig(args, pars, outDir, true);
    // Launch
    launchExperiment(config);
}