Example usage for org.springframework.util StopWatch StopWatch

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

Introduction

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

Prototype

public StopWatch() 

Source Link

Document

Construct a new StopWatch .

Usage

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");
    }//from   w  ww  .  ja  va 2s  .c  o  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.kuali.kfs.gl.batch.PreScrubberStep.java

@Override
protected CustomBatchExecutor getCustomBatchExecutor() {
    return new CustomBatchExecutor() {
        public boolean execute() {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();//from  ww  w.ja  v  a2  s.c o m

            String inputFile = batchFileDirectoryName + File.separator
                    + GeneralLedgerConstants.BatchFileSystem.BACKUP_FILE
                    + GeneralLedgerConstants.BatchFileSystem.EXTENSION;
            String outputFile = batchFileDirectoryName + File.separator
                    + GeneralLedgerConstants.BatchFileSystem.PRE_SCRUBBER_FILE
                    + GeneralLedgerConstants.BatchFileSystem.EXTENSION;

            PreScrubberReportData preScrubberReportData = null;
            LineIterator oeIterator = null;
            try {
                oeIterator = FileUtils.lineIterator(new File(inputFile));
                preScrubberReportData = preScrubberService.preprocessOriginEntries(oeIterator, outputFile);
            } catch (IOException e) {
                LOG.error("IO exception occurred during pre scrubbing.", e);
                throw new RuntimeException("IO exception occurred during pre scrubbing.", e);
            } finally {
                LineIterator.closeQuietly(oeIterator);
            }

            if (preScrubberReportData != null) {
                new PreScrubberReport().generateReport(preScrubberReportData, preScrubberReportWriterService);
            }

            stopWatch.stop();
            if (LOG.isDebugEnabled()) {
                LOG.debug("scrubber step of took " + (stopWatch.getTotalTimeSeconds() / 60.0)
                        + " minutes to complete");
            }
            return true;
        }
    };
}

From source file:org.kuali.kfs.module.ld.batch.LaborPreScrubberStep.java

/**
 * @see org.kuali.kfs.sys.batch.AbstractWrappedBatchStep#getCustomBatchExecutor()
 *//* ww w  .j  a v  a 2  s  .co m*/
@Override
protected CustomBatchExecutor getCustomBatchExecutor() {
    return new CustomBatchExecutor() {

        /**
         * @see org.kuali.kfs.sys.batch.service.WrappedBatchExecutorService.CustomBatchExecutor#execute()
         */
        public boolean execute() {
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();

            String inputFile = batchFileDirectoryName + File.separator
                    + LaborConstants.BatchFileSystem.BACKUP_FILE
                    + GeneralLedgerConstants.BatchFileSystem.EXTENSION;
            String outputFile = batchFileDirectoryName + File.separator
                    + LaborConstants.BatchFileSystem.PRE_SCRUBBER_FILE
                    + GeneralLedgerConstants.BatchFileSystem.EXTENSION;

            PreScrubberReportData preScrubberReportData = null;
            LineIterator oeIterator = null;
            try {
                oeIterator = FileUtils.lineIterator(new File(inputFile));
                preScrubberReportData = laborPreScrubberService.preprocessOriginEntries(oeIterator, outputFile);
            } catch (IOException e) {
                LOG.error("IO exception occurred during pre scrubbing.", e);
                throw new RuntimeException("IO exception occurred during pre scrubbing.", e);
            } finally {
                LineIterator.closeQuietly(oeIterator);
            }
            if (preScrubberReportData != null) {
                ((WrappingBatchService) laborPreScrubberReportWriterService).initialize();
                new PreScrubberReport().generateReport(preScrubberReportData,
                        laborPreScrubberReportWriterService);
                ((WrappingBatchService) laborPreScrubberReportWriterService).destroy();
            }

            stopWatch.stop();
            if (LOG.isDebugEnabled()) {
                LOG.debug("labor pre-scrubber scrubber step took " + (stopWatch.getTotalTimeSeconds() / 60.0)
                        + " minutes to complete");
            }
            return true;
        }

    };
}

From source file:org.kuali.kfs.sys.batch.Job.java

public static boolean runStep(ParameterService parameterService, String jobName, int currentStepNumber,
        Step step, Date jobRunDate) throws InterruptedException, WorkflowException {
    boolean continueJob = true;
    if (GlobalVariables.getUserSession() == null) {
        LOG.info(new StringBuffer("Started processing step: ").append(currentStepNumber).append("=")
                .append(step.getName()).append(" for user <unknown>"));
    } else {//from w  ww.  j  ava 2 s .c  om
        LOG.info(new StringBuffer("Started processing step: ").append(currentStepNumber).append("=")
                .append(step.getName()).append(" for user ")
                .append(GlobalVariables.getUserSession().getPrincipalName()));
    }

    if (!skipStep(parameterService, step, jobRunDate)) {

        Step unProxiedStep = (Step) ProxyUtils.getTargetIfProxied(step);
        Class<?> stepClass = unProxiedStep.getClass();
        GlobalVariables.clear();

        String stepUserName = KFSConstants.SYSTEM_USER;
        if (parameterService.parameterExists(stepClass, STEP_USER_PARM_NM)) {
            stepUserName = parameterService.getParameterValueAsString(stepClass, STEP_USER_PARM_NM);
        }
        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer("Creating user session for step: ").append(step.getName()).append("=")
                    .append(stepUserName));
        }
        GlobalVariables.setUserSession(new UserSession(stepUserName));
        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer("Executing step: ").append(step.getName()).append("=").append(stepClass));
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(jobName);
        try {
            continueJob = step.execute(jobName, jobRunDate);
        } catch (InterruptedException e) {
            LOG.error("Exception occured executing step", e);
            throw e;
        } catch (RuntimeException e) {
            LOG.error("Exception occured executing step", e);
            throw e;
        }
        stopWatch.stop();
        LOG.info(new StringBuffer("Step ").append(step.getName()).append(" of ").append(jobName)
                .append(" took ").append(stopWatch.getTotalTimeSeconds() / 60.0).append(" minutes to complete")
                .toString());
        if (!continueJob) {
            LOG.info("Stopping job after successful step execution");
        }
    }
    LOG.info(new StringBuffer("Finished processing step ").append(currentStepNumber).append(": ")
            .append(step.getName()));
    return continueJob;
}

From source file:org.kuali.ole.docstore.engine.service.rest.DocstoreRestClient_UT.java

@Test
public void testUpdateAndSearchBib() {

    StopWatch stopWatch = new StopWatch();
    stopWatch.start("Create bib");
    Bib bib = createBibRecord();/*from  www  .  j av  a  2  s . c om*/
    stopWatch.stop();

    String bibId = bib.getId();

    stopWatch.start("Search before create bib");
    searchBibWithTitleNId(bibId, "Thankfulness to Almighty God");
    stopWatch.stop();

    stopWatch.start("Update bib");
    updateTitle(bibId);
    stopWatch.stop();

    stopWatch.start("Search after update bib");
    searchBibWithTitleNId(bibId, "wings of fire");
    stopWatch.stop();

    System.out.println(stopWatch.prettyPrint());

}

From source file:org.kuali.ole.sys.batch.Job.java

public static boolean runStep(ParameterService parameterService, String jobName, int currentStepNumber,
        Step step, Date jobRunDate) throws InterruptedException, WorkflowException {
    boolean continueJob = true;
    if (GlobalVariables.getUserSession() == null) {
        LOG.info(new StringBuffer("Started processing step: ").append(currentStepNumber).append("=")
                .append(step.getName()).append(" for user <unknown>"));
    } else {//from   w ww  . j  a  va2 s  .co  m
        LOG.info(new StringBuffer("Started processing step: ").append(currentStepNumber).append("=")
                .append(step.getName()).append(" for user ")
                .append(GlobalVariables.getUserSession().getPrincipalName()));
    }

    if (!skipStep(parameterService, step, jobRunDate)) {

        Step unProxiedStep = (Step) ProxyUtils.getTargetIfProxied(step);
        Class<?> stepClass = unProxiedStep.getClass();
        GlobalVariables.clear();

        String stepUserName = getOleSelectDocumentService()
                .getSelectParameterValue(org.kuali.ole.sys.OLEConstants.SYSTEM_USER);
        if (parameterService.parameterExists(stepClass, STEP_USER_PARM_NM)) {
            stepUserName = parameterService.getParameterValueAsString(stepClass, STEP_USER_PARM_NM);
        }
        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer("Creating user session for step: ").append(step.getName()).append("=")
                    .append(stepUserName));
        }
        GlobalVariables.setUserSession(new UserSession(stepUserName));
        if (LOG.isInfoEnabled()) {
            LOG.info(new StringBuffer("Executing step: ").append(step.getName()).append("=").append(stepClass));
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start(jobName);
        try {
            continueJob = step.execute(jobName, jobRunDate);
        } catch (InterruptedException e) {
            LOG.error("Exception occured executing step", e);
            throw e;
        } catch (RuntimeException e) {
            LOG.error("Exception occured executing step", e);
            throw e;
        }
        stopWatch.stop();
        LOG.info(new StringBuffer("Step ").append(step.getName()).append(" of ").append(jobName)
                .append(" took ").append(stopWatch.getTotalTimeSeconds() / 60.0).append(" minutes to complete")
                .toString());
        if (!continueJob) {
            LOG.info("Stopping job after successful step execution");
        }
    }
    LOG.info(new StringBuffer("Finished processing step ").append(currentStepNumber).append(": ")
            .append(step.getName()));
    return continueJob;
}

From source file:org.ownchan.server.joint.scheduler.service.SchedulerService.java

public <T> void waitForCronjobFutures(List<Future<T>> futures, String jobName, Logger jobLogger) {
    jobLogger.debug(jobName + " started...");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();/*from  www.  j a v  a 2  s  .  com*/

    long countProcessed = 0;
    long countFailed = 0;
    for (Future<T> future : futures) {
        try {
            // result might be of type Void, so in fact we might not get a result at all ...
            T result = future.get();
            if (result instanceof Boolean && !(Boolean) result) {
                ++countFailed;
            }
        } catch (Exception e) {
            Throwable t = unwrapExecutionExceptionIfPossible(e);
            jobLogger.error(t.getMessage(), t);
            ++countFailed;
        }

        ++countProcessed;
    }

    stopWatch.stop();

    jobLogger.info(MESSAGE_TEMPLATE_PROCESSED, jobName, countProcessed, countFailed,
            DurationFormatUtils.formatDurationHMS(stopWatch.getTotalTimeMillis()));
}

From source file:org.patientview.monitoring.ImportMonitor.java

public static void main(String[] args) {

    int importFileCheckCount = 0;

    while (true) {
        LOGGER.info("******** Import Logger & Monitor wakes up ********");

        int monitoringFrequencyInMinutes = Integer.parseInt(getProperty("importerMonitor.frequency.minutes"));
        numberOfLinesToRead = monitoringFrequencyInMinutes / FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES;

        LOGGER.info("Import file counts will be logged every {} minutes, whereas a "
                + "health check will be done every {} minutes. Each monitoring will check the last {} lines "
                + "of the log",
                new Object[] { FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES, monitoringFrequencyInMinutes,
                        numberOfLinesToRead });

        StopWatch sw = new StopWatch();
        sw.start();/*from   w  w  w.  j a v  a  2s . c o  m*/

        importFileCheckCount = importFileCheckCount + FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES;

        /**
         * Get the folders that will be monitored
         */
        List<FolderToMonitor> foldersToMonitor = getFoldersToMonitor();

        /**
         * Count the number of files in these folders
         */
        setTheNumberOfCurrentFilesToFolderObjects(foldersToMonitor);

        /**
         * Log counts to a file
         */
        logNumberOfFiles(foldersToMonitor);

        /**
         * If it is time, check the overall monitor stability as well
         */
        if (importFileCheckCount == numberOfLinesToRead) {
            monitorImportProcess(foldersToMonitor);

            importFileCheckCount = 0;
        } else {
            LOGGER.info("Next monitoring will happen in {} minutes",
                    numberOfLinesToRead - importFileCheckCount);
        }

        sw.stop();
        LOGGER.info("ImportMonitor ends, it took {} (mm:ss)",
                new SimpleDateFormat("mm:ss").format(sw.getTotalTimeMillis()));

        /**
         * Sleep for (frequency - execution time) seconds
         */
        long maxTimeToSleep = FREQUENCY_OF_LOGGING_IMPORT_FILE_COUNTS_IN_MINUTES * SECONDS_IN_MINUTE
                * MILLISECONDS;
        long executionTime = sw.getTotalTimeMillis();
        long timeToSleep = maxTimeToSleep - executionTime;

        // if execution time is more than max time to sleep, then sleep for the max time
        if (timeToSleep < 0) {
            timeToSleep = maxTimeToSleep;
        }

        LOGGER.info("ImportMonitor will now sleep for {} (mm:ss)",
                new SimpleDateFormat("mm:ss").format(timeToSleep));

        try {
            Thread.sleep(timeToSleep);
        } catch (InterruptedException e) {
            LOGGER.error("Import Monitor could not sleep: ", e); // possible insomnia
            System.exit(0);
        }
    }
}

From source file:org.springframework.amqp.rabbit.core.BatchingRabbitTemplateTests.java

@Test
public void testDebatchByContainerPerformance() throws Exception {
    final List<Message> received = new ArrayList<Message>();
    int count = 100000;
    final CountDownLatch latch = new CountDownLatch(count);
    SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(this.connectionFactory);
    container.setQueueNames(ROUTE);/* w w w  .j av a 2  s.c om*/
    container.setMessageListener((MessageListener) message -> {
        received.add(message);
        latch.countDown();
    });
    container.setReceiveTimeout(100);
    container.setPrefetchCount(1000);
    container.setTxSize(1000);
    container.afterPropertiesSet();
    container.start();
    try {
        BatchingStrategy batchingStrategy = new SimpleBatchingStrategy(1000, Integer.MAX_VALUE, 30000);
        BatchingRabbitTemplate template = new BatchingRabbitTemplate(batchingStrategy, this.scheduler);
        //         RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(this.connectionFactory);
        MessageProperties props = new MessageProperties();
        props.setDeliveryMode(MessageDeliveryMode.NON_PERSISTENT);
        Message message = new Message(new byte[256], props);
        StopWatch watch = new StopWatch();
        watch.start();
        for (int i = 0; i < count; i++) {
            template.send("", ROUTE, message);
        }
        assertTrue(latch.await(60, TimeUnit.SECONDS));
        watch.stop();
        // System .out .println(watch.getTotalTimeMillis());
        assertEquals(count, received.size());
    } finally {
        container.stop();
    }
}

From source file:org.springframework.aop.aspectj.autoproxy.AspectJAutoProxyCreatorTests.java

@Test
public void testAspectsAndAdvisorAppliedToPrototypeIsFastEnough() {
    Assume.group(TestGroup.PERFORMANCE);
    Assume.notLogging(factoryLog);/*w  w  w  .j a  v  a 2s.c o m*/
    ClassPathXmlApplicationContext ac = newContext("aspectsPlusAdvisor.xml");
    StopWatch sw = new StopWatch();
    sw.start("Prototype Creation");
    for (int i = 0; i < 10000; i++) {
        ITestBean shouldBeWeaved = (ITestBean) ac.getBean("adrian2");
        if (i < 10) {
            doTestAspectsAndAdvisorAreApplied(ac, shouldBeWeaved);
        }
    }
    sw.stop();

    // What's a reasonable expectation for _any_ server or developer machine load?
    // 9 seconds?
    assertStopWatchTimeLimit(sw, 9000);
}