Example usage for org.apache.commons.lang.time StopWatch reset

List of usage examples for org.apache.commons.lang.time StopWatch reset

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch reset.

Prototype

public void reset() 

Source Link

Document

Resets the stopwatch.

Usage

From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java

public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException {

    if (this.jerseyHttpClientConfig.getApplicationCode() != null) {
        clientRequest.getHeaders().add(this.jerseyHttpClientConfig.getApplicationCodeHeader(),
                this.jerseyHttpClientConfig.getApplicationCode());
    }//from w w  w  .  j  av  a  2  s  .  c  om
    if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) {
        for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) {
            clientRequest.getHeaders().add(entry.getKey(), entry.getValue());
        }
    }
    // final Map<String, Object> props = cr.getProperties();

    final HttpRequestBase method = getHttpMethod(clientRequest);

    // Set the read timeout
    final Integer readTimeout = jerseyHttpClientConfig.getReadTimeOut();
    if (readTimeout != null) {
        HttpConnectionParams.setSoTimeout(method.getParams(), readTimeout.intValue());
    }

    // FIXME penser au header http
    // DEBUG|wire.header|>> "Cache-Control: no-cache[\r][\n]"
    // DEBUG|wire.header|>> "Pragma: no-cache[\r][\n]"
    if (method instanceof HttpEntityEnclosingRequestBase) {
        final HttpEntityEnclosingRequestBase entMethod = (HttpEntityEnclosingRequestBase) method;

        if (clientRequest.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(clientRequest);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                re.writeRequestEntity(new CommittingOutputStream(baos) {
                    @Override
                    protected void commit() throws IOException {
                        writeOutBoundHeaders(clientRequest.getHeaders(), method);
                    }
                });
            } catch (IOException ex) {
                throw new ClientHandlerException(ex);
            }

            final byte[] content = baos.toByteArray();
            HttpEntity httpEntity = new ByteArrayEntity(content);
            entMethod.setEntity(httpEntity);

        }
    } else {
        writeOutBoundHeaders(clientRequest.getHeaders(), method);
    }

    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.reset();
        stopWatch.start();
        HttpResponse httpResponse = client.execute(method);
        int httpReturnCode = httpResponse.getStatusLine().getStatusCode();
        stopWatch.stop();
        log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms");

        if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) {
            return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse),
                    IOUtils.toInputStream(""), getMessageBodyWorkers());
        }

        return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse),
                httpResponse.getEntity() == null ? IOUtils.toInputStream("")
                        : httpResponse.getEntity().getContent(),
                getMessageBodyWorkers());
    } catch (Exception e) {
        throw new ClientHandlerException(e);
    }
}

From source file:com.sonyericsson.hudson.plugins.gerrit.trigger.GerritProjectListUpdaterFunctionalTest.java

/**
 * Test that Project List updates are active for Gerrit Version 2.11 upon
 * connection startup.// w  ww.  ja  va2 s .c om
 * @throws Exception if occurs.
 */
@Test
public void testProjectListUpdateActiveOnStartup() throws Exception {
    GerritServer gerritServer = new GerritServer("ABCDEF");
    Config config = (Config) gerritServer.getConfig();
    config.setGerritAuthKeyFile(sshKey.getPrivateKey());
    config.setProjectListFetchDelay(1);
    config.setProjectListRefreshInterval(1);
    config = SshdServerMock.getConfigFor(sshd, config);
    gerritServer.setConfig(config);
    PluginImpl.getInstance().addServer(gerritServer);

    gerritServer.start();
    gerritServer.startConnection();

    StopWatch watch = new StopWatch();
    watch.start();
    while (!gerritServer.isConnected()) {
        TimeUnit.SECONDS.sleep(SLEEPTIME);
        if (TimeUnit.MILLISECONDS.toSeconds(watch.getTime()) > MAXSLEEPTIME) {
            break;
        }
    }
    watch.stop();

    watch.reset();
    watch.start();
    while (gerritServer.getGerritProjects().size() == 0) {
        TimeUnit.SECONDS.sleep(SLEEPTIME);
        if (TimeUnit.MILLISECONDS.toSeconds(watch.getTime()) > MAXSLEEPTIME) {
            break;
        }
    }
    watch.stop();
    assertEquals(1, gerritServer.getGerritProjects().size());

    server.returnCommandFor("gerrit ls-projects", SshdServerMock.SendTwoProjectsCommand.class);

    TimeUnit.SECONDS.sleep(LONGSLEEPTIME);
    assertEquals(2, gerritServer.getGerritProjects().size());

}

From source file:fr.inria.edelweiss.kgdqp.test.TestDQP.java

public void testLocal() throws EngineException, MalformedURLException, IOException {
    Graph graph = Graph.create();/*w w w .j ava 2 s  .c  om*/
    QueryProcess exec = QueryProcessDQP.create(graph);

    StopWatch sw = new StopWatch();
    sw.start();
    logger.info("Initializing GraphEngine, entailments: " + graph.getEntailment());
    Load ld = Load.create(graph);
    logger.info("Initialized GraphEngine: " + sw.getTime() + " ms");

    sw.reset();
    sw.start();
    try {
        ld.parseDir(TestDQP.class.getClassLoader().getResource("demographie").getPath() + "/cog-2012.ttl");
    } catch (LoadException ex) {
        LogManager.getLogger(TestDQP.class.getName()).log(Level.ERROR, "", ex);
    }

    try {
        ld.parseDir(TestDQP.class.getClassLoader().getResource("demographie").getPath() + "/popleg-2010.ttl");
    } catch (LoadException ex) {
        LogManager.getLogger(TestDQP.class.getName()).log(Level.ERROR, "", ex);
    }

    logger.info("Graph size: " + graph.size());

    for (String q : queries.values()) {
        logger.info("Querying with : \n" + q);
        for (int i = 0; i < 10; i++) {
            sw.reset();
            sw.start();
            Mappings results = exec.query(q);
            logger.info(results.size() + " results: " + sw.getTime() + " ms");
        }
    }
}

From source file:com.yahoo.flowetl.core.Plumber.java

/**
 * Translates a set of roots into a runnable object.
 * //ww w . j  a  va 2  s  .c o m
 * @param roots
 * 
 * @return the pipe runner
 * 
 * @throws PipeException
 */
public PipeRunner translate(final Set<Pipe> roots) throws PipeException {

    if (roots == null || roots.isEmpty()) {
        throw new IllegalArgumentException("No valid pipes provided");
    }

    // first translate to a graph
    final DefaultDirectedGraph<Pipe, PipeEdge> runGraph = new DefaultDirectedGraph<Pipe, PipeEdge>(
            new EdgeFactory<Pipe, PipeEdge>() {
                @Override
                public PipeEdge createEdge(Pipe src, Pipe tgt) {
                    StringBuilder tmp = new StringBuilder();
                    tmp.append("{" + src.getName() + "}");
                    tmp.append("->");
                    tmp.append("{" + tgt.getName() + "}");
                    return new PipeEdge(tmp.toString());
                }
            });

    // find all reachable pipes from the given roots
    final Set<Pipe> reachableInputs = new HashSet<Pipe>();
    Set<Pipe> reachablePipesTmp = new HashSet<Pipe>();
    for (Pipe p : roots) {
        discoverReachable(p, reachablePipesTmp);
        reachableInputs.addAll(reachablePipesTmp);
        reachableInputs.add(p);
        reachablePipesTmp.clear();
    }

    // add as vertexes..
    for (Pipe p : reachableInputs) {
        runGraph.addVertex(p);
    }

    // connect together
    for (Pipe v : reachableInputs) {
        List<Pipe> outs = v.getOutputs();
        if (outs != null) {
            int max = v.maxOutputs();
            int cur = outs.size();
            if (max != -1 && (max < cur)) {
                throw new PipeException(
                        "Pipe " + v + " is only allowed " + max + " outputs but it has " + cur + " outputs");
            }
            for (Pipe t : outs) {
                if (t == null) {
                    continue;
                }
                PipeEdge edgeName = runGraph.addEdge(v, t);
                if (logger.isEnabled(Level.INFO)) {
                    logger.log(Level.INFO, "Connected " + v + " to " + t + " with edge " + edgeName);
                }
            }
        }
    }

    // do cycle detection
    CycleDetector<Pipe, PipeEdge> cycleDetect = new CycleDetector<Pipe, PipeEdge>(runGraph);
    Set<Pipe> cycleNodes = cycleDetect.findCycles();
    if (cycleNodes != null && cycleNodes.isEmpty() == false) {
        StringBuilder msg = new StringBuilder("The following pipes are causing cycles [");
        msg.append(StringUtils.join(cycleNodes, ","));
        msg.append("]");
        throw new PipeException(msg.toString());
    }

    // check connected components
    ConnectivityInspector<Pipe, PipeEdge> cInspector = new ConnectivityInspector<Pipe, PipeEdge>(runGraph);
    if (cInspector.isGraphConnected() == false) {
        throw new PipeException(
                "The pipes provided have occurences which do not actually connect to other pipes");
    }

    // display
    if (logger.isEnabled(Level.DEBUG)) {
        StringWriter w = new StringWriter();
        DOTExporter<Pipe, PipeEdge> d = new DOTExporter<Pipe, PipeEdge>(new VertexNameProvider<Pipe>() {
            @Override
            public String getVertexName(Pipe p) {
                return p.getName();
            }
        }, new VertexNameProvider<Pipe>() {
            @Override
            public String getVertexName(Pipe p) {
                return p.getName();
            }
        }, new EdgeNameProvider<PipeEdge>() {
            @Override
            public String getEdgeName(PipeEdge e) {
                return String.valueOf(e);
            }
        });
        d.export(w, runGraph);
        try {
            w.close();
        } catch (IOException e1) {
            // should be ok to ignore this...
        }
        logger.log(Level.DEBUG, w.toString());
    }

    // all verified, yippe
    PipeRunner out = new PipeRunner() {
        @Override
        public void run() {

            // use topological order to figure out
            // how to run this graph in a way
            // that will ensure the inputs are satisfied
            // before a vertex is ran...
            GraphIterator<Pipe, PipeEdge> it = makeTraversalIterator(runGraph);

            // get the ordering first
            // which doesn't involve activating any of the pipes
            // just seeing what the iteration order will be...
            final List<Pipe> order = IterUtils.toList(it, ArrayList.class);

            // now make the real run iterator
            it = makeTraversalIterator(runGraph);
            it.addTraversalListener(new TraversalListenerAdapter<Pipe, PipeEdge>() {
                @Override
                public void vertexTraversed(VertexTraversalEvent<Pipe> v) {
                    if (logger.isEnabled(Level.INFO)) {
                        logger.log(Level.INFO, "Vertex " + v.getVertex() + " was visited");
                    }
                }
            });

            StopWatch overallTimer = new StopWatch();
            overallTimer.start();

            notifyStart(order);

            // keep track of which ones we exec'ed
            // maybe for use later??
            final List<Pipe> curExecd = new ArrayList<Pipe>(order.size());

            // iterate
            StopWatch perRunTimer = new StopWatch();
            List<Pipe> pipeOutputs = null;
            PipeResult pipeRes = null;
            while (it.hasNext()) {
                Pipe toRun = it.next();
                perRunTimer.reset();
                perRunTimer.start();
                notifyStartGenerate(toRun);
                {
                    pipeRes = toRun.generateOutput();
                }
                perRunTimer.stop();
                curExecd.add(toRun);
                pipeOutputs = toRun.getOutputs();
                if (pipeOutputs != null) {
                    for (Pipe tmp : pipeOutputs) {
                        if (tmp == null) {
                            continue;
                        }
                        tmp.attachInput(pipeRes);
                    }
                }
                notifyFinishGenerate(toRun, pipeRes, perRunTimer.getTime());
                // now clear it
                toRun.clearInputs();
            }

            overallTimer.stop();
            notifyComplete(overallTimer.getTime());

        }
    };
    return out;
}

From source file:com.mothsoft.alexis.engine.textual.TopicDocumentMatcherImpl.java

public void execute() {

    logger.info("Starting Topic<=>Document Matching");

    final StopWatch stopWatch = new StopWatch();

    // a unique state for documents pending matching so we can transition
    // items that had no topics (prevent a big future spike when a topic is
    // added that now matches really old documents)
    stopWatch.start();//from  ww  w  . j a  v a  2  s.  co m
    bulkUpdateDocumentState(DocumentState.PARSED, DocumentState.PENDING_TOPIC_MATCHING);
    stopWatch.stop();
    logger.info("Marking PARSED documents as PENDING_TOPIC_MATCHING took: " + stopWatch.toString());
    stopWatch.reset();

    stopWatch.start();
    match();
    stopWatch.stop();
    logger.info("Matching documents and topics took: " + stopWatch.toString());
    stopWatch.reset();

    // update any documents that had no assignments
    stopWatch.start();
    bulkUpdateDocumentState(DocumentState.PENDING_TOPIC_MATCHING, DocumentState.MATCHED_TO_TOPICS);
    stopWatch.stop();
    logger.info("Marking PENDING_TOPIC_MATCHING documents as MATCHED_TO_TOPICS took: " + stopWatch.toString());
}

From source file:de.csw.expertfinder.test.pos.TestPartOfSpeechTagger.java

/**
 * Tests the MorphAdorner POS tagger./*  ww w.  j  a  v  a2 s  .c o m*/
 * @throws Exception
 */
@Test(dataProvider = "morphAdornerDataProvider")
public void testMorphAdorner(List<List<String>> sentences, Class<PartOfSpeechTagger> taggerClass,
        Class<Lemmatizer> lemmatizerClass) throws Exception {

    StopWatch stopWatch = new StopWatch();

    // initialize POS tagger (can take long if lexicon based)
    stopWatch.start();

    PartOfSpeechTagger partOfSpeechTagger = taggerClass.newInstance();

    stopWatch.stop();

    if (log.isDebugEnabled())
        log.debug("Initializing POS tagger (" + taggerClass.getSimpleName() + "): " + stopWatch);

    // Initialize lemmatizer
    stopWatch.reset();
    stopWatch.start();

    Lemmatizer lemmatizer = lemmatizerClass.newInstance();

    stopWatch.stop();

    if (log.isDebugEnabled())
        log.debug("Initializing lemmatizer (" + lemmatizerClass.getSimpleName() + "): " + stopWatch);

    // POS tag sentences
    stopWatch.reset();
    stopWatch.start();

    List<List<AdornedWord>> taggedSentences = partOfSpeechTagger.tagSentences(sentences);

    stopWatch.stop();

    if (log.isDebugEnabled())
        log.debug("Tagging words: " + stopWatch);

    Lexicon wordLexicon = partOfSpeechTagger.getLexicon();

    SpellingStandardizer standardizer = new DefaultSpellingStandardizer();

    lemmatizer.setDictionary(standardizer.getStandardSpellings());

    //   Get the part of speech tags from
    //   the word lexicon.

    PartOfSpeechTags partOfSpeechTags = wordLexicon.getPartOfSpeechTags();

    WordTokenizer spellingTokenizer = new PennTreebankTokenizer();

    // write results to file
    FileWriter out = new FileWriter("posresult_" + taggerClass.getSimpleName() + ".txt");

    for (int i = 0; i < sentences.size(); i++) {
        //  Get the next adorned sentence.
        //  This contains a list of adorned
        //  words.  Only the spellings
        //  and part of speech tags are
        //  guaranteed to be defined.

        List<AdornedWord> sentence = taggedSentences.get(i);

        out.write("---------- Sentence " + (i + 1) + " ----------");

        //  Print out the spelling and part(s)
        //  of speech for each word in the
        //  sentence.  Punctuation is treated
        //  as a word too.

        for (int j = 0; j < sentence.size(); j++) {
            AdornedWord adornedWord = sentence.get(j);

            setLemma(adornedWord, wordLexicon, lemmatizer, partOfSpeechTags, spellingTokenizer);

            out.write(StringUtils.rpad((j + 1) + "", 3) + ": "
                    + StringUtils.rpad("spell: " + adornedWord.getSpelling(), 20)
                    + StringUtils.rpad("lemmata: " + adornedWord.getLemmata(), 20)
                    + adornedWord.getPartsOfSpeech() + "\n");
        }
    }

    out.close();

    partOfSpeechTagger = null;
    System.gc();
}

From source file:net.craigstars.game.services.GameControllerImpl.java

/**
 * Generate a new turn for a game./*from ww w. j ava2 s .  co  m*/
 * 
 * @param gameId The id of the game to generate a turn for
 */
public void generateTurn(Game game) {
    StopWatch timer = new StopWatch();
    timer.start();

    // merge the game from the cache with the session
    game = dao.getGameDao().merge(game);
    log.info("Merged turn {}, {}ms", game.getYear(), timer.getTime());

    // set our status to generating a turn and put it back in the cache
    game.setStatus(GameStatus.GeneratingTurn);
    putInCache(game);

    // generate the turn
    TurnGenerator tg = new TurnGenerator(game, fleetController, planetController);
    tg.generate();

    timer.reset();
    timer.start();
    game = dao.getGameDao().save(game);
    log.info("Save game {}, {} ms", game.getYear(), timer.getTime());
    putInCache(game);
}

From source file:com.streamsets.pipeline.stage.destination.jobtype.avroparquet.LargeInputFileIT.java

@Test
public void testLargeFile() throws Exception {
    File inputFile = new File(getInputDir(), "input.avro");
    File outputFile = new File(getOutputDir(), "input.parquet");
    long recordCount = Long.valueOf(System.getProperty(TARGET_RECORD_COUNT, TARGET_RECORD_COUNT_DEFAULT));
    StopWatch stopWatch = new StopWatch();

    stopWatch.start();//from  ww  w. j a va 2 s.c o  m
    generateAvroFile(AVRO_SCHEMA, inputFile, recordCount);
    stopWatch.stop();

    LOG.info("Created input avro file in {}, contains {} records and have {}.", stopWatch.toString(),
            recordCount, humanReadableSize(inputFile.length()));

    AvroConversionCommonConfig commonConfig = new AvroConversionCommonConfig();
    AvroParquetConfig conf = new AvroParquetConfig();
    commonConfig.inputFile = inputFile.getAbsolutePath();
    commonConfig.outputDirectory = getOutputDir();

    MapReduceExecutor executor = generateExecutor(commonConfig, conf, Collections.emptyMap());

    ExecutorRunner runner = new ExecutorRunner.Builder(MapReduceDExecutor.class, executor)
            .setOnRecordError(OnRecordError.TO_ERROR).build();
    runner.runInit();

    Record record = RecordCreator.create();
    record.set(Field.create(Collections.<String, Field>emptyMap()));

    stopWatch.reset();
    stopWatch.start();
    runner.runWrite(ImmutableList.of(record));
    stopWatch.stop();
    LOG.info("Generated output parquet file in {} and have {}.", stopWatch.toString(),
            humanReadableSize(outputFile.length()));

    Assert.assertEquals(0, runner.getErrorRecords().size());
    runner.runDestroy();

    validateParquetFile(new Path(outputFile.getAbsolutePath()), recordCount);
}

From source file:com.sforce.cd.apexUnit.client.testEngine.TestStatusPollerAndResultHandler.java

public boolean waitForTestsToComplete(String parentJobId, PartnerConnection conn) {
    String soql = QueryConstructor.getTestExecutionStatus(parentJobId);
    // String soql =
    // QueryConstructor.getTestExecutionStatusAndTransactionTime(parentJobId);

    QueryResult queryResult;/*from  w  w  w.  ja  v  a  2  s.c o m*/
    boolean testsCompleted = false;

    try {
        LOG.debug(soql);
        int index = 0;
        queryResult = conn.query(soql);

        if (queryResult.getDone()) {
            SObject[] sObjects = queryResult.getRecords();

            if (sObjects != null) {
                String status = "";
                int totalTests = sObjects.length;
                totalTestClasses = totalTests;
                int remainingTests = totalTests;
                LOG.info("Total test classes to execute: " + totalTestClasses);
                String testId = "";
                String testName = "";
                String id = "";
                StopWatch stopWatch = new StopWatch();
                long startTime = 0;
                long endTime = 0;
                for (SObject sobject : sObjects) {
                    sobject.setType("ApexTestQueueItem");
                    status = sobject.getField("Status").toString();
                    testId = sobject.getField("ApexClassId").toString();
                    id = sobject.getField("Id").toString();
                    LOG.debug("ID for ApexTestQueueItem: " + id);
                    testName = ApexClassFetcherUtils.apexClassMap.get(testId);
                    LOG.info("Now executing the test class: " + testName + " ("
                            + CommandLineArguments.getOrgUrl() + "/" + testId + " ) " + "Status : " + status);
                    stopWatch.reset();
                    stopWatch.start();
                    startTime = stopWatch.getTime();
                    LOG.debug("Start time: " + startTime);

                    while (status.equals("Processing") || status.equals("Queued") || status.equals("Preparing")
                            || !status.equals("Completed")) {

                        // break out of the loop if the test failed
                        if (status.equals("Failed")) {
                            LOG.info("Test class failure for : " + testName + " ("
                                    + CommandLineArguments.getOrgUrl() + "/" + testId + " ) ");
                            break;
                        } else if (status.equals("Aborted")) {
                            LOG.info("Test : " + testName + " (" + CommandLineArguments.getOrgUrl() + "/"
                                    + testId + " ) has been aborted.");
                            totalTestClassesAborted++;
                            break;
                        }
                        // Abort the long running tests based on user
                        // input(default: 10 minutes)
                        // stopWatch.getTime() will be in milliseconds,
                        // hence divide by 1000 to convert to seconds
                        // maxTestExecTimeThreshold will be in minutes,
                        // hence multiply by 60 to convert to seconds

                        if (CommandLineArguments.getMaxTestExecTimeThreshold() != null
                                && stopWatch.getTime()
                                        / 1000.0 > CommandLineArguments.getMaxTestExecTimeThreshold() * 60
                                && status.equals("Processing")) {
                            LOG.info("Oops! This test is a long running test. "
                                    + CommandLineArguments.getMaxTestExecTimeThreshold()
                                    + " minutes elapsed; aborting the test: " + testName);

                            // create new sobject for updating the record
                            SObject newSObject = new SObject();
                            newSObject.setType("ApexTestQueueItem");
                            newSObject.setField("Id", id);
                            // abort the test using DML, set status to
                            // "Aborted"
                            newSObject.setField("Status", "Aborted");
                            totalTestClassesAborted++;
                            // logging the status and id fields to compare
                            // them for pre and post update call

                            try {
                                // TODO : up to 10 records can be updated at
                                // a time by update() call.
                                // add the logic to leverage this feature.
                                // Currently only one record is being
                                // updated(aborted)

                                // Challenge: By the time we wait for 10
                                // records that needs to be aborted, the
                                // 'to-be-aborted' test might continue to
                                // run and might get completed

                                // update() call- analogous to UPDATE
                                // Statement in SQL
                                SaveResult[] saveResults = conn.update(new SObject[] { newSObject });

                                LOG.debug("Stop time: " + stopWatch.getTime());
                                stopWatch.stop();

                                for (int i = 0; i < saveResults.length; i++) {
                                    if (saveResults[i].isSuccess()) {
                                        LOG.debug("The record " + saveResults[i].getId()
                                                + " was updated successfully");
                                        LOG.info("Aborted test case: " + testName
                                                + " since the test took more time than the threshold execution time of "
                                                + CommandLineArguments.getMaxTestExecTimeThreshold() + " mins");
                                    } else {
                                        // There were errors during the
                                        // update call, so loop through and
                                        // print them out

                                        StringBuffer errorMsg = new StringBuffer();
                                        errorMsg.append("Record " + saveResults[i].getId() + " failed to save");
                                        for (int j = 0; j < saveResults[i].getErrors().length; j++) {
                                            com.sforce.soap.partner.Error err = saveResults[i].getErrors()[j];
                                            errorMsg.append("error code: " + err.getStatusCode().toString());
                                            errorMsg.append("error message: " + err.getMessage());
                                        }
                                        ApexUnitUtils.shutDownWithErrMsg(errorMsg.toString());
                                    }
                                }
                                LOG.debug("After update--" + newSObject.getField("Status").toString());
                                break;
                            } catch (ConnectionException e) {
                                ApexUnitUtils.shutDownWithDebugLog(e,
                                        ConnectionHandler.logConnectionException(e, conn, soql));
                            }

                        }

                        LOG.debug("Status of the test class: " + testName + " ("
                                + CommandLineArguments.getOrgUrl() + "/" + testId + " ) " + " is : " + status);

                        while (stopWatch.getTime() % 1000 != 0) {
                            // wait, till 1 second elapses
                        }
                        LOG.debug("Firing polling query at " + stopWatch.getTime());
                        queryResult = conn.query(soql);
                        sObjects = queryResult.getRecords();
                        status = sObjects[index].getField("Status").toString();
                    }
                    endTime = stopWatch.getTime();
                    // get and log extended status for the test
                    if (sObjects[index] != null && sObjects[index].getField("ExtendedStatus") != null) {
                        String extendedStatus = sObjects[index].getField("ExtendedStatus").toString();
                        LOG.info("Test status for " + testName + ":" + extendedStatus);
                    }
                    LOG.info("Completed executing the test class: " + testName + ". Time taken by the test: "
                            + endTime / 1000 / 60 + " minutes," + (endTime / 1000) % 60 + " seconds");
                    index++;
                    remainingTests = totalTests - index;
                    LOG.info("Total tests executed " + index + " , Remaining tests " + remainingTests);
                    if (remainingTests == 0) {
                        testsCompleted = true;
                    }
                }
            }
        }
    } catch (ConnectionException e) {
        ApexUnitUtils.shutDownWithDebugLog(e, ConnectionHandler.logConnectionException(e, conn, soql));
    }
    return testsCompleted;

}

From source file:de.unisb.cs.st.javalanche.mutation.runtime.testDriver.MutationTestDriver.java

/**
 * Runs the tests without applying any changes. This method is used to check
 * if the driver works correctly.//from w w  w  .j av a2s  .co  m
 */
private void runNormalTests() {
    logger.info("Running tests of project " + configuration.getProjectPrefix());
    // addMutationTestListener(new AdabuListener());
    addListenersFromProperty();
    List<String> allTests = getAllTests();
    int counter = 0;
    int size = allTests.size();
    timeout = Integer.MAX_VALUE;
    boolean allPass = true;
    List<SingleTestResult> failing = new ArrayList<SingleTestResult>();
    testsStart();
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    coldRun(allTests);
    for (String testName : allTests) {
        counter++;
        logger.info(DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " (" + counter + " / " + size
                + ") Running test:  " + testName);
        MutationTestRunnable runnable = getTestRunnable(testName);
        testStart(testName);
        stopWatch.reset();
        stopWatch.start();
        runWithTimeout(runnable);
        SingleTestResult result = runnable.getResult();
        logger.info("Test took " + DurationFormatUtils.formatDurationHMS(stopWatch.getTime()) + " " + testName);
        if (!result.hasPassed()) {
            allPass = false;
            failing.add(result);
            logger.warn("Test has not passed " + result.getTestMessage());
        }
        testEnd(testName);
    }
    testsEnd();
    if (allPass) {
        String message = "All " + allTests.size() + " tests passed ";
        System.out.println(message);
        logger.info(message);
    } else {
        logger.warn("Not all tests passed");
        for (SingleTestResult str : failing) {
            logger.warn(str.getTestMessage().getTestCaseName() + ": " + str.getTestMessage());
        }
        File outFile = new File(configuration.getOutputDir(), "/failed-tests.xml");
        XmlIo.toXML(failing, outFile);
    }
}