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

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

Introduction

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

Prototype

@CheckReturnValue
public long elapsed(TimeUnit desiredUnit) 

Source Link

Document

Returns the current elapsed time shown on this stopwatch, expressed in the desired time unit, with any fraction rounded down.

Usage

From source file:org.terasology.polyworld.viewer.layers.MoistureModelFacetLayer.java

@Override
public void render(BufferedImage img, Region region) {
    MoistureModelFacet facet = region.getFacet(MoistureModelFacet.class);

    Stopwatch sw = Stopwatch.createStarted();

    Graphics2D g = img.createGraphics();
    int dx = region.getRegion().minX();
    int dy = region.getRegion().minZ();
    g.translate(-dx, -dy);// ww w  .j  av  a2s .  co m

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    for (Graph graph : facet.getKeys()) {
        MoistureModel model = facet.get(graph);
        draw(g, model, graph);
    }

    g.dispose();

    if (logger.isTraceEnabled()) {
        logger.debug("Rendered regions in {}ms.", sw.elapsed(TimeUnit.MILLISECONDS));
    }
}

From source file:com.vmware.photon.controller.apife.backends.ResourceTicketSqlBackend.java

/**
 * This method consumes quota associated with the specified cost
 * recorded in the usageMap. IF the cost pushes usage over the limit,
 * then this function has no side effect and false is returned.
 * <p/>/*ww  w  . ja v a2  s  . c o m*/
 * Quota limits and Cost metrics are loosely coupled in that a Quota limit
 * can be set for a narrow set of metrics. Only these metrics are used
 * for limit enforcement. All metrics are tracked in usage.
 * <p>
 * Note: it is assumed that locks preventing concurrency on this structure
 * are held externally, or are managed through optimistic concurrency/retry
 * on the container that owns the ResourceTicket object (normally the project).
 * </p>
 *
 * @param resourceTicketId - id of the resource ticket
 * @param cost             - the cost object representing how much will be consumed
 * @throws QuotaException when quota allocation fails
 */
@Override
@Transactional
public void consumeQuota(String resourceTicketId, QuotaCost cost) throws QuotaException {

    Stopwatch resourceTicketWatch = Stopwatch.createStarted();
    ResourceTicketEntity resourceTicket = resourceTicketDao.loadWithUpgradeLock(resourceTicketId);
    resourceTicketWatch.stop();
    logger.info("consumeQuota for resourceTicket {}, lock obtained in {} milliseconds", resourceTicket.getId(),
            resourceTicketWatch.elapsed(TimeUnit.MILLISECONDS));

    // first, whip through the cost's actualCostKeys and
    // compute the new usage. then, if usage is ok, commit
    // the new usage values and then update rawUsage
    List<QuotaLineItemEntity> newUsage = new ArrayList<>();
    for (String key : cost.getCostKeys()) {
        if (!resourceTicket.getUsageMap().containsKey(key)) {
            // make sure usage map has appropriate entries, its only initialized
            // with keys from the limit set
            resourceTicket.getUsageMap().put(key,
                    new QuotaLineItemEntity(key, 0.0, cost.getCost(key).getUnit()));
        }

        // capture current usage into a new object
        QuotaLineItemEntity qli = new QuotaLineItemEntity(key, resourceTicket.getUsageMap().get(key).getValue(),
                resourceTicket.getUsageMap().get(key).getUnit());
        QuotaLineItemEntity computedUsage = qli.add(cost.getCost(key));
        newUsage.add(computedUsage);
    }

    // now compare newUsage against limits. if usage > limit, then return false with no
    // side effects. otherwise, apply the new usage values, then blindly update rawUsage
    for (QuotaLineItemEntity qli : newUsage) {
        // only enforce limits is the usage entry is covered by
        // limits
        if (resourceTicket.getLimitMap().containsKey(qli.getKey())) {
            // test to see if the limit is less than the computed
            // new usage. if it is, then abort
            if (resourceTicket.getLimitMap().get(qli.getKey()).compareTo(qli) < 0) {
                throw new QuotaException(resourceTicket.getLimitMap().get(qli.getKey()),
                        resourceTicket.getLimitMap().get(qli.getKey()), qli);
            }
        }
    }

    // if we made it this far, commit the new usage
    for (QuotaLineItemEntity qli : newUsage) {
        resourceTicket.getUsageMap().put(qli.getKey(), qli);
    }
}

From source file:com.cinchapi.concourse.server.ManagedConcourseServer.java

/**
 * Install a Concourse Server in {@code directory} using {@code installer}.
 * /*  w w  w  . ja  va 2s  . c  o m*/
 * @param installer
 * @param directory
 * @return the server install directory
 */
private static String install(String installer, String directory) {
    try {
        Files.createDirectories(Paths.get(directory));
        Path binary = Paths.get(directory + File.separator + TARGET_BINARY_NAME);
        Files.deleteIfExists(binary);
        Files.copy(Paths.get(installer), binary);
        ProcessBuilder builder = new ProcessBuilder(Lists.newArrayList("sh", binary.toString()));
        builder.directory(new File(directory));
        builder.redirectErrorStream();
        Process process = builder.start();
        // The concourse-server installer prompts for an admin password in
        // order to make optional system wide In order to get around this
        // prompt, we have to "kill" the process, otherwise the server
        // install will hang.
        Stopwatch watch = Stopwatch.createStarted();
        while (watch.elapsed(TimeUnit.SECONDS) < 1) {
            continue;
        }
        watch.stop();
        process.destroy();
        TerminalFactory.get().restore();
        String application = directory + File.separator + "concourse-server"; // the install directory for the
                                                                              // concourse-server application
        process = Runtime.getRuntime().exec("ls " + application);
        List<String> output = Processes.getStdOut(process);
        if (!output.isEmpty()) {
            Files.deleteIfExists(Paths.get(application, "conf/concourse.prefs.dev")); // delete the dev prefs
                                                                                      // because those would
                                                                                      // take precedence over
                                                                                      // what is configured
                                                                                      // in this class
            configure(application);
            log.info("Successfully installed server in {}", application);
            return application;
        } else {
            throw new RuntimeException(MessageFormat.format(
                    "Unsuccesful attempt to " + "install server at {0} " + "using binary from {1}", directory,
                    installer));
        }

    } catch (Exception e) {
        throw Throwables.propagate(e);
    }

}

From source file:qa.qcri.nadeef.core.pipeline.ViolationCSVExport.java

@Override
protected File execute(File file) throws Exception {
    Stopwatch stopwatch = Stopwatch.createStarted();
    Tracer tracer = Tracer.getTracer(ViolationCSVExport.class);
    DBConfig config = getCurrentContext().getConnectionPool().getNadeefConfig();
    SQLDialectBase instance = SQLDialectFactory.getDialectManagerInstance(config.getDialect());
    tracer.info("Load " + file.getCanonicalPath() + " into violation table");
    if (instance.supportBulkLoad()) {
        instance.bulkLoad(config, "VIOLATION", file.toPath(), false);
    } else {//from  w  ww  . j  a v a 2s . c om
        instance.fallbackLoad(config, "VIOLATION", file, false);
    }

    PerfReport.appendMetric(PerfReport.Metric.ViolationExportTime, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    stopwatch.stop();
    return file;
}

From source file:co.mitro.core.servlets.ListMySecretsAndGroupKeys.java

public static ListMySecretsAndGroupKeysResponse executeWithoutAuditLog(MitroRequestContext context)
        throws SQLException, MitroServletException, DoEmailVerificationException {
    ListMySecretsAndGroupKeysResponse out = new RPC.ListMySecretsAndGroupKeysResponse();
    Stopwatch stopwatch = Stopwatch.createStarted();
    out.myUserId = context.requestor.getName();
    @SuppressWarnings("deprecation")
    AuthenticatedDB userDb = AuthenticatedDB.deprecatedNew(context.manager, context.requestor);

    out.groups = Maps.newHashMap();//from www .j  a va2 s  . co m
    out.organizations = Maps.newHashMap();
    Set<String> users = Sets.newHashSet();
    Set<Integer> groupIds = getGroupsUsersAndOrgsFromRawStatement(context, context.requestor.getId(), null,
            out.groups, out.organizations, users, null);
    for (GroupInfo gi : out.organizations.values()) {
        if (gi.isTopLevelOrg) {
            if (userDb.isOrganizationAdmin(gi.groupId)) {
                gi.isRequestorAnOrgAdmin = true;
            } else {
                gi.encryptedPrivateKey = null;
                gi.isRequestorAnOrgAdmin = false;
            }
        }
    }

    out.autocompleteUsers = Lists.newArrayList(users);
    out.secretToPath = Maps.newHashMap();
    getSecretInfo(context, AdminAccess.IGNORE_ACCESS_VIA_TOPLEVEL_GROUPS, out.secretToPath, groupIds, null,
            IncludeAuditLogInfo.NO_AUDIT_LOG_INFO);

    logger.info("{} elapsed: {} ms:", out.myUserId, stopwatch.elapsed(TimeUnit.MILLISECONDS));
    return out;
}

From source file:org.openqa.selenium.safari.SafariDriverCommandExecutor.java

/**
 * Launches a {@link SafariDriverServer}, opens Safari, and requests that
 * Safari connect to the server./*from  w w  w  .  ja v a  2s  .c o  m*/
 *
 * @throws IOException If an error occurs while launching Safari.
 */
synchronized void start() throws IOException {
    if (commandLine != null) {
        return;
    }

    server.start();

    if (cleanSession) {
        sessionData.clear();
    }

    File connectFile = prepareConnectFile(server.getUri());
    BrowserInstallation installation = browserLocator.findBrowserLocationOrFail();

    // Older versions of Safari could open a URL from the command line using "Safari -url $URL",
    // but this does not work on the latest versions (5.1.3). On Mac OS X, we can use
    // "open -a Safari $URL", but we need a cross platform solution. So, we generate a simple
    // HTML file that redirects to the base of our SafariDriverServer, which kicks off the
    // connection sequence.
    log.info("Launching Safari");
    commandLine = new CommandLine(installation.launcherFilePath(), connectFile.getAbsolutePath());
    commandLine.executeAsync();

    Stopwatch stopwatch = Stopwatch.createStarted();
    try {
        log.info("Waiting for SafariDriver to connect");
        connection = server.getConnection(10, TimeUnit.SECONDS);
    } catch (InterruptedException ignored) {
        // Do nothing.
    }

    if (connection == null) {
        stop();
        throw new UnreachableBrowserException(String.format("Failed to connect to SafariDriver after %d ms",
                stopwatch.elapsed(TimeUnit.MILLISECONDS)));
    }
    log.info(String.format("Driver connected in %d ms", stopwatch.elapsed(TimeUnit.MILLISECONDS)));
}

From source file:org.ow2.proactive.scheduler.task.executors.InProcessTaskExecutor.java

/**
 * Executes a task inside a task context.
 *
 * @param taskContext Task context to execute.
 * @param output      Standard output sink.
 * @param error       Error sink.//from w w w . j  av  a2  s  .  c  o  m
 * @return Returns the task result.
 */
@Override
public TaskResultImpl execute(TaskContext taskContext, PrintStream output, PrintStream error) {
    ScriptHandler scriptHandler = ScriptLoader.createLocalHandler();
    String nodesFile = null;
    SchedulerNodeClient schedulerNodeClient = null;
    RemoteSpace userSpaceClient = null;
    RemoteSpace globalSpaceClient = null;
    try {
        nodesFile = writeNodesFile(taskContext);
        VariablesMap variables = new VariablesMap();
        variables.setInheritedMap(taskContextVariableExtractor.extractVariables(taskContext, nodesFile, false));
        variables.setScopeMap(taskContextVariableExtractor.extractScopeVariables(taskContext));
        Map<String, String> resultMetadata = new HashMap<>();
        Map<String, String> thirdPartyCredentials = forkedTaskVariablesManager
                .extractThirdPartyCredentials(taskContext);
        schedulerNodeClient = forkedTaskVariablesManager.createSchedulerNodeClient(taskContext);
        userSpaceClient = forkedTaskVariablesManager.createDataSpaceNodeClient(taskContext, schedulerNodeClient,
                IDataSpaceClient.Dataspace.USER);
        globalSpaceClient = forkedTaskVariablesManager.createDataSpaceNodeClient(taskContext,
                schedulerNodeClient, IDataSpaceClient.Dataspace.GLOBAL);

        forkedTaskVariablesManager.addBindingsToScriptHandler(scriptHandler, taskContext, variables,
                thirdPartyCredentials, schedulerNodeClient, userSpaceClient, globalSpaceClient, resultMetadata);

        Stopwatch stopwatch = Stopwatch.createUnstarted();
        TaskResultImpl taskResult;
        try {
            stopwatch.start();
            Serializable result = execute(taskContext, output, error, scriptHandler, thirdPartyCredentials,
                    variables);
            stopwatch.stop();
            taskResult = new TaskResultImpl(taskContext.getTaskId(), result, null,
                    stopwatch.elapsed(TimeUnit.MILLISECONDS));
        } catch (Throwable e) {
            stopwatch.stop();
            e.printStackTrace(error);
            taskResult = new TaskResultImpl(taskContext.getTaskId(), e, null,
                    stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }

        executeFlowScript(taskContext.getControlFlowScript(), scriptHandler, output, error, taskResult);

        taskResult.setPropagatedVariables(
                SerializationUtil.serializeVariableMap(variables.getPropagatedVariables()));
        taskResult.setMetadata(resultMetadata);

        return taskResult;
    } catch (Throwable e) {
        e.printStackTrace(error);
        return new TaskResultImpl(taskContext.getTaskId(), e);
    } finally {
        if (nodesFile != null && !nodesFile.isEmpty()) {
            FileUtils.deleteQuietly(new File(nodesFile));
        }
    }
}

From source file:org.eclipse.viatra.modelobfuscator.application.common.ModelObfuscatorHeadless.java

/**
 * @param outputDirectory//from w  ww .  j a va 2 s. com
 * @param inputs
 * @param obfuscatorBuilder
 */
private void performObfuscation(File outputDirectory, Map<String, FileInputStream> inputs,
        XMLModelObfuscatorBuilder obfuscatorBuilder) {
    for (Entry<String, FileInputStream> input : inputs.entrySet()) {
        BufferedInputStream bufferedInputStream = new BufferedInputStream(input.getValue());
        obfuscatorBuilder.setInput(bufferedInputStream);
        String fileName = input.getKey();
        File output = new File(outputDirectory, fileName);
        BufferedOutputStream bufferedOutputStream;
        try {
            bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(output));
            obfuscatorBuilder.setOutput(bufferedOutputStream);
            XMLModelObfuscator obfuscator = obfuscatorBuilder.build();
            System.out.println("Obfuscating " + fileName);
            Stopwatch stopwatch = Stopwatch.createStarted();
            obfuscator.obfuscate();
            stopwatch.stop();
            System.out.println("Obfuscation finished in: " + stopwatch.elapsed(TimeUnit.MILLISECONDS) + " ms ("
                    + stopwatch.elapsed(TimeUnit.NANOSECONDS) + " ns)");
            bufferedOutputStream.close();
            bufferedInputStream.close();
        } catch (FileNotFoundException e) {
            reportError("Could not ouput to file " + output.getPath());
        } catch (IOException e) {
            reportError("Could not close output file " + output.getPath());
        }
    }
}

From source file:joshelser.LimitAndSumColumnFamilyIterator.java

@Override
public void next() throws IOException {
    Stopwatch nextSw = Stopwatch.createStarted();

    // Make sure we invalidate our last record
    nextRecordNotFound();// ww w  .  j a  v a2 s  . co  m

    // Catch the case where we have no data and there's nothing to next()
    if (!getSource().hasTop()) {
        return;
    }

    getSource().next();

    aggregate();

    nextSw.stop();
    log.info("Next duration: " + nextSw.elapsed(TimeUnit.MILLISECONDS));
}

From source file:benchmarkio.consumer.rabbitmq.RabbitMQMessageConsumer.java

@Override
public Histogram call() throws Exception {
    final String queueName = channel.queueDeclare().getQueue();
    channel.queueBind(queueName, topic, "#");

    final QueueingConsumer consumer = new QueueingConsumer(channel);
    channel.basicConsume(queueName, true, consumer);

    logger.info("topic: {}, queueName: {}", topic, queueName);

    int messageCount = 0;

    // Note that this is a polling consumer and will be terminated
    // whenever the Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS passes and no new messages have arrived.
    while (true) {
        // Start// w  w w .  j  a va 2  s  .c o  m
        final Stopwatch stopwatch = Stopwatch.createStarted();

        final QueueingConsumer.Delivery delivery = consumer
                .nextDelivery(Consts.POLLING_CONSUMER_MAX_IDLE_TIME_MS);

        if (delivery == null) {
            logger.info("Consumer was terminated through timeout");

            break;
        }

        final byte[] message = delivery.getBody();

        messageCount++;

        final String routingKey = delivery.getEnvelope().getRoutingKey();

        // End
        stopwatch.stop();
        histogram.recordValue(stopwatch.elapsed(Consts.TIME_UNIT_FOR_REPORTING));
    }

    logger.info("In total consumed {} messages", messageCount);

    return histogram;
}