Example usage for com.google.common.base Stopwatch createStarted

List of usage examples for com.google.common.base Stopwatch createStarted

Introduction

In this page you can find the example usage for com.google.common.base Stopwatch createStarted.

Prototype

@CheckReturnValue
public static Stopwatch createStarted() 

Source Link

Document

Creates (and starts) a new stopwatch using System#nanoTime as its time source.

Usage

From source file:org.geogig.geoserver.gwc.TruncateHelper.java

public static void issueTruncateTasks(Context context, Optional<Ref> oldRef, Optional<Ref> newRef,
        GeoServerTileLayer tileLayer, TileBreeder breeder) {

    final ObjectId oldCommit = oldRef.isPresent() ? oldRef.get().getObjectId() : ObjectId.NULL;
    final ObjectId newCommit = newRef.isPresent() ? newRef.get().getObjectId() : ObjectId.NULL;

    final String tileLayerName = tileLayer.getName();
    final String layerTreeName = tileLayer.getLayerInfo().getResource().getNativeName();

    LOGGER.debug(/*from   www  .j ava 2 s.c  o  m*/
            String.format("Computing minimal bounds geometry on layer '%s' (tree '%s') for change %s...%s ",
                    tileLayerName, layerTreeName, oldCommit, newCommit));
    final Geometry minimalBounds;
    Stopwatch sw = Stopwatch.createStarted();
    try {
        MinimalDiffBounds geomBuildCommand = context.command(MinimalDiffBounds.class)
                .setOldVersion(oldCommit.toString()).setNewVersion(newCommit.toString());

        geomBuildCommand.setTreeNameFilter(layerTreeName);

        minimalBounds = geomBuildCommand.call();
        sw.stop();
        if (minimalBounds.isEmpty()) {
            LOGGER.debug(String.format("Feature tree '%s' not affected by change %s...%s (took %s)",
                    layerTreeName, oldCommit, newCommit, sw));
            return;
        }
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug(String.format("Minimal bounds on layer '%s' computed in %s: %s", tileLayerName, sw,
                    formattedWKT(minimalBounds)));
        }
    } catch (Exception e) {
        sw.stop();
        LOGGER.error(String.format("Error computing minimal bounds for %s...%s on layer '%s' after %s",
                oldCommit, newCommit, tileLayerName, sw));
        throw Throwables.propagate(e);
    }
    final Set<String> gridSubsets = tileLayer.getGridSubsets();

    LayerInfo layerInfo = tileLayer.getLayerInfo();
    ResourceInfo resource = layerInfo.getResource();
    final CoordinateReferenceSystem sourceCrs;
    {
        CoordinateReferenceSystem nativeCrs = resource.getNativeCRS();
        if (nativeCrs == null) {
            // no native CRS specified, layer must have been configured with an overriding one
            sourceCrs = resource.getCRS();
        } else {
            sourceCrs = nativeCrs;
        }
    }
    for (String gridsetId : gridSubsets) {
        GridSubset gridSubset = tileLayer.getGridSubset(gridsetId);
        final CoordinateReferenceSystem gridSetCrs = getGridsetCrs(gridSubset);

        LOGGER.debug("Reprojecting geometry mask to gridset {}", gridsetId);
        Geometry geomInGridsetCrs = transformToGridsetCrs(minimalBounds, sourceCrs, gridSetCrs);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("geometry mask reprojected to gridset {}: {}", gridsetId,
                    formattedWKT(geomInGridsetCrs));
        }
        geomInGridsetCrs = bufferAndSimplifyBySizeOfSmallerTile(geomInGridsetCrs, gridSetCrs, gridSubset);
        try {
            truncate(tileLayer, gridsetId, geomInGridsetCrs, breeder);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:org.opendaylight.controller.cluster.datastore.jmx.mbeans.shard.OnDemandShardStateCache.java

private OnDemandShardState retrieveState() throws Exception {
    stateRetrievalTime = null;//  w  w w . j a  v a  2 s.  c  om
    Timeout timeout = new Timeout(10, TimeUnit.SECONDS);
    Stopwatch timer = Stopwatch.createStarted();

    OnDemandShardState state = (OnDemandShardState) Await
            .result(Patterns.ask(shardActor, GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());

    stateRetrievalTime = timer.stop().toString();
    return state;
}

From source file:org.activityinfo.server.endpoint.gwtrpc.AdvisoryLock.java

public AdvisoryLock(HibernateEntityManager entityManager) {
    Preconditions.checkNotNull(entityManager);

    this.entityManager = entityManager;

    try {/*from ww w . ja v  a2s  .c  om*/
        Stopwatch stopwatch = Stopwatch.createStarted();

        String sql = String.format("SELECT GET_LOCK('%s', %s)", ADVISORY_LOCK_NAME, ADVISORY_GET_LOCK_TIMEOUT);

        Query query = entityManager.getSession().createSQLQuery(sql);
        Object result = query.uniqueResult();

        if (result == null) {
            throw new UnexpectedCommandException("Error occurred while trying to obtain advisory lock.");
        }

        int resultCode = ((Number) result).intValue();
        if (resultCode == TIMEOUT_CODE) { // time out
            LOGGER.severe("Timed out waiting for write lock.");
            throw new CommandTimeoutException();
        }

        if (resultCode != SUCCESS_CODE) { // not success
            LOGGER.severe("Failed to acquire lock, result code: " + resultCode);
            throw new RuntimeException("Failed to acquire lock, result code: " + resultCode);
        }

        stopwatch.stop();
        LOGGER.finest("Acquiring advisory lock takes: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + "ms");
    } catch (CommandTimeoutException e) {
        throw e;
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "Internal error during acquiring advisory lock: " + e.getMessage(), e);
        throw new RuntimeException("Exception caught while trying to acquire update lock", e);
    }
}

From source file:org.graylog2.plugin.indexer.retention.RetentionStrategy.java

public void runStrategy(String indexName) {
    Stopwatch sw = Stopwatch.createStarted();

    if (iterates()) {
        // TODO: Run per message.
    }/*from   ww w. ja va2s  .  co m*/

    // Delete or close index.
    switch (getType()) {
    case DELETE:
        LOG.info("Strategy is deleting.");
        indexManagement.delete(indexName);
        break;
    case CLOSE:
        LOG.info("Strategy is closing.");
        indexManagement.close(indexName);
        break;
    }

    LOG.info("Finished index retention strategy [" + this.getClass().getCanonicalName() + "] for "
            + "index <{}> in {}ms.", indexName, sw.stop().elapsed(TimeUnit.MILLISECONDS));
}

From source file:io.takari.maven.plugins.compile.jdt.ClasspathDigester.java

public HashMap<String, byte[]> digestDependencies(List<File> dependencies) throws IOException {
    Stopwatch stopwatch = Stopwatch.createStarted();

    HashMap<String, byte[]> digest = new HashMap<String, byte[]>();

    // scan dependencies backwards to properly deal with duplicate type definitions
    for (int i = dependencies.size() - 1; i >= 0; i--) {
        File file = dependencies.get(i);
        if (file.isFile()) {
            digest.putAll(digestJar(file));
        } else if (file.isDirectory()) {
            digest.putAll(digestDirectory(file));
        } else {//from  w  w w.  ja  v a2s  .c om
            // happens with reactor dependencies with empty source folders
            continue;
        }
    }

    log.debug("Analyzed {} classpath dependencies ({} ms)", dependencies.size(),
            stopwatch.elapsed(TimeUnit.MILLISECONDS));

    return digest;
}

From source file:org.locationtech.geogig.rest.repository.SendObjectResource.java

@Override
public void post(Representation entity) {
    InputStream input = null;//ww w  .j ava  2 s.  c o  m

    Request request = getRequest();
    try {
        LOGGER.info("Receiving objects from {}", request.getClientInfo().getAddress());
        Representation representation = request.getEntity();
        input = representation.getStream();
        final GeoGIG ggit = getGeogig(request).get();
        final BinaryPackedObjects unpacker = new BinaryPackedObjects(ggit.getRepository().objectDatabase());

        CountingInputStream countingStream = new CountingInputStream(input);

        Stopwatch sw = Stopwatch.createStarted();
        IngestResults ingestResults = unpacker.ingest(countingStream);
        sw.stop();

        LOGGER.info(String.format(
                "SendObjectResource: Processed %,d objects.\nInserted: %,d.\nExisting: %,d.\nTime to process: %s.\nStream size: %,d bytes.\n",
                ingestResults.total(), ingestResults.getInserted(), ingestResults.getExisting(), sw,
                countingStream.getCount()));

    } catch (IOException e) {
        LOGGER.warn("Error processing incoming objects from {}", request.getClientInfo().getAddress(), e);
        throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e);
    } finally {
        if (input != null)
            Closeables.closeQuietly(input);
    }
}

From source file:com.twitter.distributedlog.ZooKeeperClientUtils.java

/**
 * Expire given zookeeper client's session.
 *
 * @param zkc//from  ww w.ja  v  a2  s  . c  o  m
 *          zookeeper client
 * @param zkServers
 *          zookeeper servers
 * @param timeout
 *          timeout
 * @throws Exception
 */
public static void expireSession(ZooKeeperClient zkc, String zkServers, int timeout) throws Exception {
    final CountDownLatch expireLatch = new CountDownLatch(1);
    final CountDownLatch latch = new CountDownLatch(1);
    ZooKeeper oldZk = zkc.get();
    oldZk.exists("/", new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            logger.debug("Receive event : {}", event);
            if (event.getType() == Event.EventType.None && event.getState() == Event.KeeperState.Expired) {
                expireLatch.countDown();
            }
        }
    });
    ZooKeeper newZk = new ZooKeeper(zkServers, timeout, new Watcher() {
        @Override
        public void process(WatchedEvent event) {
            if (Event.EventType.None == event.getType()
                    && Event.KeeperState.SyncConnected == event.getState()) {
                latch.countDown();
            }
        }
    }, oldZk.getSessionId(), oldZk.getSessionPasswd());
    if (!latch.await(timeout, TimeUnit.MILLISECONDS)) {
        throw KeeperException.create(KeeperException.Code.CONNECTIONLOSS);
    }
    newZk.close();

    boolean done = false;
    Stopwatch expireWait = Stopwatch.createStarted();
    while (!done && expireWait.elapsed(TimeUnit.MILLISECONDS) < timeout * 2) {
        try {
            zkc.get().exists("/", false);
            done = true;
        } catch (KeeperException ke) {
            done = (ke.code() == KeeperException.Code.SESSIONEXPIRED);
        }
    }

    assertTrue("Client should receive session expired event.",
            expireLatch.await(timeout, TimeUnit.MILLISECONDS));
}

From source file:org.restlet.ext.apispark.internal.firewall.rule.counter.PeriodicCounter.java

/**
 * Constructor./* ww  w .j  ava 2  s  .c o m*/
 * 
 * @param period
 *            The period associated to the counter.
 */
public PeriodicCounter(long period) {
    this.counter = new AtomicInteger();
    this.period = period;
    this.stopwatch = Stopwatch.createStarted();
    this.counterReset = new AtomicLong();
}

From source file:org.apache.eagle.alert.coordinator.trigger.CoordinatorTrigger.java

@Override
public void run() {
    if (Coordinator.isPeriodicallyForceBuildEnable()) {
        LOG.info("CoordinatorTrigger started ... ");

        Stopwatch watch = Stopwatch.createStarted();
        ZKConfig zkConfig = ZKConfigBuilder.getZKConfig(config);
        try (ExclusiveExecutor executor = new ExclusiveExecutor(zkConfig)) {
            executor.execute(Coordinator.GREEDY_SCHEDULER_ZK_PATH, () -> {
                // schedule
                IScheduleContext context = new ScheduleContextBuilder(config, client).buildContext();
                TopologyMgmtService mgmtService = new TopologyMgmtService();
                IPolicyScheduler scheduler = PolicySchedulerFactory.createScheduler();

                scheduler.init(context, mgmtService);

                ScheduleState state = scheduler.schedule(new ScheduleOption());

                // use try catch to use AutoCloseable interface to close producer automatically
                try (ConfigBusProducer producer = new ConfigBusProducer(ZKConfigBuilder.getZKConfig(config))) {
                    Coordinator.postSchedule(client, state, producer);
                }/*from   www .  j  a v  a 2  s.c  om*/

                watch.stop();
                LOG.info("CoordinatorTrigger ended, used time {} sm.", watch.elapsed(TimeUnit.MILLISECONDS));
            });
        } catch (Exception e) {
            LOG.error("trigger schedule failed!", e);
        }
    } else {
        LOG.info("CoordinatorTrigger found isPeriodicallyForceBuildEnable = false, skipped build");
    }
}

From source file:org.apache.bookkeeper.proto.PacketProcessorBase.java

PacketProcessorBase(Request request, Channel channel, Bookie bookie, StatsLogger statsLogger) {
    this.request = request;
    this.channel = channel;
    this.bookie = bookie;
    this.enqueueStopwatch = Stopwatch.createStarted();
    this.statsLogger = statsLogger;
    this.channelWriteOpStatsLogger = statsLogger.getOpStatsLogger(CHANNEL_WRITE);
}