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.jahia.tools.jvm.ThreadMonitorTestIT.java

private void runParallelTest(String testName, Runnable runnable) throws InterruptedException {

    StopWatch stopWatch = new StopWatch(testName);
    stopWatch.start(Thread.currentThread().getName() + " dumping thread info");

    threadSet.clear();/*from  w ww . j a va 2s .c om*/
    ThreadMonitor.getInstance().setActivated(true);
    ThreadMonitor.getInstance().setDebugLogging(enabledDebugLogging);
    ThreadMonitor.getInstance().setMinimalIntervalBetweenDumps(minimalIntervalBetweenDumps);

    for (int i = 0; i < THREAD_COUNT; i++) {
        Thread newThread = new Thread(runnable, testName + i);
        threadSet.add(newThread);
        Thread.yield();
        Thread.sleep(50);
        newThread.start();
    }

    logger.info("Waiting for test completion...");

    Thread.yield();
    while (ThreadMonitor.getInstance().isDumping()) {
        Thread.sleep(100);
    }

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

    ThreadMonitor.shutdownInstance();

    stopWatch.stop();
    logger.info(stopWatch.prettyPrint());

    Thread.sleep(minimalIntervalBetweenDumps * 2);
}

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();/* w w  w  . j  ava  2s.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  av  a2  s.  c o 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   ww w.ja  v  a  2 s. c o 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 = 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 w w w  . j  av a2s .c  o  m*/
    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 w  w .j ava 2  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();//  ww w  .ja v a 2  s . co  m

    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  va2 s . 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);/*from   ww  w.ja va  2s  . com*/
    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);/*from  w w w.j  a  va 2  s  . c  om*/
    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);
}