Example usage for java.lang Thread sleep

List of usage examples for java.lang Thread sleep

Introduction

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

Prototype

public static native void sleep(long millis) throws InterruptedException;

Source Link

Document

Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.

Usage

From source file:it.polito.tellmefirst.web.rest.TMFServer.java

/**
 * TMF starting point. From rest directory, launch this command:
 * mvn exec:java -Dexec.mainClass="it.polito.temefirst.web.rest.TMFServer" -Dexec.args="<path_to_TMF_installation>/conf/server.properties"
 * or use the run.sh file in bin directory
 *///from w  w  w. j  a  v  a  2  s.c o  m
public static void main(String[] args) throws TMFConfigurationException, TMFIndexesWarmUpException,
        URISyntaxException, InterruptedException, IOException {
    LOG.debug("[main] - BEGIN");
    URI serverURI = new URI("http://localhost:2222/rest/");
    String configFileName = args[0];
    new TMFVariables(configFileName);

    // XXX I put the code of IndexUtil.init() here, because, for now, I need a reference of SimpleSearchers for the Enhancer

    // build italian searcher
    Directory contextIndexDirIT = LuceneManager.pickDirectory(new File(TMFVariables.CORPUS_INDEX_IT));
    LOG.info("Corpus index used for italian: " + contextIndexDirIT);
    LuceneManager contextLuceneManagerIT = new LuceneManager(contextIndexDirIT);
    contextLuceneManagerIT
            .setLuceneDefaultAnalyzer(new ItalianAnalyzer(Version.LUCENE_36, TMFVariables.STOPWORDS_IT));
    ITALIAN_CORPUS_INDEX_SEARCHER = new SimpleSearcher(contextLuceneManagerIT);

    // build english searcher
    Directory contextIndexDirEN = LuceneManager.pickDirectory(new File(TMFVariables.CORPUS_INDEX_EN));
    LOG.info("Corpus index used for english: " + contextIndexDirEN);
    LuceneManager contextLuceneManagerEN = new LuceneManager(contextIndexDirEN);
    contextLuceneManagerEN
            .setLuceneDefaultAnalyzer(new EnglishAnalyzer(Version.LUCENE_36, TMFVariables.STOPWORDS_EN));
    ENGLISH_CORPUS_INDEX_SEARCHER = new SimpleSearcher(contextLuceneManagerEN);

    // build kb italian searcher
    String kbDirIT = TMFVariables.KB_IT;
    String residualKbDirIT = TMFVariables.RESIDUAL_KB_IT;
    ITALIAN_KB_INDEX_SEARCHER = new KBIndexSearcher(kbDirIT, residualKbDirIT);

    // build kb english searcher
    String kbDirEN = TMFVariables.KB_EN;
    String residualKbDirEN = TMFVariables.RESIDUAL_KB_EN;
    ENGLISH_KB_INDEX_SEARCHER = new KBIndexSearcher(kbDirEN, residualKbDirEN);

    enhancer = new Enhancer(ITALIAN_CORPUS_INDEX_SEARCHER, ENGLISH_CORPUS_INDEX_SEARCHER,
            ITALIAN_KB_INDEX_SEARCHER, ENGLISH_KB_INDEX_SEARCHER);

    italianClassifier = new Classifier("it", ITALIAN_CORPUS_INDEX_SEARCHER);
    englishClassifier = new Classifier("en", ENGLISH_CORPUS_INDEX_SEARCHER);

    //The following is adapted from DBpedia Spotlight (https://github.com/dbpedia-spotlight/dbpedia-spotlight)
    final Map<String, String> initParams = new HashMap<String, String>();
    initParams.put("com.sun.jersey.config.property.resourceConfigClass",
            "com.sun.jersey.api.core." + "PackagesResourceConfig");
    initParams.put("com.sun.jersey.config.property.packages", "it.polito.tellmefirst.web.rest.services");
    initParams.put("com.sun.jersey.config.property.WadlGeneratorConfig",
            "it.polito.tellmefirst.web.rest.wadl." + "ExternalUriWadlGeneratorConfig");
    SelectorThread threadSelector = GrizzlyWebContainerFactory.create(serverURI, initParams);
    threadSelector.start();
    System.err.println("Server started in " + System.getProperty("user.dir") + " listening on " + serverURI);
    Thread warmUp = new Thread() {
        public void run() {
        }
    };
    warmUp.start();
    while (running) {
        Thread.sleep(100);
    }
    threadSelector.stopEndpoint();
    System.exit(0);
    LOG.debug("[main] - END");
}

From source file:com.moss.veracity.core.filemonitor.FileMonitor.java

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

    BasicConfigurator.configure();/*from w w w.ja va 2  s.co  m*/

    FileMonitor m = FileMonitor.monitor(new File("pom.xml"), 1000);
    m.addListener(new FileListener() {
        public void fileChanged() {
            System.out.println("Changed");
        }
    });

    m.setPaused(true);

    Thread.sleep(5000l);

    m.setPaused(false);

    Thread.sleep(10000000l);
}

From source file:com.francetelecom.rd.dashboard.pc.DashboardPC.java

/**
 * Launch the application.//  w w w . j a  v  a2  s. c  om
 */
public static void main(String[] args) {
    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            try {
                logger.info("Application close, will unpublish node!");
                myNode.unPublishFromHomeBus();
            } catch (HomeBusException e) {
                logger.error("Application close, could not unpublish node : " + e.getMessage());
                e.printStackTrace();
            }
        }
    });

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {

                DashboardPC frame = new DashboardPC();

                String nodeId = frame.getIdForType(ID_type_Node);
                frame.busFactory = new HomeBusFactory(nodeId);
                try {
                    // temporary solution
                    // fake solution
                    // must remove this sleep after sds will no longer need it
                    Thread.sleep(1000);
                } catch (Exception e) {
                    logger.error("Error while sleep before node publish! \n" + e.getMessage());
                }

                frame.initNode(nodeId);
                frame.initDashboardWithRules();

                frame.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:org.mitre.mpf.rest.client.Main.java

public static void main(String[] args) throws RestClientException, IOException, InterruptedException {
    System.out.println("Starting rest-client!");

    //not necessary for localhost, but left if a proxy configuration is needed
    //System.setProperty("http.proxyHost","");
    //System.setProperty("http.proxyPort","");  

    String currentDirectory;//  w ww . j a va  2  s  .  c  o  m
    currentDirectory = System.getProperty("user.dir");
    System.out.println("Current working directory : " + currentDirectory);

    String username = "mpf";
    String password = "mpf123";
    byte[] encodedBytes = Base64.encodeBase64((username + ":" + password).getBytes());
    String base64 = new String(encodedBytes);
    System.out.println("encodedBytes " + base64);
    final String mpfAuth = "Basic " + base64;

    RequestInterceptor authorize = new RequestInterceptor() {
        @Override
        public void intercept(HttpRequestBase request) {
            request.addHeader("Authorization", mpfAuth /*credentials*/);
        }
    };

    //RestClient client = RestClient.builder().requestInterceptor(authorize).build();
    CustomRestClient client = (CustomRestClient) CustomRestClient.builder()
            .restClientClass(CustomRestClient.class).requestInterceptor(authorize).build();

    //getAvailableWorkPipelineNames
    String url = "http://localhost:8080/workflow-manager/rest/pipelines";
    Map<String, String> params = new HashMap<String, String>();
    List<String> availableWorkPipelines = client.get(url, params, new TypeReference<List<String>>() {
    });
    System.out.println("availableWorkPipelines size: " + availableWorkPipelines.size());
    System.out.println(Arrays.toString(availableWorkPipelines.toArray()));

    //processMedia        
    JobCreationRequest jobCreationRequest = new JobCreationRequest();
    URI uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S001-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    uri = Paths.get(currentDirectory,
            "/trunk/workflow-manager/src/test/resources/samples/meds/aa/S008-01-t10_01.jpg").toUri();
    jobCreationRequest.getMedia().add(new JobCreationMediaData(uri.toString()));
    jobCreationRequest.setExternalId("external id");

    //get first DLIB pipeline
    String firstDlibPipeline = availableWorkPipelines.stream()
            //.peek(pipepline -> System.out.println("will filter - " + pipepline))
            .filter(pipepline -> pipepline.startsWith("DLIB")).findFirst().get();

    System.out.println("found firstDlibPipeline: " + firstDlibPipeline);

    jobCreationRequest.setPipelineName(firstDlibPipeline); //grabbed from 'rest/pipelines' - see #1
    //two optional params
    jobCreationRequest.setBuildOutput(true);
    //jobCreationRequest.setPriority(priority); //will be set to 4 (default) if not set
    JobCreationResponse jobCreationResponse = client.customPostObject(
            "http://localhost:8080/workflow-manager/rest/jobs", jobCreationRequest, JobCreationResponse.class);
    System.out.println("jobCreationResponse job id: " + jobCreationResponse.getJobId());

    System.out.println("\n---Sleeping for 10 seconds to let the job process---\n");
    Thread.sleep(10000);

    //getJobStatus
    url = "http://localhost:8080/workflow-manager/rest/jobs"; // /status";
    params = new HashMap<String, String>();
    //OPTIONAL
    //params.put("v", "") - no versioning currently implemented         
    //id is now a path var - if not set, all job info will returned
    url = url + "/" + Long.toString(jobCreationResponse.getJobId());
    SingleJobInfo jobInfo = client.get(url, params, SingleJobInfo.class);
    System.out.println("jobInfo id: " + jobInfo.getJobId());

    //getSerializedOutput
    String jobIdToGetOutputStr = Long.toString(jobCreationResponse.getJobId());
    url = "http://localhost:8080/workflow-manager/rest/jobs/" + jobIdToGetOutputStr + "/output/detection";
    params = new HashMap<String, String>();
    //REQUIRED  - job id is now a path var and required for this endpoint
    String serializedOutput = client.getAsString(url, params);
    System.out.println("serializedOutput: " + serializedOutput);
}

From source file:com.joshlong.esb.springintegration.modules.net.feed.FeedEntryReaderMessageSource.java

public static void main(String[] args) throws Throwable {
    String siweb = "http://twitter.com/statuses/public_timeline.atom"; //http://localhost:8080/siweb/foo.atom";
    FeedEntryReaderMessageSource feedEntryReaderMessageSource = new FeedEntryReaderMessageSource();
    feedEntryReaderMessageSource.setFeedUrl(siweb);
    feedEntryReaderMessageSource.afterPropertiesSet();
    feedEntryReaderMessageSource.start();

    while (true) {
        Message<SyndEntry> entryMessage = feedEntryReaderMessageSource.receive();

        if (entryMessage != null) {
            SyndEntry entry = entryMessage.getPayload();
            logger.debug((entry.getTitle() + "=" + entry.getUri()));
        }//from www. jav a 2s.  co m

        Thread.sleep(1000);
    }
}

From source file:com.nextdoor.bender.S3SnsNotifier.java

public static void main(String[] args) throws ParseException, InterruptedException, IOException {
    formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZoneUTC();

    /*/*from   w w w .  j  ava 2  s  .  c o m*/
     * Parse cli arguments
     */
    Options options = new Options();
    options.addOption(Option.builder().longOpt("bucket").hasArg().required()
            .desc("Name of S3 bucket to list s3 objects from").build());
    options.addOption(Option.builder().longOpt("key-file").hasArg().required()
            .desc("Local file of S3 keys to process").build());
    options.addOption(
            Option.builder().longOpt("sns-arn").hasArg().required().desc("SNS arn to publish to").build());
    options.addOption(Option.builder().longOpt("throttle-ms").hasArg()
            .desc("Amount of ms to wait between publishing to SNS").build());
    options.addOption(Option.builder().longOpt("processed-file").hasArg()
            .desc("Local file to use to store procssed S3 object names").build());
    options.addOption(Option.builder().longOpt("skip-processed").hasArg(false)
            .desc("Whether to skip S3 objects that have been processed").build());
    options.addOption(
            Option.builder().longOpt("dry-run").hasArg(false).desc("If set do not publish to SNS").build());

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

    String bucket = cmd.getOptionValue("bucket");
    String keyFile = cmd.getOptionValue("key-file");
    String snsArn = cmd.getOptionValue("sns-arn");
    String processedFile = cmd.getOptionValue("processed-file", null);
    boolean skipProcessed = cmd.hasOption("skip-processed");
    dryRun = cmd.hasOption("dry-run");
    long throttle = Long.parseLong(cmd.getOptionValue("throttle-ms", "-1"));

    if (processedFile != null) {
        File file = new File(processedFile);

        if (!file.exists()) {
            logger.debug("creating local file to store processed s3 object names: " + processedFile);
            file.createNewFile();
        }
    }

    /*
     * Import S3 keys that have been processed
     */
    if (skipProcessed && processedFile != null) {
        try (BufferedReader br = new BufferedReader(new FileReader(processedFile))) {
            String line;
            while ((line = br.readLine()) != null) {
                alreadyPublished.add(line.trim());
            }
        }
    }

    /*
     * Setup writer for file containing processed S3 keys
     */
    FileWriter fw = null;
    BufferedWriter bw = null;
    if (processedFile != null) {
        fw = new FileWriter(processedFile, true);
        bw = new BufferedWriter(fw);
    }

    /*
     * Create clients
     */
    AmazonS3Client s3Client = new AmazonS3Client();
    AmazonSNSClient snsClient = new AmazonSNSClient();

    /*
     * Get S3 object list
     */
    try (BufferedReader br = new BufferedReader(new FileReader(keyFile))) {
        String line;
        while ((line = br.readLine()) != null) {
            String key = line.trim();

            if (alreadyPublished.contains(key)) {
                logger.info("skipping " + key);
            }

            ObjectMetadata om = s3Client.getObjectMetadata(bucket, key);

            S3EventNotification s3Notification = getS3Notification(key, bucket, om.getContentLength());

            String json = s3Notification.toJson();

            /*
             * Publish to SNS
             */
            if (publish(snsArn, json, snsClient, key) && processedFile != null) {
                bw.write(key + "\n");
                bw.flush();
            }

            if (throttle != -1) {
                Thread.sleep(throttle);
            }

        }
    }

    if (processedFile != null) {
        bw.close();
        fw.close();
    }
}

From source file:edu.kit.dama.transfer.client.impl.CLUploadClient.java

/**
 * Main entry point.//from   w ww  . j  av a2s.c o  m
 *
 * @param args Command line arguments.
 */
public static void main(String[] args) {
    int result = 0;
    CLUploadClient client;
    try {
        client = new CLUploadClient(args);
        Thread.currentThread().setUncaughtExceptionHandler(client);
        client.performUpload();
        while (client.getTransferClient().isTransferRunning()) {
            try {
                Thread.sleep(DateUtils.MILLIS_PER_SECOND);
            } catch (InterruptedException ie) {
            }
        }
    } catch (TransferClientInstatiationException ie) {
        LOGGER.error("Failed to create instance of command line client", ie);
        result = 1;
    } catch (CommandLineHelpOnlyException choe) {
        result = 0;
    }
    System.exit(result);
}

From source file:com.cloud.test.longrun.PerformanceWithAPI.java

public static void main(String[] args) {

    List<String> argsList = Arrays.asList(args);
    Iterator<String> iter = argsList.iterator();
    String host = "http://localhost";
    int numThreads = 1;

    while (iter.hasNext()) {
        String arg = iter.next();
        if (arg.equals("-h")) {
            host = "http://" + iter.next();
        }/*from w w  w. j a va 2s .c o  m*/
        if (arg.equals("-t")) {
            numThreads = Integer.parseInt(iter.next());
        }
        if (arg.equals("-n")) {
            numVM = Integer.parseInt(iter.next());
        }
    }

    final String server = host + ":" + _apiPort + "/";
    final String developerServer = host + ":" + _developerPort + _apiUrl;

    s_logger.info("Starting test in " + numThreads + " thread(s). Each thread is launching " + numVM + " VMs");

    for (int i = 0; i < numThreads; i++) {
        new Thread(new Runnable() {
            public void run() {
                try {

                    String username = null;
                    String singlePrivateIp = null;
                    String singlePublicIp = null;
                    Random ran = new Random();
                    username = Math.abs(ran.nextInt()) + "-user";

                    //Create User
                    User myUser = new User(username, username, server, developerServer);
                    try {
                        myUser.launchUser();
                        myUser.registerUser();
                    } catch (Exception e) {
                        s_logger.warn("Error code: ", e);
                    }

                    if (myUser.getUserId() != null) {
                        s_logger.info("User " + myUser.getUserName()
                                + " was created successfully, starting VM creation");
                        //create VMs for the user
                        for (int i = 0; i < numVM; i++) {
                            //Create a new VM, add it to the list of user's VMs
                            VirtualMachine myVM = new VirtualMachine(myUser.getUserId());
                            myVM.deployVM(_zoneId, _serviceOfferingId, _templateId, myUser.getDeveloperServer(),
                                    myUser.getApiKey(), myUser.getSecretKey());
                            myUser.getVirtualMachines().add(myVM);
                            singlePrivateIp = myVM.getPrivateIp();

                            if (singlePrivateIp != null) {
                                s_logger.info(
                                        "VM with private Ip " + singlePrivateIp + " was successfully created");
                            } else {
                                s_logger.info("Problems with VM creation for a user" + myUser.getUserName());
                                break;
                            }

                            //get public IP address for the User            
                            myUser.retrievePublicIp(_zoneId);
                            singlePublicIp = myUser.getPublicIp().get(myUser.getPublicIp().size() - 1);
                            if (singlePublicIp != null) {
                                s_logger.info("Successfully got public Ip " + singlePublicIp + " for user "
                                        + myUser.getUserName());
                            } else {
                                s_logger.info("Problems with getting public Ip address for user"
                                        + myUser.getUserName());
                                break;
                            }

                            //create ForwardProxy rules for user's VMs
                            int responseCode = CreateForwardingRule(myUser, singlePrivateIp, singlePublicIp,
                                    "22", "22");
                            if (responseCode == 500)
                                break;
                        }

                        s_logger.info("Deployment successful..." + numVM
                                + " VMs were created. Waiting for 5 min before performance test");
                        Thread.sleep(300000L); // Wait 

                        //Start performance test for the user
                        s_logger.info("Starting performance test for Guest network that has "
                                + myUser.getPublicIp().size() + " public IP addresses");
                        for (int j = 0; j < myUser.getPublicIp().size(); j++) {
                            s_logger.info("Starting test for user which has "
                                    + myUser.getVirtualMachines().size() + " vms. Public IP for the user is "
                                    + myUser.getPublicIp().get(j) + " , number of retries is " + _retry
                                    + " , private IP address of the machine is"
                                    + myUser.getVirtualMachines().get(j).getPrivateIp());
                            guestNetwork myNetwork = new guestNetwork(myUser.getPublicIp().get(j), _retry);
                            myNetwork.setVirtualMachines(myUser.getVirtualMachines());
                            new Thread(myNetwork).start();
                        }

                    }
                } catch (Exception e) {
                    s_logger.error(e);
                }
            }
        }).start();

    }
}

From source file:com.betfair.cougar.test.socket.app.SocketCompatibilityTestingApp.java

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

    Parser parser = new PosixParser();
    Options options = new Options();
    options.addOption("r", "repo", true, "Repository type to search: local|central");
    options.addOption("c", "client-concurrency", true,
            "Max threads to allow each client tester to run tests, defaults to 10");
    options.addOption("t", "test-concurrency", true, "Max client testers to run concurrently, defaults to 5");
    options.addOption("m", "max-time", true,
            "Max time (in minutes) to allow tests to complete, defaults to 10");
    options.addOption("v", "version", false, "Print version and exit");
    options.addOption("h", "help", false, "This help text");
    CommandLine commandLine = parser.parse(options, args);
    if (commandLine.hasOption("h")) {
        System.out.println(options);
        System.exit(0);//  w w  w.  j  a v a 2  s.c o m
    }
    if (commandLine.hasOption("v")) {
        System.out.println("How the hell should I know?");
        System.exit(0);
    }
    // 1. Find all testers in given repos
    List<RepoSearcher> repoSearchers = new ArrayList<>();
    for (String repo : commandLine.getOptionValues("r")) {
        if ("local".equals(repo.toLowerCase())) {
            repoSearchers.add(new LocalRepoSearcher());
        } else if ("central".equals(repo.toLowerCase())) {
            repoSearchers.add(new CentralRepoSearcher());
        } else {
            System.err.println("Unrecognized repo: " + repo);
            System.err.println(options);
            System.exit(1);
        }
    }
    int clientConcurrency = 10;
    if (commandLine.hasOption("c")) {
        try {
            clientConcurrency = Integer.parseInt(commandLine.getOptionValue("c"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "client-concurrency is not a valid integer: '" + commandLine.getOptionValue("c") + "'");
            System.exit(1);
        }
    }
    int testConcurrency = 5;
    if (commandLine.hasOption("t")) {
        try {
            testConcurrency = Integer.parseInt(commandLine.getOptionValue("t"));
        } catch (NumberFormatException nfe) {
            System.err.println(
                    "test-concurrency is not a valid integer: '" + commandLine.getOptionValue("t") + "'");
            System.exit(1);
        }
    }
    int maxMinutes = 10;
    if (commandLine.hasOption("m")) {
        try {
            maxMinutes = Integer.parseInt(commandLine.getOptionValue("m"));
        } catch (NumberFormatException nfe) {
            System.err.println("max-time is not a valid integer: '" + commandLine.getOptionValue("m") + "'");
            System.exit(1);
        }
    }

    Properties clientProps = new Properties();
    clientProps.setProperty("client.concurrency", String.valueOf(clientConcurrency));

    File baseRunDir = new File(System.getProperty("user.dir") + "/run");
    baseRunDir.mkdirs();

    File tmpDir = new File(baseRunDir, "jars");
    tmpDir.mkdirs();

    List<ServerRunner> serverRunners = new ArrayList<>();
    List<ClientRunner> clientRunners = new ArrayList<>();
    for (RepoSearcher searcher : repoSearchers) {
        List<File> jars = searcher.findAndCache(tmpDir);
        for (File f : jars) {
            ServerRunner serverRunner = new ServerRunner(f, baseRunDir);
            System.out.println("Found tester: " + serverRunner.getVersion());
            serverRunners.add(serverRunner);
            clientRunners.add(new ClientRunner(f, baseRunDir, clientProps));
        }
    }

    // 2. Start servers and collect ports
    System.out.println();
    System.out.println("Starting " + serverRunners.size() + " servers...");
    for (ServerRunner server : serverRunners) {
        server.startServer();
    }
    System.out.println();

    List<TestCombo> tests = new ArrayList<>(serverRunners.size() * clientRunners.size());
    for (ServerRunner server : serverRunners) {
        for (ClientRunner client : clientRunners) {
            tests.add(new TestCombo(server, client));
        }
    }

    System.out.println("Enqueued " + tests.size() + " test combos to run...");

    long startTime = System.currentTimeMillis();
    // 3. Run every client against every server, collecting results
    BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue(serverRunners.size() * clientRunners.size());
    ThreadPoolExecutor service = new ThreadPoolExecutor(testConcurrency, testConcurrency, 5000,
            TimeUnit.MILLISECONDS, workQueue);
    service.prestartAllCoreThreads();
    workQueue.addAll(tests);
    while (!workQueue.isEmpty()) {
        Thread.sleep(1000);
    }
    service.shutdown();
    service.awaitTermination(maxMinutes, TimeUnit.MINUTES);
    long endTime = System.currentTimeMillis();
    long totalTimeSecs = Math.round((endTime - startTime) / 1000.0);
    for (ServerRunner server : serverRunners) {
        server.shutdownServer();
    }

    System.out.println();
    System.out.println("=======");
    System.out.println("Results");
    System.out.println("-------");
    // print a summary
    int totalTests = 0;
    int totalSuccess = 0;
    for (TestCombo combo : tests) {
        String clientVer = combo.getClientVersion();
        String serverVer = combo.getServerVersion();
        String results = combo.getClientResults();
        ObjectMapper mapper = new ObjectMapper(new JsonFactory());
        JsonNode node = mapper.reader().readTree(results);
        JsonNode resultsArray = node.get("results");
        int numTests = resultsArray.size();
        int numSuccess = 0;
        for (int i = 0; i < numTests; i++) {
            if ("success".equals(resultsArray.get(i).get("result").asText())) {
                numSuccess++;
            }
        }
        totalSuccess += numSuccess;
        totalTests += numTests;
        System.out.println(clientVer + "/" + serverVer + ": " + numSuccess + "/" + numTests
                + " succeeded - took " + String.format("%2f", combo.getRunningTime()) + " seconds");
    }
    System.out.println("-------");
    System.out.println(
            "Overall: " + totalSuccess + "/" + totalTests + " succeeded - took " + totalTimeSecs + " seconds");

    FileWriter out = new FileWriter("results.json");
    PrintWriter pw = new PrintWriter(out);

    // 4. Output full results
    pw.println("{\n  \"results\": [");
    for (TestCombo combo : tests) {
        combo.emitResults(pw, "    ");
    }
    pw.println("  ],");
    pw.println("  \"servers\": [");
    for (ServerRunner server : serverRunners) {
        server.emitInfo(pw, "    ");
    }
    pw.println("  ],");
    pw.close();
}

From source file:JobScheduler.java

public static void main(String[] args) throws Exception {
    Runnable r1 = new Runnable() {
        public void run() {
            System.out.print("1");
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
            }//from   w  w  w  .  j av  a 2s .c om
            ;
            System.out.print("1");
        }
    };
    Runnable r2 = new Runnable() {
        public void run() {
            System.out.print("2");
            try {
                Thread.sleep(5000);
            } catch (Exception ex) {
            }
            ;
            System.out.print("2");
        }
    };
    Runnable r3 = new Runnable() {
        public void run() {
            System.out.print("3");
        }
    };
    Runnable r4 = new Runnable() {
        public void run() {
            System.out.print("4");
        }
    };

    JobScheduler js = new JobScheduler(0);
    Thread.sleep(1000);

    // Test 1 - General Test
    js.executeInAndRepeat(r1, 10000, 3000, 10);
    js.executeInAndRepeat(r2, 20000, 1000, 10);
    //Thread.sleep(11000);
    //js.cancel(r1);
    //js.cancel(r2);

    //js.configureBackup(r1);
    // Test 2 - Signature Test
    //Date in10Sec = new Date(System.currentTimeMillis()+10000L);
    //js.execute(r1);
    //js.executeIn(r2, 2000L);
    //js.executeInAndRepeat(r3, 10000L, 2000L);
    //js.executeInAndRepeat(r4, 10000L, 2000L, 5);
    //js.executeAt(r1, in10Sec);
    //js.executeAtAndRepeat(r2, in10Sec, 2000L);
    //js.executeAtAndRepeat(r3, in10Sec, 1000L, 5);
    //js.cancel(r4);
    //Thread.sleep(20000L);
    //js.cancel(r2);

    // Test 3 - Interval Test
    //js.executeInAndRepeat(r3, 10000L, JobScheduler.HOURLY);
    //js.executeInAndRepeat(r3, 10000L, JobScheduler.DAILY);
    //js.executeInAndRepeat(r3, 10000L, JobScheduler.WEEKLY);
    //js.executeInAndRepeat(r3, 10000L, JobScheduler.MONTHLY);
    //js.executeInAndRepeat(r3, 10000L, JobScheduler.YEARLY);
}