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

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

Introduction

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

Prototype

public Stopwatch stop() 

Source Link

Document

Stops the stopwatch.

Usage

From source file:com.palantir.atlasdb.keyvalue.cassandra.CassandraJMXCompaction.java

private boolean performTableCompaction(String keyspace, String tableName) {
    try {/*from w  ww.j a  v  a2s.co  m*/
        Stopwatch timer = Stopwatch.createStarted();
        ssProxy.forceKeyspaceCompaction(keyspace, tableName);
        log.info("Compaction for {}:{} completed on node {} in {}", keyspace, Arrays.asList(tableName), host,
                timer.stop());
    } catch (IOException e) {
        log.error("Invalid keyspace or tableNames specified for forceTableCompaction()", e);
        return false;
    } catch (ExecutionException e) {
        log.error("ExecutionException in forceTableCompaction()", e);
        return false;
    } catch (InterruptedException e) {
        log.error("InterruptedException in forceTableCompaction()", e);
        return false;
    }
    return true;
}

From source file:edu.mit.streamjit.impl.distributed.runtimer.OnlineTuner.java

@Override
public void run() {
    int tryCount = 0;
    try {//from   w  ww .  j ava2 s .c om
        tuner.startTuner(String.format("lib%sopentuner%sstreamjit%sstreamjit2.py", File.separator,
                File.separator, File.separator));

        tuner.writeLine("program");
        tuner.writeLine(app.name);

        tuner.writeLine("confg");
        String s = getConfigurationString(app.blobConfiguration);
        tuner.writeLine(s);

        System.out.println("New tune run.............");
        while (manager.getStatus() != AppStatus.STOPPED) {
            String pythonDict = tuner.readLine();
            if (pythonDict == null)
                break;

            // At the end of the tuning, Opentuner will send "Completed"
            // msg. This means no more tuning.
            if (pythonDict.equals("Completed")) {
                handleTermination();
                break;
            }

            System.out.println("----------------------------------------------");
            System.out.println(tryCount++);
            Configuration config = rebuildConfiguration(pythonDict, app.blobConfiguration);

            if (GlobalConstants.saveAllConfigurations)
                saveConfg(config, tryCount);

            try {
                if (!cfgManager.newConfiguration(config)) {
                    tuner.writeLine("-1");
                    continue;
                }

                if (manager.isRunning()) {
                    boolean state = drainer.startDraining(0);
                    if (!state) {
                        System.err.println("Final drain has already been called. no more tuning.");
                        tuner.writeLine("exit");
                        break;
                    }

                    System.err.println("awaitDrainedIntrmdiate");
                    drainer.awaitDrainedIntrmdiate();

                    if (GlobalConstants.useDrainData) {
                        System.err.println("awaitDrainData...");
                        drainer.awaitDrainData();
                        DrainData drainData = drainer.getDrainData();
                        app.drainData = drainData;
                    }
                }

                drainer.setBlobGraph(app.blobGraph);
                System.err.println("Reconfiguring...");
                if (manager.reconfigure()) {
                    Stopwatch stopwatch = Stopwatch.createStarted();
                    manager.awaitForFixInput();
                    stopwatch.stop();
                    // TODO: need to check the manager's status before
                    // passing
                    // the time. Exceptions, final drain, etc may causes app
                    // to
                    // stop executing.
                    long time = stopwatch.elapsed(TimeUnit.MILLISECONDS);

                    System.out.println("Execution time is " + time + " milli seconds");
                    tuner.writeLine(new Double(time).toString());
                } else {
                    tuner.writeLine("-1");
                    continue;
                }
            } catch (Exception ex) {
                System.err.println("Couldn't compile the stream graph with this configuration");
                tuner.writeLine("-1");
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        drainer.dumpDraindataStatistics();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.geogit.gwc.TruncateTilesOnUpdateRefHook.java

@SuppressWarnings("unchecked")
@Override//from w  ww  .  j  a  va  2s.  c  om
public <T> T post(AbstractGeoGitOp<T> command, Object retVal, boolean success) throws Exception {
    checkArgument(command instanceof UpdateRef);
    final UpdateRef cmd = (UpdateRef) command;
    final String refName = (String) cmd.getClientData().get("name");
    checkState(refName != null, "refName not captured in pre-hook");
    if (Boolean.TRUE.equals(cmd.getClientData().get("ignore"))) {
        LOGGER.debug("GWC geogit truncate post-hook returning, ref '{}' is ignored.", refName);
        return (T) retVal;
    }

    if (!success) {
        LOGGER.info("GWC geogit truncate post-hook returning, UpdateRef operation failed on ref '{}'.",
                refName);
        return (T) retVal;
    }

    final GWC mediator = GWC.get();
    if (mediator == null) {
        LOGGER.debug("GWC geogit truncate post-hook returning, GWC mediator not installed?.");
        return (T) retVal;
    }

    final Optional<Ref> oldValue = (Optional<Ref>) cmd.getClientData().get("oldValue");
    final Optional<Ref> newValue = (Optional<Ref>) retVal;// == oldValue if the ref was deleted

    checkState(oldValue != null, "oldValue not captured in pre-hook");

    if (oldValue.equals(newValue)) {
        LOGGER.debug("GWC geogit truncate post-hook returning, ref '{}' didn't change ({}).", refName,
                oldValue);
        return (T) retVal;
    }

    List<LayerInfo> affectedLayers;
    final String newRefName = newValue.get().getName();
    Stopwatch sw = Stopwatch.createStarted();
    affectedLayers = findAffectedLayers(mediator, command.context(), newRefName);
    LOGGER.debug("GWC geogit truncate post-hook found {} affected layers on branch {} in {}.",
            affectedLayers.size(), refName, sw.stop());

    for (LayerInfo layer : affectedLayers) {
        truncate(mediator, command.context(), layer, oldValue, newValue);
    }
    return (T) retVal;
}

From source file:co.cask.cdap.examples.wordcount.RetrieveCountsHandler.java

/**
 * Returns the counts for all words in the input.  The request body is expected to contain
 * a comma-separated list of words.//from ww w.ja  v a2  s  . c om
 */
@Path("counts")
@POST
public void getCounts(HttpServiceRequest request, HttpServiceResponder responder) {
    String wordString = Charsets.UTF_8.decode(request.getContent()).toString();
    String[] words = wordString.split(",");
    Map<String, Long> wordCounts = Maps.newHashMap();
    Stopwatch timer = new Stopwatch().start();
    for (int i = 0; i < words.length; i++) {
        byte[] countBytes = wordCountsTable.read(Bytes.toBytes(words[i]));
        long count = countBytes != null ? Bytes.toLong(countBytes) : 0;
        wordCounts.put(words[i], count);
    }
    timer.stop();
    Map<String, Object> responseBody = Maps.newHashMap();
    responseBody.put("counts", wordCounts);
    responseBody.put("elapsed", timer.toString());
    responder.sendJson(responseBody);
}

From source file:net.monofraps.gradlebukkit.tasks.RunBukkit.java

@TaskAction
public void doWork() throws IOException, LifecycleExecutionException, InterruptedException {
    final int latestDownloadedBuild = findBukkitBuildToRun();
    if (latestDownloadedBuild < 0) {
        throw new LifecycleExecutionException("Couldn't find Bukkit jar to run.");
    }//from  ww  w . j  a  v  a2  s.  co  m

    final String bukkitJarName = "bukkit-" + latestDownloadedBuild + ".jar";

    final RemoteDebugging debugConfiguration = ((Bukkit) getProject().getExtensions().getByName("bukkit"))
            .getDebugSettings();
    final String debuggingArguments = (debugConfiguration == null) ? "" : debugConfiguration.getJvmArguments();

    final ProcessBuilder bukkitProcessBuilder = new ProcessBuilder("java", debuggingArguments, "-jar",
            bukkitJarName);
    bukkitProcessBuilder.environment().putAll(System.getenv());
    bukkitProcessBuilder.directory(new File(getProject().getBuildDir(), "bukkit"));

    getLogger().lifecycle("Starting Bukkit...");
    final Process bukkitProcess = bukkitProcessBuilder.start();

    final StreamGrabber errorGrabber = new StreamGrabber(bukkitProcess.getErrorStream());
    final StreamGrabber stdoutGrabber = new StreamGrabber(bukkitProcess.getInputStream());
    errorGrabber.start();
    stdoutGrabber.start();

    final PrintWriter stdinWriter = new PrintWriter(bukkitProcess.getOutputStream());
    String line;
    while ((line = System.console().readLine()) != null && !line.equals("gterm")) {
        stdinWriter.write(line);
        stdinWriter.write("\n");
        stdinWriter.flush();

        try {
            bukkitProcess.exitValue();
            break;
        } catch (final IllegalThreadStateException ignored) {
        }
    }

    try {
        bukkitProcess.exitValue();
    } catch (final IllegalThreadStateException ex) {
        final Thread joiner = new Thread() {
            @Override
            public void run() {
                bukkitProcess.destroy();
            }
        };

        joiner.start();
        final Stopwatch stopwatch = new Stopwatch();
        stopwatch.start();
        while (joiner.isAlive()) {
            if (stopwatch.elapsed(TimeUnit.MILLISECONDS) > 60) {
                joiner.interrupt();
                joiner.join(5000);
            }
            Thread.sleep(500);
        }
        stopwatch.stop();
    }

    getLogger().lifecycle("Bukkit process exited with exit code " + bukkitProcess.exitValue());
}

From source file:org.litecoinj.crypto.KeyCrypterScrypt.java

/**
 * Generate AES key./*from  www.j ava 2s  .  c  om*/
 *
 * This is a very slow operation compared to encrypt/ decrypt so it is normally worth caching the result.
 *
 * @param password    The password to use in key generation
 * @return            The KeyParameter containing the created AES key
 * @throws            KeyCrypterException
 */
@Override
public KeyParameter deriveKey(CharSequence password) throws KeyCrypterException {
    byte[] passwordBytes = null;
    try {
        passwordBytes = convertToByteArray(password);
        byte[] salt = new byte[0];
        if (scryptParameters.getSalt() != null) {
            salt = scryptParameters.getSalt().toByteArray();
        } else {
            // Warn the user that they are not using a salt.
            // (Some early MultiBit wallets had a blank salt).
            log.warn(
                    "You are using a ScryptParameters with no salt. Your encryption may be vulnerable to a dictionary attack.");
        }

        final Stopwatch watch = Stopwatch.createStarted();
        byte[] keyBytes = SCrypt.scrypt(passwordBytes, salt, (int) scryptParameters.getN(),
                scryptParameters.getR(), scryptParameters.getP(), KEY_LENGTH);
        watch.stop();
        log.info("Deriving key took {} for {} scrypt iterations.", watch, scryptParameters.getN());
        return new KeyParameter(keyBytes);
    } catch (Exception e) {
        throw new KeyCrypterException("Could not generate key from password and salt.", e);
    } finally {
        // Zero the password bytes.
        if (passwordBytes != null) {
            java.util.Arrays.fill(passwordBytes, (byte) 0);
        }
    }
}

From source file:ch.ge.ve.offlineadmin.controller.BallotDecryptionController.java

private void performBallotDecryption(BallotCipherService ballotCipherService,
        List<EncryptedBallotAndWrappedKey> encryptedBallots) {
    DecryptionService decryptionService = new DecryptionService(ballotCipherService, consoleOutputController);
    // Using a task here, so as to perform decryption without blocking the UI.
    Task<List<String>> ballotDecryptionTask = new BallotDecryptionTask(decryptionService, encryptedBallots);

    final Stopwatch ballotDecryption = Stopwatch.createStarted();

    // Handle success
    ballotDecryptionTask.setOnSucceeded(event -> {
        ballotDecryption.stop();
        consoleOutputController/*www  .ja  v  a  2  s  . c  o m*/
                .logOnScreen(String.format(resources.getString("ballot_decryption.decryption_finished"),
                        formatElapsedTime(ballotDecryption)));

        consoleOutputController
                .progressMessage(String.format(resources.getString("ballot_decryption.invalid_ballots_text"),
                        decryptionService.getInvalidCounter())); //"Count of invalid ballots : " +
        saveCleartextBallots(ballotDecryptionTask.getValue());
        consoleOutputController.incrementStepCount();
    });

    // Handle failure
    ballotDecryptionTask.exceptionProperty().addListener((observable, oldValue, newException) -> {
        if (newException != null) {
            LOGGER.error(resources.getString("ballot_decryption.exception_occurred"), newException);
            consoleOutputController.logOnScreen(resources.getString("ballot_decryption.exception_occurred"),
                    LogLevel.ERROR);
        }
    });

    // Start execution
    exec.execute(ballotDecryptionTask);
}

From source file:org.graylog2.indexer.ranges.RebuildIndexRangesJob.java

@Override
public void execute() {
    info("Re-calculating index ranges.");

    String[] indices = deflector.getAllGraylogIndexNames();
    if (indices == null || indices.length == 0) {
        info("No indices, nothing to calculate.");
        return;//w ww  .  j av a 2s .c  o m
    }
    indicesToCalculate = indices.length;

    Stopwatch sw = Stopwatch.createStarted();
    final String deflectorIndexName = deflector.getName();
    for (String index : indices) {
        if (deflectorIndexName.equals(index)) {
            continue;
        }
        if (cancelRequested) {
            info("Stop requested. Not calculating next index range, not updating ranges.");
            sw.stop();
            return;
        }

        try {
            final IndexRange indexRange = indexRangeService.calculateRange(index);
            indexRangeService.save(indexRange);
            LOG.debug("Created ranges for index {}: {}", index, indexRange);
        } catch (Exception e) {
            LOG.info("Could not calculate range of index [" + index + "]. Skipping.", e);
        } finally {
            indicesCalculated++;
        }
    }

    info("Done calculating index ranges for " + indices.length + " indices. Took "
            + sw.stop().elapsed(TimeUnit.MILLISECONDS) + "ms.");
}

From source file:nl.knaw.huygens.timbuctoo.storage.graph.tinkerpop.TinkerPopLowLevelAPI.java

public Iterator<Edge> getLatestEdgesOf(Class<? extends Relation> type) {
    Stopwatch stopwatch = Stopwatch.createStarted();
    LOG.debug("Begin get latest edges for [{}]", type);

    Stopwatch queryStopwatch = Stopwatch.createStarted();
    LOG.debug("Begin query latest edges for [{}]", type);
    Iterable<Edge> edges = queryLatestByType(type).edges();
    LOG.debug("End querying latest edges for [{}] in [{}]", type, queryStopwatch.stop());

    LOG.debug("End get latest edges for [{}] in [{}]", type, stopwatch.stop());
    return edges.iterator();
}

From source file:org.terasology.cities.debug.SwingRasterizer.java

/**
 * @param g the graphics object//from  ww w  .  j av a 2s. co m
 * @param sector the sector to render
 */
public void rasterizeSector(Graphics2D g, Sector sector) {

    Stopwatch sw = debugMap.getUnchecked(sector.toString());
    sw.start();

    drawCityNames(g, sector);
    drawLakes(g, sector);
    drawFrame(g, sector);
    drawSectorText(g, sector);

    sw.stop();
}