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

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

Introduction

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

Prototype

public void start() 

Source Link

Document

Start the stopwatch.

This method starts a new timing session, clearing any previous values.

Usage

From source file:ch.systemsx.cisd.openbis.generic.server.authorization.DefaultReturnValueFilter.java

public final Object applyFilter(final IAuthSession session, final Method method,
        final Object returnValueOrNull) {
    assert session != null : "Unspecified session";
    assert method != null : "Unspecified method";
    final StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    try {/*w w w  .  j a v  a2 s  .c  om*/
        if (returnValueOrNull == null) {
            operationLog.debug(String.format(NULL_RETURN_VALUE_MSG_FORMAT, MethodUtils.describeMethod(method)));
            return returnValueOrNull;
        }
        final ReturnValueFilter annotation = method.getAnnotation(ReturnValueFilter.class);
        if (annotation == null) {
            operationLog.debug(String.format(NO_ANNOTATION_FOUND_MSG_FORMAT, MethodUtils.describeMethod(method),
                    ReturnValueFilter.class.getSimpleName()));
            return returnValueOrNull;
        }
        final IValidator<?> validator = getValidator(annotation);
        return proceed(session.tryGetPerson(), method, returnValueOrNull, validator);
    } finally {
        logTimeTaken(stopWatch, method);
    }
}

From source file:com.continuuity.weave.yarn.YarnWeaveController.java

@Override
protected void doShutDown() {
    if (processController == null) {
        LOG.warn("No process controller for application that is not submitted.");
        return;/*  ww w. ja va  2s  .  c o  m*/
    }

    // Wait for the stop message being processed
    try {
        Uninterruptibles.getUninterruptibly(getStopMessageFuture(), Constants.APPLICATION_MAX_STOP_SECONDS,
                TimeUnit.SECONDS);
    } catch (Exception e) {
        LOG.error("Failed to wait for stop message being processed.", e);
        // Kill the application through yarn
        kill();
    }

    // Poll application status from yarn
    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        stopWatch.split();
        long maxTime = TimeUnit.MILLISECONDS.convert(Constants.APPLICATION_MAX_STOP_SECONDS, TimeUnit.SECONDS);

        YarnApplicationReport report = processController.getReport();
        FinalApplicationStatus finalStatus = report.getFinalApplicationStatus();
        while (finalStatus == FinalApplicationStatus.UNDEFINED && stopWatch.getSplitTime() < maxTime) {
            LOG.debug("Yarn application final status for {} {}", report.getApplicationId(), finalStatus);
            TimeUnit.SECONDS.sleep(1);
            stopWatch.split();
            finalStatus = processController.getReport().getFinalApplicationStatus();
        }
        LOG.debug("Yarn application final status is {}", finalStatus);

        // Application not finished after max stop time, kill the application
        if (finalStatus == FinalApplicationStatus.UNDEFINED) {
            kill();
        }
    } catch (Exception e) {
        LOG.warn("Exception while waiting for application report: {}", e.getMessage(), e);
        kill();
    }

    super.doShutDown();
}

From source file:com.manydesigns.portofino.interceptors.ApplicationInterceptor.java

public Resolution intercept(ExecutionContext context) throws Exception {
    logger.debug("Retrieving Stripes objects");
    ActionBeanContext actionContext = context.getActionBeanContext();

    logger.debug("Retrieving Servlet API objects");
    HttpServletRequest request = actionContext.getRequest();

    logger.debug("Starting page response timer");
    StopWatch stopWatch = new StopWatch();
    // There is no need to stop this timer.
    stopWatch.start();
    request.setAttribute(RequestAttributes.STOP_WATCH, stopWatch);

    Dispatch dispatch = DispatcherUtil.getDispatch(request);
    if (dispatch != null) {
        logger.debug("Preparing PageActions");
        for (PageInstance page : dispatch.getPageInstancePath()) {
            if (page.getParent() == null) {
                logger.debug("Not preparing root");
                continue;
            }//  ww w  .  jav a2 s . c  o m
            if (page.isPrepared()) {
                continue;
            }
            logger.debug("Preparing PageAction {}", page);
            PageAction actionBean = ensureActionBean(page);
            configureActionBean(actionBean, page, request);
            try {
                actionBean.setContext(actionContext);
                actionBean.setPageInstance(page);
                Resolution resolution = actionBean.preparePage();
                if (resolution != null) {
                    logger.debug("PageAction prepare returned a resolution: {}", resolution);
                    request.setAttribute(INVALID_PAGE_INSTANCE, page);
                    return resolution;
                }
                page.setPrepared(true);
            } catch (Throwable t) {
                request.setAttribute(INVALID_PAGE_INSTANCE, page);
                logger.error("PageAction prepare failed for " + page, t);
                if (!PageActionLogic.isEmbedded(actionBean)) {
                    String msg = MessageFormat.format(
                            ElementsThreadLocals.getText("this.page.has.thrown.an.exception.during.execution"),
                            ExceptionUtils.getRootCause(t));
                    SessionMessages.addErrorMessage(msg);
                }
                return new ForwardResolution("/m/pageactions/redirect-to-last-working-page.jsp");
            }
        }
        PageInstance pageInstance = dispatch.getLastPageInstance();
        request.setAttribute(RequestAttributes.PAGE_INSTANCE, pageInstance);
    }

    return context.proceed();
}

From source file:com.liferay.portal.search.lucene.LuceneIndexer.java

protected void reindex(Indexer indexer) throws Exception {
    StopWatch stopWatch = null;

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

        stopWatch.start();
    }//ww w  .j a  va2  s .  c  o m

    if (_log.isInfoEnabled()) {
        _log.info("Reindexing with " + indexer.getClass() + " started");
    }

    indexer.reindex(new String[] { String.valueOf(_companyId) });

    if (_log.isInfoEnabled()) {
        _log.info("Reindexing with " + indexer.getClass() + " completed in "
                + (stopWatch.getTime() / Time.SECOND) + " seconds");
    }
}

From source file:com.nridge.connector.fs.con_fs.core.RunMetricReport.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 ww w.  j  a  v  a2  s  .c o m
 * 
 * The general contract of the method <code>run</code> is that it may
 * take any action whatsoever.
 *
 * @see Thread#run()
 */
@Override
public void run() {
    long msTime;
    String[] phaseTimes;
    double secondsTime, docsPerSecond;
    String docId, queueItem, phaseName;
    Logger appLogger = mAppMgr.getLogger(this, "run");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    long extractCount = 0;
    DescriptiveStatistics dsExtract = new DescriptiveStatistics();
    long transformCount = 0;
    DescriptiveStatistics dsTransform = new DescriptiveStatistics();
    long publishCount = 0;
    DescriptiveStatistics dsPublish = new DescriptiveStatistics();

    BlockingQueue publishQueue = (BlockingQueue) mAppMgr.getProperty(Connector.QUEUE_PUBLISH_NAME);

    do {
        try {
            queueItem = (String) publishQueue.poll(Constants.QUEUE_POLL_TIMEOUT_DEFAULT, TimeUnit.SECONDS);
            if (mCrawlQueue.isQueueItemDocument(queueItem)) {
                StopWatch stopWatch = new StopWatch();
                stopWatch.start();

                docId = Connector.docIdFromQueueItem(queueItem);

                appLogger.debug(String.format("Publish Queue Item: %s", docId));

                phaseTimes = Connector.phaseTimeFromQueueItem(queueItem);
                if (phaseTimes != null) {
                    for (String phaseTime : phaseTimes) {
                        phaseName = Connector.phaseFromPhaseTime(phaseTime);
                        msTime = Connector.timeFromPhaseTime(phaseTime);
                        if (StringUtils.equals(phaseName, Connector.PHASE_EXTRACT)) {
                            extractCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsExtract.addValue(secondsTime);
                        } else if (StringUtils.equals(phaseName, Connector.PHASE_TRANSFORM)) {
                            transformCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsTransform.addValue(secondsTime);
                        } else if (StringUtils.equals(phaseName, Connector.PHASE_PUBLISH)) {
                            publishCount++;
                            secondsTime = msTime / MILLISECONDS_IN_A_SECOND;
                            dsPublish.addValue(secondsTime);
                        }
                    }
                }
            }
        } catch (InterruptedException e) {
            queueItem = StringUtils.EMPTY;
        }
    } while (!mCrawlQueue.isPhaseComplete(Connector.PHASE_PUBLISH, queueItem));

    // Note: This is the end of the queue processing pipeline, so we will not pass on queue item markers.

    // Generate our metrics summary for the log file.

    writePhaseMetric(Connector.PHASE_EXTRACT, extractCount, dsExtract.getSum());
    writePhaseMetric(Connector.PHASE_TRANSFORM, transformCount, dsTransform.getSum());
    writePhaseMetric(Connector.PHASE_PUBLISH, publishCount, dsPublish.getSum());

    double totalTime = dsExtract.getSum() + dsTransform.getSum() + dsPublish.getSum();
    if ((publishCount > 0L) && (totalTime > 0.0))
        docsPerSecond = publishCount / totalTime;
    else
        docsPerSecond = 0.0;
    String msgStr = String.format("Total metric summary: %d documents, %.2f seconds (%.2f docs/sec avg)",
            publishCount, totalTime, docsPerSecond);
    appLogger.info(msgStr);

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);
}

From source file:com.couchbase.graph.CBGraphPerfTest.java

@Test
@RunIf(value = PerfEnabledChecker.class)
public void traverse50KEdges() {
    System.out.println("-- traverse50KEdges");

    int COUNT = 10000;
    String data = "123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790123456790";

    //Create a graph of neighbors and second neighbors
    System.out.println("Creating graph ...");

    Vertex root = graph.addVertex(UUID.randomUUID().toString());

    for (int i = 0; i < COUNT; i++) {

        Vertex v = graph.addVertex(UUID.randomUUID().toString());
        System.out.println("id = " + v.getId());
        v.setProperty("data", data);

        graph.addEdge(null, root, v, "neighbor of");

    }/*from www  . j av  a2 s.c om*/

    //Traverse the graph
    System.out.println("Traversing graph ...");

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

    Iterable<Vertex> vertices = root.getVertices(Direction.OUT);

    for (Vertex v : vertices) {

        System.out.println(v.getId());

    }

    sw.stop();
    System.out.println("Traversed tree in " + sw.getTime() + " ms");
}

From source file:eagle.storage.jdbc.TestJdbcStorage.java

/**
 * TODO: Investigate why writing performance becomes slower as records count increases
 *
 * 1) Wrote 100000 records in about 18820 ms for empty table
 * 2) Wrote 100000 records in about 35056 ms when 1M records in table
 *
 * @throws IOException//from ww w .ja  v a  2 s.com
 */
//@Test
public void testWriterPerformance() throws IOException {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    List<TestTimeSeriesAPIEntity> entityList = new ArrayList<TestTimeSeriesAPIEntity>();
    int i = 0;
    while (i++ < 100000) {
        entityList.add(newInstance());
        if (entityList.size() >= 1000) {
            ModifyResult<String> result = storage.create(entityList, entityDefinition);
            Assert.assertNotNull(result);
            entityList.clear();
        }
    }
    stopWatch.stop();
    LOG.info("Wrote 100000 records in " + stopWatch.getTime() + " ms");
}

From source file:com.cedarsoft.serialization.test.performance.StaxMateDelegatePerformance.java

private void runBenchmark(@Nonnull Runnable runnable, final int count) {
    //Warmup//from  www.j a  va  2 s.  com
    runnable.run();
    runnable.run();
    runnable.run();

    List<Long> times = new ArrayList<Long>();

    for (int i = 0; i < count; i++) {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        runnable.run();
        stopWatch.stop();

        times.add(stopWatch.getTime());
    }

    System.out.println("-----------------------");
    for (Long time : times) {
        System.out.println("--> " + time);
    }
    System.out.println("-----------------------");
}

From source file:com.gst.infrastructure.security.filter.TenantAwareBasicAuthenticationFilter.java

@Override
public void doFilter(final ServletRequest req, final ServletResponse res, final FilterChain chain)
        throws IOException, ServletException {

    final HttpServletRequest request = (HttpServletRequest) req;
    final HttpServletResponse response = (HttpServletResponse) res;

    final StopWatch task = new StopWatch();
    task.start();

    try {/*from   w w  w.ja  v a2  s  .c o  m*/

        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            // ignore to allow 'preflight' requests from AJAX applications
            // in different origin (domain name)
        } else {

            String tenantIdentifier = request.getHeader(this.tenantRequestHeader);

            if (org.apache.commons.lang.StringUtils.isBlank(tenantIdentifier)) {
                tenantIdentifier = request.getParameter("tenantIdentifier");
            }

            if (tenantIdentifier == null && this.exceptionIfHeaderMissing) {
                throw new InvalidTenantIdentiferException(
                        "No tenant identifier found: Add request header of '" + this.tenantRequestHeader
                                + "' or add the parameter 'tenantIdentifier' to query string of request URL.");
            }

            String pathInfo = request.getRequestURI();
            boolean isReportRequest = false;
            if (pathInfo != null && pathInfo.contains("report")) {
                isReportRequest = true;
            }
            final FineractPlatformTenant tenant = this.basicAuthTenantDetailsService
                    .loadTenantById(tenantIdentifier, isReportRequest);

            ThreadLocalContextUtil.setTenant(tenant);
            String authToken = request.getHeader("Authorization");

            if (authToken != null && authToken.startsWith("Basic ")) {
                ThreadLocalContextUtil.setAuthToken(authToken.replaceFirst("Basic ", ""));
            }

            if (!firstRequestProcessed) {
                final String baseUrl = request.getRequestURL().toString().replace(request.getPathInfo(), "/");
                System.setProperty("baseUrl", baseUrl);

                final boolean ehcacheEnabled = this.configurationDomainService.isEhcacheEnabled();
                if (ehcacheEnabled) {
                    this.cacheWritePlatformService.switchToCache(CacheType.SINGLE_NODE);
                } else {
                    this.cacheWritePlatformService.switchToCache(CacheType.NO_CACHE);
                }
                TenantAwareBasicAuthenticationFilter.firstRequestProcessed = true;
            }
        }

        super.doFilter(req, res, chain);
    } catch (final InvalidTenantIdentiferException e) {
        // deal with exception at low level
        SecurityContextHolder.getContext().setAuthentication(null);

        response.addHeader("WWW-Authenticate", "Basic realm=\"" + "Fineract Platform API" + "\"");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    } finally {
        task.stop();
        final PlatformRequestLog log = PlatformRequestLog.from(task, request);
        logger.info(this.toApiJsonSerializer.serialize(log));
    }
}

From source file:de.pro.dbw.application.testdata.service.TipOfTheNightService.java

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {/*w ww. j a  v  a  2s.c o  m*/
            updateProgress(0, saveMaxEntities);
        }

        @Override
        protected Void call() throws Exception {
            LoggerFacade.INSTANCE.deactivate(Boolean.TRUE);

            final StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            final ICrudService crudService = DatabaseFacade.INSTANCE.getCrudService(entityName);
            //                crudService.beginTransaction();
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final TipOfTheNightModel model = new TipOfTheNightModel();
                model.setGenerationTime(TipOfTheNightService.this.createGenerationTime());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault()
                        .getTextWithMaxEntries(LoremIpsum.MAX_ENTRIES_FOR__TIP_OF_THE_NIGHT));

                crudService.create(model, false);
                updateProgress(i - 1, saveMaxEntities);

                crudService.commitTransaction();
                //                    if (i % 250 == 0) {
                //                        crudService.commitTransaction();
                //                        crudService.beginTransaction();
                //                    }
            }

            //                crudService.commitTransaction();

            LoggerFacade.INSTANCE.deactivate(Boolean.FALSE);
            stopWatch.split();
            LoggerFacade.INSTANCE.debug(this.getClass(),
                    "  + " + stopWatch.toSplitString() + " for " + saveMaxEntities + " TipOfTheNights."); // NOI18N
            stopWatch.stop();

            return null;
        }
    };
}