Example usage for org.springframework.util StopWatch start

List of usage examples for org.springframework.util StopWatch start

Introduction

In this page you can find the example usage for org.springframework.util StopWatch start.

Prototype

public void start() throws IllegalStateException 

Source Link

Document

Start an unnamed task.

Usage

From source file:org.ameba.aop.IntegrationLayerAspect.java

/**
 * Around intercepted methods do some logging and exception translation. <p> <ul> <li> Set log level of {@link
 * LoggingCategories#INTEGRATION_LAYER_ACCESS} to INFO to enable method tracing. <li>Set log level of {@link
 * LoggingCategories#INTEGRATION_LAYER_EXCEPTION} to ERROR to enable exception logging. </ul> </p>
 *
 * @param pjp The joinpoint/*from   w ww  .j  a  va  2s . c  om*/
 * @return Method return value
 * @throws Throwable in case of errors
 */
@Around("org.ameba.aop.Pointcuts.integrationPointcut()")
public Object measure(ProceedingJoinPoint pjp) throws Throwable {
    StopWatch sw = null;
    if (P_LOGGER.isInfoEnabled()) {
        sw = new StopWatch();
        sw.start();
        P_LOGGER.info("[I]>> {}#{}", pjp.getTarget().getClass().getSimpleName(), pjp.getSignature().getName());
    }
    try {
        return pjp.proceed();
    } catch (Exception ex) {
        throw translateException(ex);
    } finally {
        if (P_LOGGER.isInfoEnabled() && sw != null) {
            sw.stop();
            P_LOGGER.info("[I]<< {}#{} took {} [ms]", pjp.getTarget().getClass().getSimpleName(),
                    pjp.getSignature().getName(), sw.getTotalTimeMillis());
        }
    }
}

From source file:com.persistent.cloudninja.scheduler.TenantDBBandwidthProcessor.java

@Override
public boolean execute() {
    boolean retVal = true;
    int tenantDBBWsCount = 0;
    try {//from   w ww  .j  av  a 2s .com
        LOGGER.debug("In Processor");
        TenantDBBandwidthQueue queue = (TenantDBBandwidthQueue) getWorkQueue();
        String message = queue.dequeue(SchedulerSettings.MessageVisibilityTimeout);
        if (message == null) {
            retVal = false;
            LOGGER.debug("Processor : msg is null");
        } else {
            StopWatch watch = new StopWatch();
            watch.start();
            LOGGER.debug("Processor : msg is " + message);
            List<DBBandwidthUsageEntity> listDbBandwidthUsageEntities = partitionStatsAndBWUsageDao
                    .getBandwidthUsage();
            tenantDBBWsCount = listDbBandwidthUsageEntities.size();
            Map<String, MeteringEntity> map = new HashMap<String, MeteringEntity>();
            MeteringEntity meteringEntity = null;
            String dbName = null;
            String tenantId = null;

            for (DBBandwidthUsageEntity dbBandwidthUsageEntity : listDbBandwidthUsageEntities) {
                dbName = dbBandwidthUsageEntity.getDatabaseName();

                if (dbName.startsWith("tnt_")) {
                    tenantId = dbName.substring(4);
                    if (map.containsKey(tenantId)) {
                        meteringEntity = map.get(tenantId);
                        setDatabaseBandwidth(dbBandwidthUsageEntity, meteringEntity);
                    } else {
                        meteringEntity = new MeteringEntity();
                        meteringEntity.setTenantId(tenantId);
                        setDatabaseBandwidth(dbBandwidthUsageEntity, meteringEntity);
                        map.put(tenantId, meteringEntity);
                    }
                }
            }

            Calendar calendar = Calendar.getInstance();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z");
            dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            String date = dateFormat.format(calendar.getTime());

            for (Iterator<MeteringEntity> iterator = map.values().iterator(); iterator.hasNext();) {
                meteringEntity = (MeteringEntity) iterator.next();
                meteringEntity.setSnapshotTime(dateFormat.parse(date));
                meteringDao.add(meteringEntity);
            }
            LOGGER.info("Processor : DB bandwidth calculated.");
            watch.stop();
            taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                    "ProcessMeteringTenantDBBandwidthUse",
                    "Measured the database bandwith use for " + tenantDBBWsCount + " tenants.");
        }
    } catch (StorageException e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    } catch (ParseException e) {
        retVal = false;
        LOGGER.error(e.getMessage(), e);
    }
    return retVal;
}

From source file:org.apache.mina.springrpc.example.gettingstarted.AbstractHelloServiceClientTests.java

protected void invokeService(final HelloService service) {
    StopWatch sw = new StopWatch(
            "HelloService with concurrent [ " + useConcurrent + " ], runtimes [ " + RUN_TIMES + " ]");
    sw.start();

    List<Callable<HelloResponse>> tasks = createTasks(service);

    if (useConcurrent) {
        executeUseConcurrent(tasks);//from   w ww  .  j ava2 s .  com
    } else {
        execute(tasks);
    }

    sw.stop();
    logger.info(sw.prettyPrint());
}

From source file:org.jsmiparser.AbstractMibTestCase.java

protected SmiMib getMib() {
    // this is a rather ugly hack to mimic JUnit4 @BeforeClass, without
    // having to annotate all test methods:
    if (m_mib.get() == null || m_testClass.get() != getClass()) {
        try {//from  w  w  w .ja va2  s.  c  o m
            SmiParser parser = createParser();
            StopWatch stopWatch = new StopWatch();
            stopWatch.start();
            SmiMib mib = parser.parse();
            stopWatch.stop();
            m_log.info("Parsing time: " + stopWatch.getTotalTimeSeconds() + " s");

            m_mib.set(mib);
            m_testClass.set(getClass());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    return m_mib.get();
}

From source file:org.dd4t.core.filters.impl.RichTextResolverFilter.java

/**
 * Recursivly resolves all components links.
 * /*from www . j a va2 s .  c o  m*/
 * @param item
 *            the to resolve the links
 * @param context
 *            the requestContext
 */
@Override
public void doFilter(Item item, RequestContext context) throws FilterException {

    StopWatch stopWatch = null;
    if (logger.isDebugEnabled()) {
        stopWatch = new StopWatch();
        stopWatch.start();
    }
    if (item instanceof GenericPage) {
        resolvePage((GenericPage) item);
    } else if (item instanceof GenericComponent) {
        resolveComponent((GenericComponent) item);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "RichTextResolverFilter. Item is not a GenericPage or GenericComponent so no component to resolve");
        }
    }
    if (logger.isDebugEnabled()) {
        stopWatch.stop();
        logger.debug("RichTextResolverFilter finished in " + stopWatch.getTotalTimeMillis() + " ms");
    }
}

From source file:com.googlecode.flyway.core.validation.DbValidator.java

/**
 * Validate the checksum of all existing sql migration in the metadata table with the checksum of the sql migrations
 * in the classpath/* w  ww . j  a v  a2 s  .  co  m*/
 *
 * @param resolvedMigrations All migrations available on the classpath, sorted by version, newest first.
 * @return description of validation error or NULL if no validation error was found
 */
public String validate(List<Migration> resolvedMigrations) {
    if (ValidationMode.NONE.equals(validationMode)) {
        return null;
    }

    LOG.debug(String.format("Validating (mode %s) migrations ...", validationMode));
    StopWatch stopWatch = new StopWatch();
    stopWatch.start();

    final List<MetaDataTableRow> appliedMigrations = new ArrayList<MetaDataTableRow>(
            metaDataTable.allAppliedMigrations());
    if (appliedMigrations.isEmpty()) {
        LOG.info("No migrations applied yet. No validation necessary.");
        return null;
    }

    List<Migration> migrations = new ArrayList<Migration>(resolvedMigrations);
    // migrations now with newest last
    Collections.reverse(migrations);
    final MetaDataTableRow firstAppliedMigration = appliedMigrations.get(0);
    if (MigrationType.INIT.equals(firstAppliedMigration.getMigrationType())) {
        // if first migration is INIT, just check checksum of following migrations
        final SchemaVersion initVersion = firstAppliedMigration.getVersion();
        appliedMigrations.remove(firstAppliedMigration);

        Iterator<Migration> iterator = migrations.iterator();
        while (iterator.hasNext()) {
            Migration migration = iterator.next();
            if (migration.getVersion().compareTo(initVersion) <= 0) {
                iterator.remove();
            }
        }
    }

    if (appliedMigrations.size() > migrations.size()) {
        List<SchemaVersion> schemaVersions = new ArrayList<SchemaVersion>();
        for (MetaDataTableRow metaDataTableRow : appliedMigrations) {
            schemaVersions.add(metaDataTableRow.getVersion());
        }
        for (Migration migration : migrations) {
            schemaVersions.remove(migration.getVersion());
        }

        String diff = StringUtils.collectionToCommaDelimitedString(schemaVersions);

        return String.format(
                "More applied migrations than classpath migrations: DB=%s, Classpath=%s, Missing migrations=(%s)",
                appliedMigrations.size(), migrations.size(), diff);
    }

    for (int i = 0; i < appliedMigrations.size(); i++) {
        MetaDataTableRow appliedMigration = appliedMigrations.get(i);
        //Migrations are sorted in the opposite order: newest first.
        Migration classpathMigration = migrations.get(i);

        if (!appliedMigration.getVersion().equals(classpathMigration.getVersion())) {
            return String.format("Version mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getVersion(),
                    classpathMigration.getVersion());

        }
        if (!appliedMigration.getMigrationType().equals(classpathMigration.getMigrationType())) {
            return String.format("Migration Type mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedMigration.getMigrationType(),
                    classpathMigration.getMigrationType());
        }

        final Integer appliedChecksum = appliedMigration.getChecksum();
        final Integer classpathChecksum = classpathMigration.getChecksum();
        if (!ObjectUtils.nullSafeEquals(appliedChecksum, classpathChecksum)) {
            return String.format("Checksum mismatch for migration %s: DB=%s, Classpath=%s",
                    appliedMigration.getScript(), appliedChecksum, classpathMigration.getChecksum());
        }
    }

    stopWatch.stop();
    if (appliedMigrations.size() == 1) {
        LOG.info(String.format("Validated 1 migration (mode: %s) (execution time %s)", validationMode,
                TimeFormat.format(stopWatch.getTotalTimeMillis())));
    } else {
        LOG.info(String.format("Validated %d migrations (mode: %s) (execution time %s)",
                appliedMigrations.size(), validationMode, TimeFormat.format(stopWatch.getTotalTimeMillis())));
    }

    return null;
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

@Override
public boolean execute() {
    boolean retVal = true;
    try {//from w ww  .ja v a2 s. c om
        StopWatch watch = new StopWatch();
        watch.start();
        StringBuffer roleInfo = getRoleInfoForDeployment();
        parseRoleInfo(roleInfo);
        watch.stop();
        taskCompletionDao.updateTaskCompletionDetails(watch.getTotalTimeSeconds(),
                "ProcessMonitorInstanceCount", "");
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        retVal = false;
    }
    return retVal;
}

From source file:org.jason.mapmaker.repository.impl.HibernateGenericRepository.java

public void save(Collection<T> objects) {

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

    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    int i = 1;/*from   w ww  .  jav  a2  s. c o  m*/
    for (T obj : objects) {

        session.save(obj);
        //sessionFactory.getCurrentSession().save(obj);
        i++;
        if (i % 100 == 0) {
            session.flush();
            session.clear();
            //sessionFactory.getCurrentSession().flush();
        }
    }

    tx.commit();
    session.close();

    stopWatch.stop();
    log.debug("Persisted " + i + " objects in " + stopWatch.getTotalTimeSeconds() + " seconds");

}

From source file:my.adam.smo.client.SocketClient.java

@Override
public RpcChannel connect(final InetSocketAddress sa) {
    RpcChannel rpcChannel = new RpcChannel() {
        private Channel c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();

        @Override/*from  w  w w.  j a v a2s  . co m*/
        public void callMethod(Descriptors.MethodDescriptor method, RpcController controller, Message request,
                Message responsePrototype, RpcCallback<Message> done) {
            StopWatch stopWatch = new StopWatch("callMethod");
            stopWatch.start();

            long id = seqNum.addAndGet(1);

            logger.trace("calling method: " + method.getFullName());

            //infinit reconnection loop
            while (reconnect && !c.isOpen()) {
                logger.debug("channel closed " + sa);
                logger.debug("trying to reconnect");
                c.disconnect().awaitUninterruptibly();
                c.unbind().awaitUninterruptibly();
                c = bootstrap.connect(sa).awaitUninterruptibly().getChannel();
                try {
                    Thread.sleep(reconnect_delay * 1000);
                } catch (InterruptedException e) {
                    logger.error("error while sleeping", e);
                }
            }

            RPCommunication.Request protoRequest = RPCommunication.Request.newBuilder()
                    .setServiceName(method.getService().getFullName()).setMethodName(method.getName())
                    .setMethodArgument(request.toByteString()).setRequestId(id).build();

            logger.trace("request built: " + request.toString());

            if (enableSymmetricEncryption) {
                protoRequest = getEncryptedRequest(protoRequest);
                logger.trace("symmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            if (enableAsymmetricEncryption) {
                protoRequest = getAsymEncryptedRequest(protoRequest);
                logger.trace("asymmetric encryption enabled, encrypted request: " + protoRequest.toString());
            }

            callbackMap.put(id, done);
            descriptorProtoMap.put(id, responsePrototype);

            c.write(protoRequest);
            logger.trace("request sent: " + protoRequest.toString());

            stopWatch.stop();
            logger.trace(stopWatch.shortSummary());
        }
    };
    logger.trace("connected to address: " + sa.toString());
    return rpcChannel;
}