Example usage for org.apache.commons.lang.time StopWatch StopWatch

List of usage examples for org.apache.commons.lang.time StopWatch StopWatch

Introduction

In this page you can find the example usage for org.apache.commons.lang.time StopWatch StopWatch.

Prototype

public StopWatch() 

Source Link

Document

Constructor.

Usage

From source file:org.lic.ip.iplocator.IPv4RadixIntTree.java

private IPv4RadixIntTree() {
    StopWatch sw = new StopWatch();
    sw.start();/* www. j  av a2  s.c o  m*/

    try {
        String filepath = getClass().getClassLoader().getResource("ipdb_all_2015-01-19").getPath();

        int lines = countLinesInLocalFile(filepath);
        logger.info("file lines: {}", lines);

        init(lines);
        loadFromLocalFile(filepath);
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }

    sw.stop();
    logger.info("init cost: {}ms", sw.getTime());
}

From source file:org.lic.ip.ipseeker.IPSeeker.java

private static void benchmark() throws Exception {
    String ip = "123.58.182.1";

    StopWatch sw = new StopWatch();
    int times = 100000000;
    Random rand = new Random();

    sw.start();//w w w  .j a  v  a 2  s .c o m
    for (int i = 0; i < times; i++) {
        IPSeeker ips = IPSeeker.getInstance();
        IPLocation ipl = ips.getIPLocation(String.valueOf(rand.nextInt()));
    }
    System.out.println(sw.getTime() + "ms");
    System.out.println(IPSeeker.ipCacheMap.size());

    while (true) {
        Thread.sleep(1);
    }
}

From source file:org.midonet.cluster.data.util.ZkOpLock.java

public ZkOpLock(ZookeeperLockFactory lockFactory, int lockOpNumber, String lockName) {
    lock = lockFactory.createShared(lockName);
    opNumber = lockOpNumber;/*ww  w . j av a  2s.c  o m*/
    timeHeld = new StopWatch();
    name = lockName;
}

From source file:org.midonet.cluster.data.util.ZkOpLock.java

public void acquire() {
    StopWatch timeToAcquire = new StopWatch();
    timeToAcquire.start();/*from  w  w w  . j a  va2 s .c  o m*/
    try {
        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 av a  2s  . co  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.mifos.framework.components.logger.ServiceActivityLogger.java

public ServiceActivityLogger(String serviceName) {
    super();
    this.serviceName = serviceName;
    stopWatch = new StopWatch();
}

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();/* w w w  .ja  v a  2  s  . co  m*/

    try {

        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();//from w  w  w  . j  ava 2s .c  o  m

    try {

        // 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 av a 2 s. co m

    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.mule.transport.http.functional.HttpContinueFunctionalTestCase.java

@Test
public void testSendWithContinue() throws Exception {
    stopWatch = new StopWatch();
    MuleClient client = new MuleClient(muleContext);

    //Need to use Http1.1 for Expect: Continue
    HttpClientParams params = new HttpClientParams();
    params.setVersion(HttpVersion.HTTP_1_1);
    params.setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, true);

    Map<String, Object> props = new HashMap<String, Object>();
    props.put(HttpConnector.HTTP_PARAMS_PROPERTY, params);

    stopWatch.start();/*from  w ww .j a v  a2s  .  c o  m*/
    MuleMessage result = client.send("clientEndpoint", TEST_MESSAGE, props);
    stopWatch.stop();

    assertNotNull(result);
    assertEquals(TEST_MESSAGE + " Received", result.getPayloadAsString());

    if (stopWatch.getTime() > DEFAULT_HTTP_CLIENT_CONTINUE_WAIT) {
        fail("Server did not handle Expect=100-continue header properly,");
    }
}