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:com.auditbucket.test.functional.TestForceDuplicateRlx.java

@Test
public void uniqueChangeRLXUnderLoad() throws Exception {
    logger.info("uniqueChangeRLXUnderLoad started");
    SecurityContextHolder.getContext().setAuthentication(authMike);
    regService.registerSystemUser(new RegistrationBean("TestTrack", mike, "bah").setIsUnique(false));

    int auditMax = 10;
    int logMax = 10;
    int fortress = 1;
    String simpleJson = "{\"who\":";
    ArrayList<Long> list = new ArrayList<>();

    logger.info("FortressCount: " + fortressMax + " AuditCount: " + auditMax + " LogCount: " + logMax);
    logger.info(/* ww w  .  j  a  v a  2  s.  c o m*/
            "We will be expecting a total of " + (auditMax * logMax * fortressMax) + " messages to be handled");

    StopWatch watch = new StopWatch();
    watch.start();
    double splitTotals = 0;
    long totalRows = 0;
    int auditSleepCount; // Discount all the time we spent sleeping

    DecimalFormat f = new DecimalFormat("##.000");

    while (fortress <= fortressMax) {
        String fortressName = "bulkloada" + fortress;
        int audit = 1;
        long requests = 0;
        auditSleepCount = 0;

        Fortress iFortress = fortressService.registerFortress(new FortressInputBean(fortressName, true));
        requests++;
        logger.info("Starting run for " + fortressName);
        while (audit <= auditMax) {
            MetaInputBean aib = new MetaInputBean(iFortress.getName(), fortress + "olivia@sunnybell.com",
                    "CompanyNode", new DateTime(), "ABC" + audit);
            TrackResultBean arb = trackEP.trackHeader(aib, null, null).getBody();
            requests++;
            int log = 1;
            while (log <= logMax) {
                createLog(simpleJson, aib, arb, log);
                requests++;
                log++;
            } // Logs created
            audit++;
        } // Audit headers finished with
        watch.split();
        double fortressRunTime = (watch.getSplitTime() - auditSleepCount) / 1000d;
        logger.info("*** " + iFortress.getName() + " took " + fortressRunTime + "  avg processing time for ["
                + requests + "] RPS= " + f.format(fortressRunTime / requests) + ". Requests per second "
                + f.format(requests / fortressRunTime));

        splitTotals = splitTotals + fortressRunTime;
        totalRows = totalRows + requests;
        watch.reset();
        watch.start();
        list.add(iFortress.getId());
        fortress++;
    }

    logger.info("*** Created data set in " + f.format(splitTotals) + " fortress avg = "
            + f.format(splitTotals / fortressMax) + " avg processing time per request "
            + f.format(splitTotals / totalRows) + ". Requests per second " + f.format(totalRows / splitTotals));
    watch.reset();
}

From source file:fr.inria.edelweiss.kgdqp.core.CentralizedInferrencing.java

@Override
public void run() {
    StopWatch sw = new StopWatch();
    sw.start();
    ruleEngine.process();/*from w ww  . java2s.  c om*/
    logger.info("Rules applied in " + sw.getTime() + " ms");
}

From source file:io.cloudslang.engine.queue.services.ExecutionQueueServiceImpl.java

@Override
@Transactional//from  w  ww .  j a va 2s  .c om
public void enqueue(List<ExecutionMessage> messages) {
    if (CollectionUtils.isEmpty(messages))
        return;

    if (logger.isDebugEnabled())
        logger.debug("Enqueue " + messages.size() + " messages");
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    // assign worker for messages with pending status
    messages = executionAssignerService.assignWorkers(messages);
    if (logger.isDebugEnabled())
        logger.debug("Messages were assigned successfully");

    final List<ExecutionMessage> stateMessages = new ArrayList<>(messages.size());

    // first fill the execution state id for new insert
    for (ExecutionMessage msg : messages) {
        if (msg.getExecStateId() == ExecutionMessage.EMPTY_EXEC_STATE_ID) {
            long execStateId = executionQueueRepository.generateExecStateId();
            msg.setExecStateId(execStateId);
            stateMessages.add(msg);
        } else if (msg.getPayload() != null && msg.getStatus() == ExecStatus.IN_PROGRESS) {
            stateMessages.add(msg);
        }
    }

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        for (QueueListener listener : listeners) {
            listener.prePersist(messages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }

    stopWatch.split();
    if (stateMessages.size() > 0)
        executionQueueRepository.insertExecutionStates(stateMessages);

    long msgVersion = versionService.getCurrentVersion(VersionService.MSG_RECOVERY_VERSION_COUNTER_NAME);
    executionQueueRepository.insertExecutionQueue(messages, msgVersion);
    if (logger.isDebugEnabled())
        logger.debug("Persistency done in " + (stopWatch.getSplitTime()) + " ms");

    if (CollectionUtils.isNotEmpty(listeners)) {
        stopWatch.split();
        List<ExecutionMessage> failedMessages = filter(messages, ExecStatus.FAILED);
        List<ExecutionMessage> terminatedMessages = filter(messages, ExecStatus.TERMINATED);
        for (QueueListener listener : listeners) {
            listener.onEnqueue(messages, messages.size());
            if (failedMessages.size() > 0)
                listener.onFailed(failedMessages);
            if (terminatedMessages.size() > 0)
                listener.onTerminated(terminatedMessages);
        }
        if (logger.isDebugEnabled())
            logger.debug("Listeners done in " + (stopWatch.getSplitTime()) + " ms");
    }
    if (logger.isDebugEnabled())
        logger.debug("Enqueue done in " + (stopWatch.getTime()) + " ms");
}

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

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {//from w ww.  j  ava  2s.  com
            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);
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final ReflectionModel model = new ReflectionModel();
                model.setGenerationTime(ReflectionService.this.createGenerationTime());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault().getText());

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

                crudService.commitTransaction();
            }

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

            return null;
        }
    };
}

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

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

    //Create a root node
    String uuid = UUID.randomUUID().toString();

    Vertex root = graph.addVertex(uuid);

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

    add2Vertices(root, 0, 10);//from ww  w.  j  a  v  a  2s  .  c  o  m
    //add2Vertices(root, 0, 14);

    sw.stop();
    System.out.println("Binary tree with a depth of 10 added in " + sw.getTime() + " ms");

    //Traverse the tree  
    sw = new StopWatch();
    sw.start();

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

        Vertex left = root.getVertices(Direction.OUT, "to left").iterator().next();
        root = left;
    }

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

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

@Override
protected Task<Void> createTask() {
    return new Task<Void>() {
        {/*from   w  ww  .ja va2  s .c  om*/
            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);
            long id = -1_000_000_000L + DatabaseFacade.INSTANCE.getCrudService().count(entityName);
            for (int i = 1; i <= saveMaxEntities; i++) {
                crudService.beginTransaction();

                final DreamModel model = new DreamModel();
                model.setGenerationTime(DreamService.this.createGenerationTime());
                model.setDescription(LoremIpsum.getDefault().getDescription());
                model.setId(id++);
                model.setTitle(LoremIpsum.getDefault().getTitle());
                model.setText(LoremIpsum.getDefault().getText());

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

                crudService.commitTransaction();
            }

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

            return null;
        }
    };
}

From source file:de.unisb.cs.st.javalanche.rhino.RhinoTestDriver.java

private void testDirectory(File dir) {
    baseDir = dir.getAbsolutePath();//ww w. j a v  a 2s. c o m
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    File[] files = getTestFilesForDir(dir);
    List<String> passingTests = new ArrayList<String>();
    List<SingleTestResult> failingTests = new ArrayList<SingleTestResult>();
    logger.info("Searching in " + dir);
    List<String> failingList = Io.getLinesFromFile(new File("failing.txt"));
    List<String> ignoreList = Io
            .getLinesFromFile(new File("output/271545/post-fix/mozilla/js/tests/rhino-n.tests"));

    int ignore = 0;
    for (File f : files) {
        logger.info("File:  " + f);
        String testName = getRelativeLocation(f);
        logger.info("Test name: " + testName);

        if (ignoreList.contains(testName)) {
            logger.info("Not running test because its on the projects ignore list");
            ignore++;
            continue;
        }
        if (failingList.contains(testName)) {
            String message = "Not running test (Failed in previous run)";
            logger.info(message + testName);
            failingTests.add(new SingleTestResult(testName, message, TestOutcome.ERROR, 0));
            continue;
        }
        MutationTestRunnable testRunnable = getTestRunnable(testName);
        runWithTimeout(testRunnable);
        SingleTestResult result = testRunnable.getResult();
        if (result.hasPassed()) {
            logger.info("Test passed: " + testName);
            passingTests.add(testName);
        } else {
            logger.info("Test failed: " + testName);
            logger.info("Reason: " + result);
            failingTests.add(result);
        }

    }

    stopWatch.stop();
    long time = stopWatch.getTime();
    logger.info("Test Suite took " + DurationFormatUtils.formatDurationHMS(time));
    StringBuilder sbPass = new StringBuilder();
    StringBuilder sbFail = new StringBuilder();
    for (String passingTest : passingTests) {
        sbPass.append(passingTest + "\n");
    }
    for (SingleTestResult failingTestResult : failingTests) {
        sbFail.append(failingTestResult.getTestMessage().getTestCaseName()
                /* + "," + failingTestResult.getTestMessage().getMessage() */
                + "\n");
    }
    Io.writeFile(sbPass.toString(), new File("passingTests.txt"));
    Io.writeFile(sbFail.toString(), new File("failingTests.txt"));
    logger.info("Ignored " + ignore + " tests");
}

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

/**
 * To add 1000 vertices//  w w w  .j a  v a  2  s  . com
 */
@Test
@RunIf(value = PerfEnabledChecker.class)
public void testAdd1000Vertices() {
    System.out.println("-- testAdd1000Vertices");

    //Generate some random id-s
    String[] uuids = new String[1000];

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

        String uuid = UUID.randomUUID().toString();
        uuids[i] = uuid;
    }

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

    //For each UUID add a vertex

    for (String uuid : uuids) {

        graph.addVertex(uuid);
    }

    sw.stop();

    System.out.println("1000 verices added in " + sw.getTime() + " ms");

    System.out.println("- Proof that the last one was added");
    Vertex v = graph.getVertex(uuids[uuids.length - 1]);
    assertNotNull(v);

}

From source file:com.gst.infrastructure.security.filter.TenantAwareTenantIdentifierFilter.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 {// w  ww  .  ja va  2 s. c o m

        // allows for Cross-Origin
        // Requests (CORs) to be performed against the platform API.
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
        final String reqHead = request.getHeader("Access-Control-Request-Headers");

        if (null != reqHead && !reqHead.isEmpty()) {
            response.setHeader("Access-Control-Allow-Headers", reqHead);
        }

        if (!"OPTIONS".equalsIgnoreCase(request.getMethod())) {

            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("bearer ")) {
                ThreadLocalContextUtil.setAuthToken(authToken.replaceFirst("bearer ", ""));
            }

            if (!firstRequestProcessed) {
                final String baseUrl = request.getRequestURL().toString().replace(request.getRequestURI(),
                        request.getContextPath() + apiUri);
                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);
                }
                TenantAwareTenantIdentifierFilter.firstRequestProcessed = true;
            }
            chain.doFilter(request, response);
        }
    } 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:com.continuuity.weave.yarn.YarnWeaveController.java

@Override
protected void doStartUp() {
    super.doStartUp();

    // Submit and poll the status of the yarn application
    try {//from   www . jav  a  2s . c o  m
        processController = startUp.call();

        YarnApplicationReport report = processController.getReport();
        LOG.debug("Application {} submit", report.getApplicationId());

        YarnApplicationState state = report.getYarnApplicationState();
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        stopWatch.split();
        long maxTime = TimeUnit.MILLISECONDS.convert(Constants.APPLICATION_MAX_START_SECONDS, TimeUnit.SECONDS);

        LOG.info("Checking yarn application status");
        while (!hasRun(state) && stopWatch.getSplitTime() < maxTime) {
            report = processController.getReport();
            state = report.getYarnApplicationState();
            LOG.debug("Yarn application status: {}", state);
            TimeUnit.SECONDS.sleep(1);
            stopWatch.split();
        }
        LOG.info("Yarn application is in state {}", state);
        if (state != YarnApplicationState.RUNNING) {
            LOG.info("Yarn application is not in running state. Shutting down controller.",
                    Constants.APPLICATION_MAX_START_SECONDS);
            forceShutDown();
        } else {
            try {
                URL resourceUrl = URI
                        .create(String.format("http://%s:%d", report.getHost(), report.getRpcPort()))
                        .resolve(TrackerService.PATH).toURL();
                resourcesClient = new ResourceReportClient(resourceUrl);
            } catch (IOException e) {
                resourcesClient = null;
            }
        }
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}