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:org.midonet.cluster.data.util.ZkOpLock.java

public void acquire() {
    StopWatch timeToAcquire = new StopWatch();
    timeToAcquire.start();
    try {/*from   w  ww  . j av  a2  s.  c o m*/
        LOGGER.debug("Attempting to acquire lock for operation " + opNumber);
        if (!lock.acquire(LOCK_WAIT_SEC, TimeUnit.SECONDS)) {
            throw new RuntimeException("Could not acquire lock in time");
        }
        timeToAcquire.stop();
        timeHeld.start();

        LOGGER.debug(name + "ZK lock acquired for operation " + opNumber + ". Operation took "
                + timeToAcquire.getTime() + " milliseconds.");
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.midonet.midolman.state.ZkOpList.java

/**
 * Commit the Ops with duplicate paths removed.
 *//*from   w w  w.  j a va2  s .c o  m*/
public void commit() throws StateAccessException {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    if (size() > 0) {
        tryCommit(DEL_RETRIES);
        clear();
    } else {
        logger.warn("No Op to commit");
    }
    stopWatch.stop();
    logger.debug("Commit operation took " + stopWatch.getTime() + " milliseconds.");
}

From source file:org.mifosplatform.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  . j  av a 2  s  .c  om

        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.");
            }

            // check tenants database for tenantId
            final MifosPlatformTenant tenant = this.basicAuthTenantDetailsService
                    .loadTenantById(tenantIdentifier);

            ThreadLocalContextUtil.setTenant(tenant);

            if (!firstRequestProcessed) {
                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=\"" + "Mifos 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:org.mifosplatform.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 {/*from   w  w w  .j  a v  a2s .co  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.equals(null)) {
            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 MifosPlatformTenant 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=\"" + "Mifos 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:org.mule.example.loanbroker.tests.AbstractAsynchronousLoanBrokerTestCase.java

@Override
public void testLotsOfLoanRequests() throws Exception {
    final MuleClient client = new MuleClient(muleContext);
    Customer c = new Customer("Ross Mason", 1234);
    CustomerQuoteRequest[] requests = new CustomerQuoteRequest[3];
    requests[0] = new CustomerQuoteRequest(c, 100000, 48);
    requests[1] = new CustomerQuoteRequest(c, 1000, 12);
    requests[2] = new CustomerQuoteRequest(c, 10, 24);

    final StopWatch stopWatch = new StopWatch();

    final int numRequests = getNumberOfRequests() + getWarmUpMessages();
    int i = 0;//from   w  w  w .  j a v  a  2  s.c om

    int numberOfThreads = 1;

    CountDownLatch latch = new CountDownLatch(numberOfThreads);
    ExceptionHolder exceptionHolder = new ExceptionHolder();
    try {
        for (int x = 0; x < numberOfThreads; x++) {
            Thread thread = new Thread(
                    new ClientReceiver(latch, numRequests / numberOfThreads, exceptionHolder));
            thread.start();
        }

        for (i = 0; i < numRequests; i++) {
            if (i == getWarmUpMessages()) {
                stopWatch.start();
            }
            client.dispatch("CustomerRequests", requests[i % 3], null);
        }
    } finally {
        latch.await();
        stopWatch.stop();
        System.out.println("Total running time was: " + stopWatch.getTime() + "ms");
        System.out.println("Requests processed was: " + i);
        int mps = (int) (numRequests / ((double) stopWatch.getTime() / (double) 1000));
        System.out.println("Msg/sec: " + mps + " (warm up msgs = " + getWarmUpMessages() + ")");
        if (exceptionHolder.isExceptionThrown()) {
            exceptionHolder.print();
            fail("Exceptions thrown during async processing");
        }
    }
}

From source file:org.musicbrainz.search.index.CommonTables.java

/**
 * Create table showing all artist credits, then create index
 * for the table, a merge of required artist credit_name & artist information
 *
 * @throws SQLException/*w  w  w  .j a v a  2  s.c  om*/
 */
private void createArtistCreditTableUsingDb() throws SQLException {
    System.out.println("tmp_artistcredit:Started at:" + Utils.formatCurrentTimeForOutput());
    StopWatch clock = new StopWatch();
    clock.start();
    getDbConnection().createStatement().execute("CREATE TEMPORARY TABLE tmp_artistcredit AS "
            + "SELECT acn.artist_credit as artist_credit, " + "  acn.position as pos, "
            + "  acn.join_phrase as joinphrase, " + "  a.id," + "  a.gid as artistId,  "
            + "  a.comment as comment, " + "  a.name as artistName, " + "  acn.name as artistCreditName, "
            + "  a.sort_name as artistSortName " + " FROM artist_credit_name acn  "
            + "  INNER JOIN artist a ON a.id=acn.artist " + " ORDER BY acn.artist_credit,acn.position ");
    clock.stop();
    System.out.println("tmp_artistcredit:Finished:" + Utils.formatClock(clock));
    clock.reset();

    clock.start();
    getDbConnection().createStatement()
            .execute("CREATE INDEX tmp_artistcredit_idx ON tmp_artistcredit (artist_credit) ");
    clock.stop();
    System.out.println("tmp_artistcredit:Created Indexes:" + Utils.formatClock(clock));
    clock.reset();
}

From source file:org.musicbrainz.search.index.CommonTables.java

private void createReleaseTableUsingDb() throws SQLException {
    System.out.println("tmp_release     :Started at:" + Utils.formatCurrentTimeForOutput());
    StopWatch clock = new StopWatch();
    clock.start();

    getDbConnection().createStatement().execute("CREATE TEMPORARY TABLE tmp_release AS "
            + "SELECT r.id, r.gid, r.name as name, " + "  barcode, "
            + "  rgt.name as type, rg.id as rg_id, rg.gid as rg_gid, rm.amazon_asin, "
            + "  language.iso_code_3 as language, language.iso_code_2t as language_2t, script.iso_code as script, rs.name as status, "
            + "  sum(m.track_count) as tracks," + "  r.artist_credit, r.quality,rp.name as packaging,"
            + "  r.comment" + " FROM release r " + "  LEFT JOIN release_meta rm ON r.id = rm.id "
            + "  LEFT JOIN release_group rg ON rg.id = r.release_group "
            + "  LEFT JOIN release_group_primary_type rgt  ON rg.type = rgt.id "
            + "  LEFT JOIN release_status rs ON r.status = rs.id "
            + "  LEFT JOIN language ON r.language=language.id " + "  LEFT JOIN script ON r.script=script.id "
            + "  LEFT JOIN medium m ON m.release=r.id"
            + "  LEFT JOIN release_packaging rp ON r.packaging = rp.id "
            + " GROUP BY r.id,r.gid,r.name,barcode,rgt.name,rg.id, rg.gid,"
            + "  rm.amazon_asin, language.iso_code_3, language.iso_code_2t, script.iso_code,rs.name,r.artist_credit, r.quality, rp.name,r.comment");
    clock.stop();//  www.j a va 2  s . c o  m
    System.out.println("tmp_release     :Finished:" + Utils.formatClock(clock));
    clock.reset();

    clock.start();
    getDbConnection().createStatement().execute("CREATE INDEX tmp_release_idx_release ON tmp_release (id) ");
    clock.stop();
    System.out.println("tmp_release     :Created Indexes:" + Utils.formatClock(clock));
    clock.reset();
}

From source file:org.musicbrainz.search.index.CommonTables.java

private void createReleaseEventsTableUsingDb() throws SQLException {
    System.out.println("tmp_release_event     :Started at:" + Utils.formatCurrentTimeForOutput());
    StopWatch clock = new StopWatch();
    clock.start();

    //Note:assumes a release country always only maps to an area with a single 3166_1 code
    getDbConnection().createStatement()//from   w  w w  .  j  ava 2s .  c om
            .execute("CREATE TEMPORARY TABLE tmp_release_event AS " + " SELECT r1.release, r2.code as country, "
                    + "  r1.date_year, r1.date_month, r1.date_day," + "  a1.gid as gid, a1.name as name"
                    + " FROM release_country r1 " + " LEFT JOIN area a1 " + " ON r1.country = a1.id"
                    + " LEFT JOIN iso_3166_1 r2 " + " ON a1.id = r2.area " + " UNION"
                    + " SELECT release, null as country, " + "  date_year, date_month, date_day,"
                    + "  null as gid, null as name" + " FROM release_unknown_country r1 ");
    clock.stop();
    System.out.println("tmp_release_event     :Finished:" + Utils.formatClock(clock));
    clock.reset();

    clock.start();
    getDbConnection().createStatement()
            .execute("CREATE INDEX tmp_release_event_idx_release ON tmp_release_event (release) ");
    clock.stop();
    System.out.println("tmp_release_event     :Created Indexes:" + Utils.formatClock(clock));
    clock.reset();
}

From source file:org.musicbrainz.search.index.CommonTables.java

private void createTrackTableUsingDb() throws SQLException {
    System.out.println("tmp_track       :Started at:" + Utils.formatCurrentTimeForOutput());
    StopWatch clock = new StopWatch();
    clock.start();

    getDbConnection().createStatement().execute("CREATE TEMPORARY TABLE tmp_track AS "
            + "SELECT t.id, t.gid, t.recording, t.length, t.name as track_name, t.position as track_position, t.number as track_number, m.track_count, "
            + "  m.release as release_id, m.position as medium_position, mf.name as format " + " FROM track t "
            + "  INNER JOIN medium m ON t.medium=m.id " + "  LEFT JOIN  medium_format mf ON m.format=mf.id ");

    clock.stop();/*from  w ww. jav a  2  s. c  om*/
    System.out.println("tmp_track       :Finished:" + Utils.formatClock(clock));
    clock.reset();

    clock.start();
    getDbConnection().createStatement()
            .execute("CREATE INDEX tmp_track_idx_recording ON tmp_track (recording) ");
    clock.stop();
    System.out.println("tmp_track       :Created Indexes" + Utils.formatClock(clock));
    clock.reset();
}

From source file:org.ngrinder.common.util.ThreadUtilsTest.java

/**
 * Test method for {@link ThreadUtils#sleep(long)}.
 */// w  w w.jav  a  2 s .  c  om
@Test
public void testSleep() {
    StopWatch watch = new StopWatch();
    watch.start();
    ThreadUtils.sleep(1000);
    watch.stop();
    assertThat(watch.getTime()).isGreaterThanOrEqualTo(1000);
    assertThat(watch.getTime()).isLessThan(3000);
}