Example usage for org.springframework.util StopWatch stop

List of usage examples for org.springframework.util StopWatch stop

Introduction

In this page you can find the example usage for org.springframework.util StopWatch stop.

Prototype

public void stop() throws IllegalStateException 

Source Link

Document

Stop the current task.

Usage

From source file:org.alfresco.repo.search.impl.solr.DbOrIndexSwitchingQueryLanguage.java

private ResultSet executeHybridQuery(SearchParameters searchParameters,
        ADMLuceneSearcherImpl admLuceneSearcher) {
    if (indexQueryLanguage == null || dbQueryLanguage == null) {
        throw new QueryModelException("Both index and DB query language required for hybrid search [index="
                + indexQueryLanguage + ", DB=" + dbQueryLanguage + "]");
    }/*  ww  w  . j  a  va 2 s  .  c  o m*/

    StopWatch stopWatch = new StopWatch("hybrid search");
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Hybrid search, using SOLR query: " + dbQueryLanguage.getName() + " for " + searchParameters);
    }
    stopWatch.start("index query");
    ResultSet indexResults = indexQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("SOLR query returned " + indexResults.length() + " results in "
                + stopWatch.getLastTaskTimeMillis() + "ms");
    }
    // TODO: if the results are up-to-date, then nothing more to do - return the results.

    if (!(indexResults instanceof SolrJSONResultSet)) {
        if (logger.isWarnEnabled()) {
            logger.warn("Hybrid search can only use database when SOLR is also in use. "
                    + "Skipping DB search, returning results from index.");
        }
        return indexResults;
    }

    long lastTxId = ((SolrJSONResultSet) indexResults).getLastIndexedTxId();
    searchParameters.setSinceTxId(lastTxId);
    if (logger.isDebugEnabled()) {
        logger.debug(
                "Hybrid search, using DB query: " + dbQueryLanguage.getName() + " for " + searchParameters);
    }
    stopWatch.start("database query");
    ResultSet dbResults = dbQueryLanguage.executeQuery(searchParameters, admLuceneSearcher);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("DB query returned " + dbResults.length() + " results in "
                + stopWatch.getLastTaskTimeMillis() + "ms");
    }
    // Merge result sets
    List<ChildAssociationRef> childAssocs = new ArrayList<>();
    NodeParameters nodeParameters = new NodeParameters();
    nodeParameters.setFromTxnId(lastTxId + 1);
    // TODO: setToTxnId(null) when SolrDAO behaviour is fixed.
    nodeParameters.setToTxnId(Long.MAX_VALUE);
    stopWatch.start("get changed nodes");
    List<Node> changedNodeList = solrDao.getNodes(nodeParameters, null);
    stopWatch.stop();
    if (logger.isDebugEnabled()) {
        logger.debug("Nodes changed since last indexed transaction (ID " + lastTxId + ") = "
                + changedNodeList.size() + " (took " + stopWatch.getLastTaskTimeMillis() + "ms)");
    }
    stopWatch.start("merge result sets");
    Set<NodeRef> nodeRefs = new HashSet<>(changedNodeList.size());
    for (Node n : changedNodeList) {
        nodeRefs.add(n.getNodeRef());
    }
    // Only use the SOLR results for nodes that haven't changed since indexing.
    for (ChildAssociationRef car : indexResults.getChildAssocRefs()) {
        if (!nodeRefs.contains(car.getChildRef())) {
            childAssocs.add(car);
        }
    }
    // Merge in all the database results.
    childAssocs.addAll(dbResults.getChildAssocRefs());

    ResultSet results = new ChildAssocRefResultSet(nodeService, childAssocs);
    stopWatch.stop(); // merge result sets
    if (logger.isDebugEnabled()) {
        String stats = String.format("SOLR=%d, DB=%d, total=%d", indexResults.length(), dbResults.length(),
                results.length());
        logger.debug("Hybrid search returning combined results with counts: " + stats);
        logger.debug(stopWatch.prettyPrint());
    }
    return results;
}

From source file:org.eurekastreams.server.aop.PerformanceTimer.java

/**
 * Method for logging timing data.//from   w  w w. j  a v a2 s.  c o  m
 * 
 * @param call
 *            {@link ProceedingJoinPoint}
 * @return result of wrapped method.
 * @throws Throwable
 *             on error.
 */
public Object profile(final ProceedingJoinPoint call) throws Throwable {
    StopWatch clock = null;

    // get the perf log for target object.
    Log log = LogFactory.getLog("perf.timer." + call.getTarget().getClass().getCanonicalName());
    try {
        if (log.isInfoEnabled()) {
            clock = new StopWatch();
            clock.start(call.toShortString());
        }
        return call.proceed();
    } finally {
        if (log.isInfoEnabled() && clock != null) {
            clock.stop();

            Object[] args = call.getArgs();
            StringBuffer params = new StringBuffer();
            for (Object obj : args) {
                params.append("Param: " + ((obj == null) ? "null" : obj.toString()) + "\n\t");
            }

            log.info(clock.getTotalTimeMillis() + " (ms) - " + call.getTarget().getClass().getSimpleName() + "."
                    + call.getSignature().toShortString() + "\n\t" + params.toString());
        }

    }
}

From source file:org.flockdata.integration.FileProcessor.java

public int endProcess(StopWatch watch, int rows, int ignoreCount) {
    watch.stop();
    double mins = watch.getTotalTimeSeconds() / 60;
    long rowsProcessed = rows - skipCount;
    if (skipCount > 0)
        logger.info(/* w  w w. j  a  v a2 s  .c  om*/
                "Completed [{}] rows in [{}] secs. rpm [{}]. Skipped first [{}] rows, finished on row {}, ignored [{}] rows",
                rowsProcessed, formatter.format(watch.getTotalTimeSeconds()),
                formatter.format(rowsProcessed / mins), skipCount, rows, ignoreCount);
    else
        logger.info("Completed [{}] rows in [{}] secs. rpm [{}] Finished on row [{}], ignored [{}] rows.",
                rowsProcessed, formatter.format(watch.getTotalTimeSeconds()),
                formatter.format(rowsProcessed / mins), rows, ignoreCount);
    return rows;
}

From source file:org.hyperic.hq.monitor.aop.aspects.PerformanceMonitor.java

/**
 * We could bind the @Transactional annotation to the context but there's no
 * way to know if the method or the type is annotated, causing a false
 * negative.//from w w  w  .j a va 2s.c  o  m
 * @see org.hyperic.hq.monitor.aop.MonitorArchitecture
 * @param pjp
 */
@Around("org.hyperic.hq.monitor.aop.MonitorArchitecture.serviceLayerOperationDuration()")
public Object monitorServiceMethod(ProceedingJoinPoint pjp) throws Throwable {

    Object invocation = null;

    final StopWatch timer = new StopWatch(pjp.getSignature() + Thread.currentThread().getName());

    try {
        timer.start();
        invocation = pjp.proceed();
    } finally {
        timer.stop();
    }

    long duration = timer.getTotalTimeMillis();

    if (duration > maximumDuration) {
        logger.warn(new StringBuilder(warningMessage).append(pjp.getSignature()).append(" executed in ")
                .append(timer.getTotalTimeMillis()).append(":ms").toString());
    }

    return invocation;
}

From source file:org.hyperic.hq.ui.action.portlet.autoDisc.ViewAction.java

public ActionForward execute(ComponentContext context, ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();

    WebUser user = RequestUtils.getWebUser(request);
    int sessionId = user.getSessionId().intValue();
    AIQueueForm queueForm = (AIQueueForm) form;

    PageControl page = new PageControl();

    DashboardConfig dashConfig = dashboardManager
            .findDashboard((Integer) session.getAttribute(Constants.SELECTED_DASHBOARD_ID), user, authzBoss);
    ConfigResponse dashPrefs = dashConfig.getConfig();
    page.setPagesize(Integer.parseInt(dashPrefs.getValue(".dashContent.autoDiscovery.range")));

    StopWatch watch = new StopWatch();
    if (log.isDebugEnabled()) {
        watch.start("getQueue");
    }/* w w w .  j  a v  a 2s  . co m*/
    // always show ignored platforms and already-processed platforms
    PageList<AIPlatformValue> aiQueue = aiBoss.getQueue(sessionId, true, false, true, page);

    if (log.isDebugEnabled()) {
        watch.stop();
        log.debug(watch.prettyPrint());
    }
    List<AIPlatformWithStatus> queueWithStatus = getStatuses(sessionId, aiQueue);
    context.putAttribute("resources", queueWithStatus);

    // If the queue is empty, check to see if there are ANY agents
    // defined in HQ inventory.
    if (aiQueue.size() == 0) {
        int agentCnt = appdefBoss.getAgentCount(sessionId);
        request.setAttribute("hasNoAgents", new Boolean(agentCnt == 0));
    }

    // check every box for queue
    Integer[] platformsToProcess = new Integer[aiQueue.size()];
    List<Integer> serversToProcess = new ArrayList<Integer>();
    AIPlatformValue aiPlatform;
    AIServerValue[] aiServers;
    for (int i = 0; i < platformsToProcess.length; i++) {
        aiPlatform = aiQueue.get(i);
        platformsToProcess[i] = aiPlatform.getId();

        // Add all non-virtual servers on this platform
        aiServers = aiPlatform.getAIServerValues();
        for (int j = 0; j < aiServers.length; j++) {
            if (!BizappUtils.isAutoApprovedServer(sessionId, appdefBoss, aiServers[j])) {
                serversToProcess.add(aiServers[j].getId());
            }
        }
    }
    queueForm.setPlatformsToProcess(platformsToProcess);
    queueForm.setServersToProcess(serversToProcess);

    // clean out the return path
    SessionUtils.resetReturnPath(request.getSession());

    // Check for previous error
    // First, check for ignore error.
    Object ignoreErr = request.getSession().getAttribute(Constants.IMPORT_IGNORE_ERROR_ATTR);
    if (ignoreErr != null) {
        ActionMessage err = new ActionMessage("dash.autoDiscovery.import.ignore.Error");
        RequestUtils.setError(request, err, ActionMessages.GLOBAL_MESSAGE);
        // Only show the error once
        request.getSession().setAttribute(Constants.IMPORT_IGNORE_ERROR_ATTR, null);
    }

    // Check for import exception
    Exception exc = (Exception) request.getSession().getAttribute(Constants.IMPORT_ERROR_ATTR);
    if (exc != null) {
        request.getSession().removeAttribute(Constants.IMPORT_ERROR_ATTR);
        log.error("Failed to approve AI report", exc);
        ActionMessage err = new ActionMessage("dash.autoDiscovery.import.Error", exc);
        RequestUtils.setError(request, err, ActionMessages.GLOBAL_MESSAGE);
    }
    return null;
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testHighLoadDeactivation() throws InterruptedException {

    logger.info("Starting testHighLoadDeactivation test...");

    RequestLoadAverage.RequestCountProvider requestCountProvider = new RequestLoadAverage.RequestCountProvider() {
        public long getRequestCount() {
            return 100;
        }//from w  w  w.  j a v  a  2  s.c  o  m
    };

    RequestLoadAverage requestLoadAverage = new RequestLoadAverage("requestLoadAverage", requestCountProvider);
    requestLoadAverage.start();
    logger.info("Waiting for load average to reach 10...");
    while (requestLoadAverage.getOneMinuteLoad() < 10.0) {
        Thread.sleep(500);
    }

    StopWatch stopWatch = new StopWatch("testHighLoadDeactivation");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    int fileCountBeforeTest = 0;
    if (todaysDirectory.exists()) {
        File[] files = todaysDirectory.listFiles();
        fileCountBeforeTest = (files == null ? 0 : files.length);
    }

    ErrorFileDumper.setHighLoadBoundary(10.0);
    ErrorFileDumper.start();

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    RequestLoadAverage.getInstance().stop();

    int fileCountAfterTest = 0;
    if (todaysDirectory.exists()) {
        File[] files = todaysDirectory.listFiles();
        fileCountAfterTest = (files == null ? 0 : files.length);
    }

    Assert.assertEquals("File count should stay the same because high load deactivates file dumping !",
            fileCountBeforeTest, fileCountAfterTest);

    requestLoadAverage = new RequestLoadAverage("requestLoadAverage");
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumperInSequence() throws InterruptedException {

    logger.info("Starting testDumperInSequence test...");

    StopWatch stopWatch = new StopWatch("testDumperInSequence");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();/*from  w  ww .j ava2 s .c o  m*/

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    Assert.assertTrue("Error dump directory does not exist !", todaysDirectory.exists());
    Assert.assertTrue("Error dump directory should have error files in it !",
            todaysDirectory.listFiles().length > 0);
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumpErrorsToFilesSetting() throws InterruptedException {
    logger.info("Starting testDumpErrorsToFilesSetting test...");

    StopWatch stopWatch = new StopWatch("testDumpErrorsToFilesSetting");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();/*from w w w .  ja  v a2  s .  c o  m*/
    ErrorFileDumper.setFileDumpActivated(false);

    generateExceptions();

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    ErrorFileDumper.shutdown(10000L);

    SettingsBean.getInstance().setDumpErrorsToFiles(true);
    Assert.assertFalse("Error dump directory should not exist !", todaysDirectory.exists());
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testDumperInParallel() throws IOException, InterruptedException {

    logger.info("Starting testDumperInParallel test...");

    StopWatch stopWatch = new StopWatch("testDumperInParallel");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();//from  w  w  w.java  2 s  .  co m

    threadSet.clear();

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread newThread = new Thread(new Runnable() {

            public void run() {
                generateExceptions();
            }
        }, "ErrorFileDumperTestThread" + i);
        threadSet.add(newThread);
        newThread.start();
    }

    logger.info("Waiting for dumps to be processed...");

    for (Thread curThread : threadSet) {
        curThread.join();
    }

    ErrorFileDumper.shutdown(10000L);

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());

    Assert.assertTrue("Error dump directory does not exist !", todaysDirectory.exists());
    Assert.assertTrue("Error dump directory should have error files in it !",
            todaysDirectory.listFiles().length > 0);
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

@Test
public void testOutputSystemInfoAllInParallel() throws InterruptedException {

    logger.info("Starting testOutputSystemInfoAllInParallel test...");

    StopWatch stopWatch = new StopWatch("testDumperInParallel");
    stopWatch.start(Thread.currentThread().getName() + " generating error dumps");

    ErrorFileDumper.start();// w  w  w .j  ava2 s .c  o m

    threadSet.clear();
    final int[] dumpLengths = new int[(int) THREAD_COUNT];

    for (int i = 0; i < THREAD_COUNT; i++) {
        final int threadCounter = i;
        Thread newThread = new Thread(new Runnable() {

            public void run() {
                // this is the call made in errors.jsp file.
                StringWriter stringWriter = new StringWriter();
                ErrorFileDumper.outputSystemInfo(new PrintWriter(stringWriter));
                dumpLengths[threadCounter] = stringWriter.toString().length();
                stringWriter = null;
            }
        }, "ErrorFileDumperTestThread" + i);
        threadSet.add(newThread);
        newThread.start();
    }

    logger.info("Waiting for dumps to be processed...");

    for (Thread curThread : threadSet) {
        curThread.join();
    }

    ErrorFileDumper.shutdown(10000L);

    stopWatch.stop();
    long totalTime = stopWatch.getTotalTimeMillis();
    double averageTime = ((double) totalTime) / ((double) LOOP_COUNT);
    logger.info("Milliseconds per exception = " + averageTime);
    logger.info(stopWatch.prettyPrint());
    for (int dumpLength : dumpLengths) {
        Assert.assertTrue("System info dump is empty", dumpLength > 0);
    }
}