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

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

Introduction

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

Prototype

public long getTime() 

Source Link

Document

Get the time on the stopwatch.

This is either the time between the start and the moment this method is called, or the amount of time between start and stop.

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./*  www. ja  va  2 s  .  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.beangle.model.persist.hibernate.HibernateEntityContext.java

public void initFrom(SessionFactory sessionFactory) {
    if (null != sessionFactory && entityTypes.isEmpty()) {
        StopWatch watch = new StopWatch();
        watch.start();//  ww  w  . j a v  a2 s .c  o m
        Map<String, ClassMetadata> classMetadatas = sessionFactory.getAllClassMetadata();
        for (Iterator<ClassMetadata> iter = classMetadatas.values().iterator(); iter.hasNext();) {
            ClassMetadata cm = (ClassMetadata) iter.next();
            buildEntityType(sessionFactory, cm.getEntityName());
        }
        logger.info("Find {} entities,{} collections from hibernate in {} ms",
                new Object[] { entityTypes.size(), collectionTypes.size(), watch.getTime() });
        if (logger.isDebugEnabled()) {
            loggerTypeInfo();
        }
        collectionTypes.clear();
    }
}

From source file:org.beangle.security.core.session.category.SessioninfoCleaner.java

@Override
public void run() {
    StopWatch watch = new StopWatch();
    watch.start();/* w w  w  . j a  va  2s  .com*/
    logger.debug("clean up expired or over maxOnlineTime session start ...");
    Calendar calendar = Calendar.getInstance();
    @SuppressWarnings("unchecked")
    OqlBuilder<Sessioninfo> builder = OqlBuilder.from(registry.getSessioninfoBuilder().getSessioninfoClass(),
            "info");
    builder.where("info.serverName=:server and info.lastAccessAt<:givenTime",
            registry.getController().getServerName(), DateUtils.rollMinutes(calendar.getTime(), -expiredTime));
    List<Sessioninfo> activities = entityDao.search(builder);
    int removed = 0;
    for (Sessioninfo activity : activities) {
        registry.remove(activity.getId());
        removed++;
    }
    if (removed > 0 || watch.getTime() > 50) {
        logger.info("removed {} expired sessions in {} ms", removed, watch.getTime());
    }
    registry.getController().stat();
}

From source file:org.beangle.spring.bind.AutoConfigProcessor.java

public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
    StopWatch watch = new StopWatch();
    watch.start();/*from w w  w .ja  va 2s.  c  om*/
    bindRegistry = new DefinitionBindRegistry(registry);
    register(registry);
    autowire();
    logger.debug("Auto register and wire bean [{}]", newBeanDefinitions.keySet());
    logger.info("Auto register and wire {} beans using {} mills", newBeanDefinitions.size(), watch.getTime());
    newBeanDefinitions.clear();
    bindRegistry = null;
}

From source file:org.beangle.web.io.SplitStreamDownloader.java

@Override
public void download(HttpServletRequest request, HttpServletResponse response, InputStream input, String name,
        String display) {//  w  w w . ja v a  2s. c o  m
    String attach = getAttachName(name, display);
    response.reset();
    addContent(request, response, attach);
    response.setHeader("Accept-Ranges", "bytes");
    response.setHeader("connection", "Keep-Alive");
    int length = 0;
    long start = 0L;
    long begin = 0L;
    long stop = 0L;
    StopWatch watch = new StopWatch();
    watch.start();
    try {
        length = input.available();
        stop = length - 1;
        response.setContentLength(length);
        String rangestr = request.getHeader("Range");
        if (null != rangestr) {
            String[] readlength = StringUtils.substringAfter(rangestr, "bytes=").split("-");
            start = Long.parseLong(readlength[0]);
            if (readlength.length > 1 && StringUtils.isNotEmpty(readlength[1])) {
                stop = Long.parseLong(readlength[1]);
            }
            if (start != 0) {
                response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
                String crange = "bytes " + start + "-" + stop + "/" + length;
                response.setHeader("Content-Range", crange);
            }
        }
        OutputStream output = response.getOutputStream();
        input.skip(start);
        begin = start;
        int size = 4 * 1024;
        byte[] buffer = new byte[size];
        for (int step = maxStep(start, stop, size); step > 0; step = maxStep(start, stop, size)) {
            int readed = input.read(buffer, 0, step);
            if (readed == -1)
                break;
            output.write(buffer, 0, readed);
            start += readed;
        }
    } catch (IOException e) {
    } catch (Exception e) {
        logger.warn("download file error " + attach, e);
    } finally {
        IOUtils.closeQuietly(input);
        if (logger.isDebugEnabled()) {
            String percent = null;
            if (length == 0) {
                percent = "100%";
            } else {
                percent = ((int) (((start - begin) * 1.0 / length) * 10000)) / 100.0f + "%";
            }
            long time = watch.getTime();
            int rate = 0;
            if (start - begin > 0) {
                rate = (int) (((start - begin) * 1.0 / time * 1000) / 1024);
            }
            logger.debug("{}({}-{}/{}) download {}[{}] in {} ms with {} KB/s",
                    array(attach, begin, stop, length, start - begin, percent, time, rate));
        }
    }
}

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.//  w w w .j a v  a 2  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.errorconsumer.ParseErrorWorkerThread.java

/**
 * TOOD: Add a temp ordered list to store ParseError objects as they are
 * taken from the queue and log if any rows are rejected by the DB server
 * TODO: abstract out the handleDBEntry base logic and use <T> for entry and
 * a static method for marshaling into a Prepared Statement (Consider adding
 * the marshal method to a TABLE definition object).
 *///from   w w  w  .  j  a  v a 2s.  co m
public void handleDBEntry() {

    Connection myConnection = null;
    PreparedStatement myPreparedStatement = null;

    Connection myPageViewConnection = null;

    int batchExecutionResults[] = null;

    List<ParseError> theBatchTrackingList = new LinkedList<ParseError>();

    //DeviceType aDeviceType = null;
    //DeviceClass aDeviceClass = null;

    //Change to reusable map
    Map<String, String> tmpMap = null;

    //Change to StringBuilder 
    //String tmpString = null; 

    //theBatchTrackingList = new ArrayList<PageViewData>(dataQueue.size());
    boolean dbErrror = false;

    try {
        ParseError aParseError = null;
        try {
            aParseError = errorQueue.remove();
            theBatchTrackingList.add(aParseError);
        } catch (NoSuchElementException e) {
            LOG.info("There are no ParseError Objects to push into the DB");
            return;
        }
        StopWatch connectionAge = new StopWatch();
        connectionAge.start();
        setWorkerState(WORKER_STATE.ACQUIRING_CONNECTION);
        myConnection = DBUtil.getDefaultDataSource().getConnection();
        setWorkerState(WORKER_STATE.CONFIGURING_CONNECTION);
        myConnection.clearWarnings();
        myConnection.setAutoCommit(false);
        setWorkerState(WORKER_STATE.PREPARING_SQL);
        myPreparedStatement = myConnection.prepareStatement(ParseErrorTable.PREPARED_INSERT_SQL);
        setWorkerState(WORKER_STATE.BATCHING);

        while ((connectionAge.getTime() / 1000) <= 20) {
            ParseErrorTable.populatePreparedStatement(myPreparedStatement, aParseError.toParamMap(),
                    Boolean.FALSE);
            myPreparedStatement.addBatch();
            try {
                aParseError = errorQueue.remove();
                theBatchTrackingList.add(aParseError);
            } catch (NoSuchElementException e) {
                break;
            }
        }

        this.setWorkerState(WORKER_STATE.EXECUTING_BATCH);
        batchExecutionResults = myPreparedStatement.executeBatch();

        myConnection.commit();

        this.setWorkerState(WORKER_STATE.VERIFYING_BATCH);
        if (batchExecutionResults.length != theBatchTrackingList.size()) {

        }

    } catch (SQLException sqle) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal(
                    "SQLException caught. The ErrorConsumer is unable to push data to a database. ParseErrors will be dumped to /tmp/error_consumer/",
                    sqle);
        }
    } catch (Exception e) {
        if (LOG.isFatalEnabled()) {
            LOG.fatal(
                    "Exception caught. The ErrorConsumer is unable to push data to a database. Errors will be dumped to /tmp/error_consumer/",
                    e);
        }

    } finally {
        DbUtils.closeQuietly(myPreparedStatement);
        DbUtils.closeQuietly(myConnection);
    }
}

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

/**
 *///from w  ww. j  a  v a 2  s.  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.  java 2  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");
}