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

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

Introduction

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

Prototype

public void stop() 

Source Link

Document

Stop the stopwatch.

This method ends a new timing session, allowing the time to be retrieved.

Usage

From source file:org.apache.wiki.render.RenderingManagerTest.java

/**
 * Tests the relative speed of the DOM cache with respect to
 * page being parsed every single time./*w w w  .  j  a v a 2s .c o  m*/
 * @throws Exception
 */
public void testCache() throws Exception {
    m_engine.saveText("TestPage", TEST_TEXT);

    StopWatch sw = new StopWatch();

    System.out.println("DOM cache speed test:");
    sw.start();

    for (int i = 0; i < 100; i++) {
        WikiPage page = m_engine.getPage("TestPage");
        String pagedata = m_engine.getPureText(page);

        WikiContext context = new WikiContext(m_engine, page);

        MarkupParser p = m_manager.getParser(context, pagedata);

        WikiDocument d = p.parse();

        String html = m_manager.getHTML(context, d);
        assertNotNull("noncached got null response", html);
    }

    sw.stop();
    System.out.println("  Nocache took " + sw);

    long nocachetime = sw.getTime();

    sw.reset();
    sw.start();

    for (int i = 0; i < 100; i++) {
        WikiPage page = m_engine.getPage("TestPage");
        String pagedata = m_engine.getPureText(page);

        WikiContext context = new WikiContext(m_engine, page);

        String html = m_manager.getHTML(context, pagedata);

        assertNotNull("cached got null response", html);
    }

    sw.stop();
    System.out.println("  Cache took " + sw);

    long speedup = nocachetime / sw.getTime();
    System.out.println("  Approx speedup: " + speedup + "x");
}

From source file:org.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java

public static String standardSaxBenchmark(final String fileName, final int iterations) throws Exception {

    final SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    final SAXParser parser = parserFactory.newSAXParser();

    /*//from w ww.  j  a v  a 2 s.co m
     * WARMUP BEGIN
     */
    System.out.println("Warming up phase for SAX STARTED");
    for (int i = 0; i < 10000; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final InputSource inputSource = new InputSource(reader);

            final BenchmarkStandardSaxContentHandler handler = new BenchmarkStandardSaxContentHandler();
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
            parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);

            parser.parse(inputSource, handler);
            parser.reset();

            handler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }
    /*
     * WARMUP END
     */
    System.out.println("Warming up phase for SAX FINISHED");

    final StopWatch sw = new StopWatch();
    boolean started = false;

    int eventCounter = 0;
    for (int i = 0; i < iterations; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final InputSource inputSource = new InputSource(reader);

            final BenchmarkStandardSaxContentHandler handler = new BenchmarkStandardSaxContentHandler();
            parser.setProperty("http://xml.org/sax/properties/lexical-handler", handler);
            parser.setProperty("http://xml.org/sax/properties/declaration-handler", handler);

            if (started) {
                sw.resume();
            } else {
                started = true;
                sw.start();
            }

            parser.parse(inputSource, handler);
            parser.reset();

            sw.suspend();

            eventCounter = handler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }

    sw.stop();

    return "[" + eventCounter + "] " + sw.toString();

}

From source file:org.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java

public static String attoParserBenchmark(final String fileName, final int iterations) throws Exception {

    final IMarkupParser parser = new MarkupParser(MARKUP_PARSING_CONFIG);

    /*/* www. ja  v a  2  s .c o  m*/
     * WARMUP BEGIN
     */
    System.out.println("Warming up phase for ATTO STARTED");
    for (int i = 0; i < 10000; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final BenchmarkMarkupHandler handler = new BenchmarkMarkupHandler();
            parser.parse(reader, handler);

            handler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }
    /*
     * WARMUP END
     */
    System.out.println("Warming up phase for ATTO FINISHED");

    final StopWatch sw = new StopWatch();
    boolean started = false;

    int eventCounter = 0;
    for (int i = 0; i < iterations; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final BenchmarkMarkupHandler benchmarkHandler = new BenchmarkMarkupHandler();
            final IMarkupHandler handler = benchmarkHandler;

            if (started) {
                sw.resume();
            } else {
                started = true;
                sw.start();
            }

            parser.parse(reader, handler);

            sw.suspend();

            eventCounter = benchmarkHandler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }

    sw.stop();

    return "[" + eventCounter + "] " + sw.toString();

}

From source file:org.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java

public static String attoParserHtmlBenchmark(final String fileName, final int iterations) throws Exception {

    final IMarkupParser parser = new MarkupParser(HTML_MARKUP_PARSING_CONFIG);

    /*/*from   w  ww .j  a  va  2  s .co m*/
     * WARMUP BEGIN
     */
    System.out.println("Warming up phase for ATTO(HTML) STARTED");
    for (int i = 0; i < 10000; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final BenchmarkMarkupHandler handler = new BenchmarkMarkupHandler();
            parser.parse(reader, handler);

            handler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }
    /*
     * WARMUP END
     */
    System.out.println("Warming up phase for ATTO(HTML) FINISHED");

    final StopWatch sw = new StopWatch();
    boolean started = false;

    int eventCounter = 0;
    for (int i = 0; i < iterations; i++) {

        InputStream is = null;
        Reader reader = null;

        try {

            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
            reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

            final BenchmarkMarkupHandler handler = new BenchmarkMarkupHandler();

            if (started) {
                sw.resume();
            } else {
                started = true;
                sw.start();
            }

            parser.parse(reader, handler);

            sw.suspend();

            eventCounter = handler.getEventCounter();

        } finally {
            try {
                if (reader != null)
                    reader.close();
            } catch (final Exception ignored) {
                /* ignored */}
            try {
                if (is != null)
                    is.close();
            } catch (final Exception ignored) {
                /* ignored */}
        }

    }

    sw.stop();

    return "[" + eventCounter + "] " + sw.toString();

}

From source file:org.attoparser.benchmark.AttoParserVSStandardSAXBenchmark.java

public static void attoDOMOutput(final String fileName) throws Exception {

    final IMarkupParser parser = new MarkupParser(MARKUP_PARSING_CONFIG);

    InputStream is = null;//from w  w  w . j  a  v  a2  s.  c o m
    Reader reader = null;

    final StopWatch sw = new StopWatch();

    try {

        is = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
        reader = new BufferedReader(new InputStreamReader(is, "ISO-8859-1"));

        sw.start();

        final DOMBuilderMarkupHandler handler = new DOMBuilderMarkupHandler();
        parser.parse(reader, handler);

        final Document document = handler.getDocument();

        final StringWriter writer = new StringWriter();

        DOMWriter.write(document, writer);
        System.out.println(writer.toString());
        sw.stop();

    } finally {
        try {
            if (reader != null)
                reader.close();
        } catch (final Exception ignored) {
            /* ignored */}
        try {
            if (is != null)
                is.close();
        } catch (final Exception ignored) {
            /* ignored */}
    }

}

From source file:org.bml.util.elasticconsumer.ElasticConsumer.java

/**
 * Offer an object to be processed to the processing queue.
 *
 * @param theObject The object to be processed.
 * @param theTimeout The max wait time for successful offer.
 * @param theTimeUnit The TimeUnit the argument theTimeout is in.
 * @return boolean true on success false otherwise
 * @throws java.lang.InterruptedException if this thread is interrupted
 * while attempting the offer.//from  w ww .ja v a2  s .co  m
 * @throws IllegalArgumentException If theObject is null, theTimeout is less
 * than 1, or theTimeUnit is null.
 */
public boolean offer(final D theObject, final long theTimeout, final TimeUnit theTimeUnit)
        throws InterruptedException, IllegalArgumentException {
    if (theObject == null) {
        throw new IllegalArgumentException("Can not offer a null object.");
    }
    if (theTimeout < 1) {
        throw new IllegalArgumentException("Can not offer an object with a timeout less than 1.");
    }
    if (theTimeUnit == null) {
        throw new IllegalArgumentException("Can not offer an object with a null TimeUnit.");
    }

    if (log.isDebugEnabled()) {
        StopWatch watch = new StopWatch();
        watch.start();
        boolean result = doOffer(theObject, theTimeout, theTimeUnit);
        watch.stop();
        log.debug(getLogPrefix() + " DEBUG: OFFER result=" + result + " timeout=" + theTimeout + " time unit "
                + theTimeUnit + " actual time in mills=" + watch.getTime());
        return result;
    }
    return doOffer(theObject, theTimeout, theTimeUnit);
}

From source file:org.bml.util.geo.util.geolite.GISControler.java

/**
 *//*  www.  j  a va 2s . c o  m*/
private static void initGISFromDB() {
    try {
        ComboPooledDataSource myComboPooledDataSource = DBUtil.getDefaultDataSource();
        StopWatch myStopWatch = new StopWatch();
        myStopWatch.start();
        ipBlocks = GeoLiteCityBlock.readFromDB(myComboPooledDataSource);

        myStopWatch.stop();
        if (LOG.isInfoEnabled()) {
            LOG.info("Finished Loading " + ipBlocks.size() + " IPBlocks Map in "
                    + (myStopWatch.getTime() / 1000) + " Seconds");
        }
        myStopWatch.start();
        Map<Integer, GeoLiteCityLocation> locationMap = GeoLiteCityLocation.readFromDB(myComboPooledDataSource);
        myStopWatch.stop();
        if (LOG.isInfoEnabled()) {
            LOG.info("Finished Loading " + locationMap.size() + " Locations in "
                    + (myStopWatch.getTime() / 1000) + " Seconds");
        }
        startIPs = ipBlocks.keySet().toArray(new Integer[ipBlocks.keySet().size()]);
        //This should not be necessary but we sort for now until the underlying structures have been 
        // proven
        Arrays.sort(startIPs);
        for (GeoLiteCityBlock block : ipBlocks.values()) {
            block.setTheLocation(locationMap.get(block.getLocId()));
        }
        //Mark for GC
        locationMap.clear();
        locationMap = null;

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception caught while loading GIS data. GIS DATA LOOKUP WILL NOT BE AVAILABLE!", e);
        }
    } finally {
        if (ipBlocks != null && !ipBlocks.isEmpty() && startIPs != null && startIPs.length > 0) {
            isAvailable = true;
        } else {
            isAvailable = false;
        }
    }
}

From source file:org.cesecore.audit.log.InternalSecurityEventsLoggerSessionBean.java

@Override
public void log(final TrustedTime trustedTime, final EventType eventType, final EventStatus eventStatus,
        final ModuleType module, final ServiceType service, final String authToken, final String customId,
        final String searchDetail1, final String searchDetail2, final Map<String, Object> additionalDetails)
        throws AuditRecordStorageException {
    if (LogServiceState.INSTANCE.isDisabled()) {
        throw new AuditRecordStorageException("Security audit logging is currently disabled.");
    }/* w w  w  .j av  a 2 s .  c o m*/
    final Map<Class<?>, Object> ejbs = getEjbs();
    boolean anyFailures = false;
    for (final String loggerId : AuditDevicesConfig.getAllDeviceIds()) {
        try {
            StopWatch sw = null;
            if (LOG.isDebugEnabled()) {
                sw = new StopWatch();
                sw.start();
            }
            AuditDevicesConfig.getDevice(ejbs, loggerId).log(trustedTime, eventType, eventStatus, module,
                    service, authToken, customId, searchDetail1, searchDetail2, additionalDetails,
                    AuditDevicesConfig.getProperties(loggerId));
            if (LOG.isDebugEnabled()) {
                sw.stop();
                LOG.debug("LogDevice: " + loggerId + " Proc: " + sw.getTime());
            }
        } catch (Exception e) { // AuditRecordStorageException
            anyFailures = true;
            LOG.error("AuditDevice " + loggerId + " failed. An event was not logged to this device!", e);
        }
    }
    if (anyFailures) {
        // CESeCore.FAU_STG.4.1: The TSF shall prevent audited events, except those taken by the Auditable and no other actions if the audit trail is full.
        // So even if we failed to produce a proper audit trail for these events, we swallow the exception here to allow the operation to continue.
        if (!eventType.equals(EventTypes.LOG_VERIFY) && !eventType.equals(EventTypes.LOG_EXPORT)
                && !eventType.equals(EventTypes.LOG_DELETE) && !eventType.equals(EventTypes.LOG_SIGN)
                && !eventType.equals(EventTypes.LOG_MANAGEMENT_CHANGE)) {
            throw new AuditRecordStorageException("Failed to write audit log to at least one device.");
        }
    }
}

From source file:org.cesecore.audit.log.SecurityEventsLoggerSessionBeanTest.java

@Test
public void test04SecureMultipleLog() throws Exception {
    log.trace(">test03SecureMultipleLog");
    final int THREADS = 50;
    final int WORKERS = 400;
    final int TIMEOUT_MS = 30000;
    final ThreadPoolExecutor workers = (ThreadPoolExecutor) Executors.newFixedThreadPool(THREADS);
    final StopWatch time = new StopWatch();

    time.start();//from  ww  w. j av  a2  s .  c  o  m
    for (int i = 0; i < WORKERS; i++) {
        workers.execute(new Runnable() { // NOPMD: this is a test, not a JEE application
            @Override
            public void run() {
                try {
                    securityEventsLogger.log(roleMgmgToken, EventTypes.AUTHENTICATION, EventStatus.SUCCESS,
                            ModuleTypes.SECURITY_AUDIT, ServiceTypes.CORE);
                } catch (AuthorizationDeniedException e) {
                    fail("should be authorized");
                }
            }
        });
    }
    while (workers.getCompletedTaskCount() < WORKERS && time.getTime() < TIMEOUT_MS) {
        Thread.sleep(250);
    }
    time.stop();
    final long completedTaskCount = workers.getCompletedTaskCount();
    log.info("securityEventsLogger.log: " + completedTaskCount + " completed in " + time.toString() + " using "
            + THREADS + " threads.");
    workers.shutdown();

    for (final String logDeviceId : securityEventsAuditor.getQuerySupportingLogDevices()) {
        final AuditLogValidationReport report = securityEventsAuditor.verifyLogsIntegrity(roleMgmgToken,
                new Date(), logDeviceId);
        assertNotNull(report);
        final StringBuilder strBuilder = new StringBuilder();
        for (final AuditLogReportElem error : report.errors()) {
            strBuilder.append(String.format("invalid sequence: %d %d\n", error.getFirst(), error.getSecond()));
            for (final String reason : error.getReasons()) {
                strBuilder.append(String.format("Reason: %s\n", reason));
            }
        }
        assertTrue("validation report: " + strBuilder.toString(),
                (report.warnings().size() == 1 || report.warnings().size() == 0)
                        && report.errors().size() == 0);
    }
    log.trace("<test03SecureMultipleLog");
}

From source file:org.codehaus.gmaven.runtime.loader.DefaultProviderManager.java

public Provider select(final String selection) {
    assert selection != null;

    Provider provider = (Provider) cachedSelection.get(selection);
    if (provider != null) {
        log.debug("Using cached provider '{}' for selection: {}", provider, selection);
    } else {/* w  w w . j  a  v a 2  s.c o  m*/
        log.debug("Selecting provider; selection: {}", selection);

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

        try {
            provider = getSelector().select(getRegistry(), selection);
        } catch (Exception e) {
            throw new ProviderException("Selection of provider failed; selection: " + selection, e);
        }

        if (provider == null) {
            throw new ProviderException("No providers found matching selection: " + selection);
        }

        cachedSelection.put(selection, provider);

        watch.stop();

        log.debug("Selected provider: {} ({})", provider, watch);
    }

    return provider;
}