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

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

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Get the time on the stopwatch.

This is either the time between the start and the moment this method is called, or the amount of time between start and stop.

Usage

From source file:com.nridge.connector.fs.con_fs.core.RunPublishFS.java

/**
 * When an object implementing interface <code>Runnable</code> is used
 * to create a thread, starting the thread causes the object's
 * <code>run</code> method to be called in that separately executing
 * thread./*from  www.ja  v  a  2  s.  c  om*/
 * 
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    Document conDoc;
    DocumentXML documentXML;
    String docId, queueItem, srcPathFileName;
    Logger appLogger = mAppMgr.getLogger(this, "run");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    boolean isPublisherInitialized = true;
    DataBag schemaBag = (DataBag) mAppMgr.getProperty(Connector.PROPERTY_SCHEMA_NAME);
    Publishers indexPublishers = new Publishers(mAppMgr, mCrawlQueue, Constants.CFG_PROPERTY_PREFIX);
    try {
        indexPublishers.initialize(schemaBag);
    } catch (NSException e) {
        isPublisherInitialized = false;
        appLogger.error("Publisher initialization: " + e.getMessage());
    }

    if (isPublisherInitialized) {
        BlockingQueue transformQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_TRANSFORM_NAME);
        BlockingQueue publishQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_PUBLISH_NAME);

        long queueWaitTimeout = mAppMgr.getLong(Constants.CFG_PROPERTY_PREFIX + ".queue.wait_timeout",
                Constants.QUEUE_POLL_TIMEOUT_DEFAULT);
        do {
            try {
                queueItem = (String) transformQueue.poll(queueWaitTimeout, TimeUnit.SECONDS);
                if (mCrawlQueue.isQueueItemDocument(queueItem)) {
                    StopWatch stopWatch = new StopWatch();
                    stopWatch.start();

                    docId = Connector.docIdFromQueueItem(queueItem);

                    appLogger.debug(String.format("Transform Queue Item: %s", docId));
                    srcPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_TRANSFORM_NAME, docId);
                    try {
                        documentXML = new DocumentXML();
                        documentXML.load(srcPathFileName);
                        conDoc = documentXML.getDocument();

                        indexPublishers.send(conDoc);

                        File srcFile = new File(srcPathFileName);
                        if (!srcFile.delete())
                            appLogger.warn(String.format("%s: Unable to delete.", srcPathFileName));

                        stopWatch.stop();
                        queueItem = Connector.queueItemIdPhaseTime(queueItem, Connector.PHASE_PUBLISH,
                                stopWatch.getTime());
                        try {
                            // If queue is full, this thread may block.
                            publishQueue.put(queueItem);
                        } catch (InterruptedException e) {
                            // Restore the interrupted status so parent can handle (if it wants to).
                            Thread.currentThread().interrupt();
                        }
                    } catch (Exception e) {
                        String msgStr = String.format("%s: %s", docId, e.getMessage());
                        appLogger.error(msgStr, e);
                        MailManager mailManager = (MailManager) mAppMgr
                                .getProperty(Connector.PROPERTY_MAIL_NAME);
                        mailManager.addMessage(Connector.PHASE_PUBLISH, Connector.STATUS_MAIL_ERROR, msgStr,
                                Constants.MAIL_DETAIL_MESSAGE);
                    }
                }
            } catch (InterruptedException e) {
                queueItem = StringUtils.EMPTY;
            }
        } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_TRANSFORM, queueItem));

        // Forward the marker queue item to the next queue.

        if (mCrawlQueue.isQueueItemMarker(queueItem)) {
            try {
                // If queue is full, this thread may block.
                publishQueue.put(queueItem);
            } catch (InterruptedException e) {
                // Restore the interrupted status so parent can handle (if it wants to).
                Thread.currentThread().interrupt();
            }
        }

        // Now we can shutdown our search indexer publisher.

        try {
            indexPublishers.shutdown();
        } catch (NSException e) {
            appLogger.error("Publisher shutdown: " + e.getMessage());
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.qualogy.qafe.mgwt.server.RPCServiceImpl.java

public GDataObject executeEvent(EventDataGVO eventData) throws GWTServiceException {
    StopWatch stopWatch = new StopWatch();
    try {//www  . j a  v  a  2 s . co  m

        stopWatch.start();

        String appIdUUID = eventData.getUuid().substring(eventData.getUuid().lastIndexOf('|') + 1);// uuid.substring(uuid.lastIndexOf('|')+1);
        ApplicationIdentifier appId = service.getApplicationId(appIdUUID);
        GDataObject gDataObject = null;
        if (appId != null) {
            eventData.setContext(appId.toString());
            resolveRequest(eventData);
            gDataObject = eventProcessor.execute(eventData, appId,
                    new SessionContainer(getLocale(), eventData.getParameters()));
        }
        stopWatch.stop();

        if (gDataObject != null) {
            gDataObject.setTime(Long.valueOf(stopWatch.getTime()));
        }
        return gDataObject;
    } catch (Exception e) {
        GWTServiceException gWTServiceException = handleException(e);
        gWTServiceException.setGDataObject(ExceptionProcessor.handle(eventData, e));
        stopWatch.stop();
        if (gWTServiceException.getGDataObject() != null) {
            gWTServiceException.getGDataObject().setTime(Long.valueOf(stopWatch.getTime()));
        }
        throw gWTServiceException;
    }
}

From source file:com.liferay.portal.servlet.filters.doubleclick.DoubleClickFilter.java

@Override
protected void processFilter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
        throws Exception {

    StopWatch stopWatch = null;

    if (_log.isDebugEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();//from  w w  w  . j  a v  a2s.  com
    }

    HttpSession session = request.getSession(false);

    if (session == null) {
        processFilter(DoubleClickFilter.class, request, response, filterChain);
    } else {
        DoubleClickController doubleClickController = null;

        synchronized (session) {
            doubleClickController = (DoubleClickController) session.getAttribute(_CONTROLLER_KEY);

            if (doubleClickController == null) {
                doubleClickController = new DoubleClickController();

                session.setAttribute(_CONTROLLER_KEY, doubleClickController);
            }
        }

        boolean ok = false;

        try {
            doubleClickController.control(request, response, filterChain);

            ok = true;
        } finally {
            if (stopWatch != null) {
                String completeURL = HttpUtil.getCompleteURL(request);

                if (ok) {
                    _log.debug("Double click prevention succeeded in " + stopWatch.getTime() + " ms for "
                            + completeURL);
                } else {
                    _log.debug("Double click prevention failed in " + stopWatch.getTime() + " ms for "
                            + completeURL);
                }
            }
        }
    }
}

From source file:com.liferay.portal.search.elasticsearch.internal.ElasticsearchIndexSearcher.java

@Override
public long searchCount(SearchContext searchContext, Query query) throws SearchException {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/* ww  w .  j  a  v  a  2  s. co m*/

    try {
        return doSearchCount(searchContext, query);
    } catch (Exception e) {
        if (_log.isWarnEnabled()) {
            _log.warn(e, e);
        }

        if (!_logExceptionsOnly) {
            throw new SearchException(e.getMessage(), e);
        }

        return 0;
    } finally {
        if (_log.isInfoEnabled()) {
            stopWatch.stop();

            _log.info(StringBundler.concat("Searching ", query.toString(), " took ",
                    String.valueOf(stopWatch.getTime()), " ms"));
        }
    }
}

From source file:com.liferay.portal.search.elasticsearch.ElasticsearchQuerySuggester.java

@Override
public String[] suggestKeywordQueries(SearchContext searchContext, int max) {

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
        stopWatch = new StopWatch();

        stopWatch.start();//  w  w w  .ja  va2 s .  c om
    }

    SuggestBuilder.SuggestionBuilder<PhraseSuggestionBuilder> suggestionBuilder = SuggestBuilder
            .phraseSuggestion(_REQUEST_TYPE_KEYWORD_QUERY);

    Suggest.Suggestion<?> suggestion = getSuggestion(searchContext, suggestionBuilder,
            DocumentTypes.KEYWORD_QUERY, Field.KEYWORD_SEARCH, _REQUEST_TYPE_KEYWORD_QUERY, max);

    List<?> entries = suggestion.getEntries();

    Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option> suggestionEntry = (Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>) entries
            .get(0);

    List<String> keywordQueries = new ArrayList<String>();

    for (Suggest.Suggestion.Entry.Option option : suggestionEntry.getOptions()) {

        String optionText = String.valueOf(option.getText());

        keywordQueries.add(optionText);
    }

    if (_log.isInfoEnabled()) {
        stopWatch.stop();

        _log.info("Suggested keyword queries in " + stopWatch.getTime() + "ms");
    }

    return keywordQueries.toArray(new String[keywordQueries.size()]);
}

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;/* ww  w .  j  ava2 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 given test in a new thread with specified timeout
 * (DEFAULT_TIMEOUT_IN_SECONDS) and stores the results in given testResult.
 * //from   w  w  w  .j a v  a2  s  . c o  m
 * @param r
 *            the test to be run
 * @return the time needed for executing the test
 */
protected long runWithTimeoutOld(MutationTestRunnable r) {
    // ArrayList<Thread> threadsPre = ThreadUtil.getThreads();
    ExecutorService service = Executors.newSingleThreadExecutor();
    Future<?> future = service.submit(r);
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    service.shutdown();
    String exceptionMessage = null;
    Throwable capturedThrowable = null;
    try {
        logger.debug("Start  test: ");
        boolean terminated = service.awaitTermination(timeout, TimeUnit.SECONDS);
        logger.debug("First timeout");
        long time1 = stopWatch.getTime();
        if (!terminated) {
            service.shutdownNow();
        }
        future.get(1, TimeUnit.SECONDS);
        logger.debug("Second timeout");
        long time2 = stopWatch.getTime();
        if (time2 - time1 > 1000) {
            logger.info("Process got some extra time: " + (time2 - time1) + "  " + time2);
        }
        future.cancel(true);

    } catch (InterruptedException e) {
        capturedThrowable = e;
    } catch (ExecutionException e) {
        capturedThrowable = e;
    } catch (TimeoutException e) {
        exceptionMessage = "Mutation causes test timeout";
        capturedThrowable = e;
    } catch (Throwable t) {
        capturedThrowable = t;
    } finally {
        if (capturedThrowable != null) {
            if (exceptionMessage == null) {
                exceptionMessage = "Exception caught during test execution.";
            }
            r.setFailed(exceptionMessage, capturedThrowable);
        }
    }
    if (!future.isDone()) {
        r.setFailed("Mutated Thread is still running after timeout.", null);
        switchOfMutation(future);
    }
    stopWatch.stop();

    if (!r.hasFinished()) {
        shutDown(r, stopWatch);
    }
    logger.debug("End timed test, it took " + stopWatch.getTime() + " ms");
    return stopWatch.getTime();
}

From source file:com.nridge.connector.fs.con_fs.core.FileCrawler.java

private void saveAddQueueDocument(Document aDocument, StopWatch aStopWatch) throws IOException {
    Logger appLogger = mAppMgr.getLogger(this, "saveAddQueueDocument");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    if (!mIsValidationOnly) {
        DataBag dataBag = aDocument.getBag();
        DataField dataField = dataBag.getPrimaryKeyField();
        if (dataField == null)
            appLogger.error("Primary key field is missing from bag - cannot add to queue.");
        else {//w w w  . j av a2 s . c o m
            String docId = dataField.getValueAsString();

            String queueBagPathFileName = mCrawlQueue.docPathFileName(Connector.QUEUE_EXTRACT_NAME, docId);
            DocumentXML documentXML = new DocumentXML(aDocument);
            documentXML.save(queueBagPathFileName);

            aStopWatch.stop();
            String queueItem = Connector.queueItemIdPhaseTime(docId, Connector.PHASE_EXTRACT,
                    aStopWatch.getTime());
            try {
                // If queue is full, this thread may block.
                mExtractQueue.put(queueItem);
            } catch (InterruptedException e) {
                // Restore the interrupted status so parent can handle (if it wants to).
                Thread.currentThread().interrupt();
            }
        }
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.liferay.portal.search.elasticsearch.internal.ElasticsearchQuerySuggester.java

protected Suggest doSuggest(Suggester suggester, SearchContext searchContext) {

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();/* ww w.  java 2s .co  m*/

    Client client = elasticsearchConnectionManager.getClient();

    SuggestRequestBuilder suggestRequestBuilder = client
            .prepareSuggest(indexNameBuilder.getIndexName(searchContext.getCompanyId()));

    SuggestBuilder suggestBuilder = suggesterTranslator.translate(suggester, searchContext);

    for (SuggestBuilder.SuggestionBuilder<?> suggestionBuilder : suggestBuilder.getSuggestion()) {

        suggestRequestBuilder.addSuggestion(suggestionBuilder);
    }

    if (suggester instanceof AggregateSuggester) {
        AggregateSuggester aggregateSuggester = (AggregateSuggester) suggester;

        suggestRequestBuilder.setSuggestText(aggregateSuggester.getValue());
    }

    SuggestResponse suggestResponse = suggestRequestBuilder.get();

    Suggest suggest = suggestResponse.getSuggest();

    if (_log.isInfoEnabled()) {
        stopWatch.stop();

        _log.info("Spell checked keywords in " + stopWatch.getTime() + "ms");
    }

    return suggest;
}

From source file:com.qualogy.qafe.gwt.server.RPCServiceImpl.java

public GDataObject executeEvent(EventDataGVO eventData)
        throws GWTServiceException, GWTApplicationStoreException {
    StopWatch stopWatch = new StopWatch();
    logger.info("Event started[thread id=" + Thread.currentThread().getId() + "]");
    stopWatch.start();// w  w w. j a  v  a2  s  .co  m

    try {
        String appIdUUID = eventData.getUuid().substring(eventData.getUuid().lastIndexOf('|') + 1);// uuid.substring(uuid.lastIndexOf('|')+1);
        ApplicationIdentifier appId = service.getApplicationId(appIdUUID);

        GDataObject gDataObject = null;
        if (appId != null) {
            eventData.setContext(appId.toString());
            resolveRequest(eventData);
            gDataObject = eventProcessor.execute(eventData, appId,
                    new SessionContainer(getLocale(), eventData.getParameters()));

            if (gDataObject != null) {
                gDataObject.setTime(Long.valueOf(stopWatch.getTime()));
            }

        }

        //Probably it's not possible to retrieve the user data from the local store.
        if (gDataObject == null) {
            logger.info("gDataObject is null!");
            throw new GWTApplicationStoreException();
        }

        stopWatch.stop();
        logger.info("Event ends[thread id=" + Thread.currentThread().getId() + "]");

        return gDataObject;
    } catch (GWTApplicationStoreException gwtApplicationStoreException) {
        throw new GWTApplicationStoreException();
    } catch (Exception e) {
        GWTServiceException gWTServiceException = handleException(e);
        gWTServiceException.setGDataObject(ExceptionProcessor.handle(eventData, e));
        stopWatch.stop();
        if (gWTServiceException.getGDataObject() != null) {
            gWTServiceException.getGDataObject().setTime(Long.valueOf(stopWatch.getTime()));
        }
        logger.info("Event ends[thread id=" + Thread.currentThread().getId() + "]");
        throw gWTServiceException;
    }
}