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:de.schildbach.wallet.WalletApplication.java

private void initMnemonicCode() {
    try {/*from w w w. j  a v a 2  s .  c om*/
        final Stopwatch watch = Stopwatch.createStarted();
        MnemonicCode.INSTANCE = new MnemonicCode(getAssets().open(BIP39_WORDLIST_FILENAME), null);
        watch.stop();
        log.info("BIP39 wordlist loaded from: '{}', took {}", BIP39_WORDLIST_FILENAME, watch);
    } catch (final IOException x) {
        throw new Error(x);
    }
}

From source file:ch.ge.ve.protopoc.service.protocol.DefaultVotingClient.java

@Override
public List<String> sumbitVote(String identificationCredentials, List<Integer> selections)
        throws VoteCastingException {
    Preconditions.checkState(publicParameters != null,
            "The public parameters need to have been retrieved first");
    Preconditions.checkState(electionSet != null, "The electionSet needs to have been retrieved first");

    Stopwatch stopwatch = Stopwatch.createStarted();
    List<EncryptionPublicKey> publicKeyParts = bulletinBoardService.getPublicKeyParts();
    EncryptionPublicKey systemPublicKey = keyEstablishmentAlgorithms.getPublicKey(publicKeyParts);

    BallotQueryAndRand ballotQueryAndRand = computeBallot(identificationCredentials, selections,
            systemPublicKey);//from w ww  . jav a 2s . co  m
    randomizations = ballotQueryAndRand.getBold_r();
    stopwatch.stop();
    stats.voteEncodingTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    List<ObliviousTransferResponse> obliviousTransferResponses = sentBallotAndQuery(
            ballotQueryAndRand.getAlpha());

    stopwatch.reset().start();
    pointMatrix = computePointMatrix(selections, obliviousTransferResponses);
    List<String> returnCodes = voteCastingClientAlgorithms.getReturnCodes(selections, pointMatrix);
    stopwatch.stop();
    stats.verificationCodesComputationTime = stopwatch.elapsed(TimeUnit.MILLISECONDS);

    return returnCodes;
}

From source file:com.example.postgres.PostgresSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id SERIAL NOT NULL, "
            + "user_ip VARCHAR(46) NOT NULL, ts timestamp NOT NULL, " + "PRIMARY KEY (visit_id) );";
    final String createVisitSql = "INSERT INTO visits (user_ip, ts) VALUES (?, ?);";
    final String selectSql = "SELECT user_ip, ts FROM visits ORDER BY ts DESC " + "LIMIT 10;";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }/*from ww w  .  j av a2  s.  co  m*/

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("ts");
                out.println("Time: " + timeStamp + " Addr: " + savedIp);
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:com.example.cloudsql.CloudSqlServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
    final String createTableSql = "CREATE TABLE IF NOT EXISTS visits ( visit_id INT NOT NULL "
            + "AUTO_INCREMENT, user_ip VARCHAR(46) NOT NULL, timestamp DATETIME NOT NULL, "
            + "PRIMARY KEY (visit_id) )";
    final String createVisitSql = "INSERT INTO visits (user_ip, timestamp) VALUES (?, ?)";
    final String selectSql = "SELECT user_ip, timestamp FROM visits ORDER BY timestamp DESC " + "LIMIT 10";

    String path = req.getRequestURI();
    if (path.startsWith("/favicon.ico")) {
        return; // ignore the request for favicon.ico
    }// w w w . j  a  v  a  2s  .c  o m

    PrintWriter out = resp.getWriter();
    resp.setContentType("text/plain");

    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
        // nest indexOf calls to find the second occurrence of a character in a string
        // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
        userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
        userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Stopwatch stopwatch = Stopwatch.createStarted();
    try (PreparedStatement statementCreateVisit = conn.prepareStatement(createVisitSql)) {
        conn.createStatement().executeUpdate(createTableSql);
        statementCreateVisit.setString(1, userIp);
        statementCreateVisit.setTimestamp(2, new Timestamp(new Date().getTime()));
        statementCreateVisit.executeUpdate();

        try (ResultSet rs = conn.prepareStatement(selectSql).executeQuery()) {
            stopwatch.stop();
            out.print("Last 10 visits:\n");
            while (rs.next()) {
                String savedIp = rs.getString("user_ip");
                String timeStamp = rs.getString("timestamp");
                out.print("Time: " + timeStamp + " Addr: " + savedIp + "\n");
            }
            out.println("Elapsed: " + stopwatch.elapsed(TimeUnit.MILLISECONDS));
        }
    } catch (SQLException e) {
        throw new ServletException("SQL error", e);
    }
}

From source file:org.apache.jackrabbit.oak.scalability.suites.ScalabilityAbstractSuite.java

/**
 * Runs the iteration of the benchmarks added.
 * /*from w  w  w. j  av a 2  s  . c o  m*/
 * @param context the execution context
 * @throws Exception 
 */
private void runIteration(ExecutionContext context) throws Exception {
    Preconditions.checkArgument(benchmarks != null && !benchmarks.isEmpty(), "No Benchmarks configured");

    for (String key : benchmarks.keySet()) {
        ScalabilityBenchmark benchmark = benchmarks.get(key);
        if (result.getBenchmarkStatistics(benchmark) == null) {
            result.addBenchmarkStatistics(benchmark, new SynchronizedDescriptiveStatistics());
        }

        Stopwatch watch = Stopwatch.createStarted();

        executeBenchmark(benchmark, context);

        watch.stop();
        result.getBenchmarkStatistics(benchmark).addValue(watch.elapsed(TimeUnit.MILLISECONDS));

        if (LOG.isDebugEnabled()) {
            LOG.debug("Execution time for " + benchmark + "-" + watch.elapsed(TimeUnit.MILLISECONDS));
        }
    }
}

From source file:org.locationtech.geogig.remote.HttpRemoteRepo.java

/**
 * Retrieve objects from the remote repository, and update have/want lists accordingly.
 * Specifically, any retrieved commits are removed from the want list and added to the have
 * list, and any parents of those commits are removed from the have list (it only represents the
 * most recent common commits.) Retrieved objects are added to the local repository, and the
 * want/have lists are updated in-place.
 * /*w ww.  j  a  v  a2  s. co m*/
 * @param want a list of ObjectIds that need to be fetched
 * @param have a list of ObjectIds that are in common with the remote repository
 * @param progress
 */
private void fetchMoreData(final List<ObjectId> want, final Set<ObjectId> have,
        final ProgressListener progress) {
    final JsonObject message = createFetchMessage(want, have);
    final URL resourceURL;
    try {
        resourceURL = new URL(repositoryURL.toString() + "/repo/batchobjects");
    } catch (MalformedURLException e) {
        throw Throwables.propagate(e);
    }

    final HttpURLConnection connection;
    try {
        final Gson gson = new Gson();
        OutputStream out;
        final Writer writer;
        connection = (HttpURLConnection) resourceURL.openConnection();
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        out = connection.getOutputStream();
        writer = new OutputStreamWriter(out);
        gson.toJson(message, writer);
        writer.flush();
        out.flush();
    } catch (IOException e) {
        throw Throwables.propagate(e);
    }

    final HttpUtils.ReportingInputStream in = HttpUtils.getResponseStream(connection);

    BinaryPackedObjects unpacker = new BinaryPackedObjects(localRepository.objectDatabase());
    BinaryPackedObjects.Callback callback = new BinaryPackedObjects.Callback() {
        @Override
        public void callback(Supplier<RevObject> supplier) {
            RevObject object = supplier.get();
            progress.setProgress(progress.getProgress() + 1);
            if (object instanceof RevCommit) {
                RevCommit commit = (RevCommit) object;
                want.remove(commit.getId());
                have.removeAll(commit.getParentIds());
                have.add(commit.getId());
            } else if (object instanceof RevTag) {
                RevTag tag = (RevTag) object;
                want.remove(tag.getId());
                have.remove(tag.getCommitId());
                have.add(tag.getId());
            }
        }
    };

    Stopwatch sw = Stopwatch.createStarted();
    IngestResults ingestResults = unpacker.ingest(in, callback);
    sw.stop();

    String msg = String.format(
            "Processed %,d objects. Inserted: %,d. Existing: %,d. Time: %s. Compressed size: %,d bytes. Uncompressed size: %,d bytes.",
            ingestResults.total(), ingestResults.getInserted(), ingestResults.getExisting(), sw,
            in.compressedSize(), in.unCompressedSize());
    LOGGER.info(msg);
    progress.setDescription(msg);
}

From source file:com.microsoft.azure.servicebus.samples.prefetch.Prefetch.java

long sendAndReceiveMessages(IMessageSender sender, IMessageReceiver receiver, int messageCount)
        throws Exception {
    // Now we can start sending messages.
    Random rnd = new Random();
    byte[] mockPayload = new byte[100]; // 100 random-byte payload

    rnd.nextBytes(mockPayload);//from  www . ja v a  2s  . c om

    System.out.printf("\nSending %d messages to the queue\n", messageCount);
    ArrayList<CompletableFuture<Void>> sendOps = new ArrayList<>();
    for (int i = 0; i < messageCount; i++) {
        IMessage message = new Message(mockPayload);
        message.setTimeToLive(Duration.ofMinutes(5));
        sendOps.add(sender.sendAsync(message));
    }
    CompletableFuture.allOf(sendOps.toArray(new CompletableFuture<?>[sendOps.size()])).join();

    System.out.printf("Send completed\n");

    // Receive the messages
    System.out.printf("Receiving messages...\n");

    // Start stopwatch
    Stopwatch stopWatch = Stopwatch.createStarted();

    IMessage receivedMessage = receiver.receive(Duration.ofSeconds(5));
    while (receivedMessage != null) {
        // here's where you'd do any work

        // complete (round trips)
        receiver.complete(receivedMessage.getLockToken());

        if (--messageCount <= 0)
            break;

        // now get the next message
        receivedMessage = receiver.receive(Duration.ofSeconds(5));
    }
    // Stop the stopwatch
    stopWatch.stop();

    System.out.printf("Receive completed\n");

    long timeTaken = stopWatch.elapsed(TimeUnit.MILLISECONDS);
    System.out.printf("Time to receive and complete all messages = %d milliseconds\n", timeTaken);

    return timeTaken;
}

From source file:org.locationtech.geogig.remote.http.HttpRemoteRepo.java

/**
 * Retrieve objects from the remote repository, and update have/want lists accordingly.
 * Specifically, any retrieved commits are removed from the want list and added to the have
 * list, and any parents of those commits are removed from the have list (it only represents the
 * most recent common commits.) Retrieved objects are added to the local repository, and the
 * want/have lists are updated in-place.
 * /*from w w w . java  2  s  .  c o  m*/
 * @param want a list of ObjectIds that need to be fetched
 * @param have a list of ObjectIds that are in common with the remote repository
 * @param progress
 */
private void fetchMoreData(final Repository local, final List<ObjectId> want, final Set<ObjectId> have,
        final ProgressListener progress) {
    final JsonObject message = createFetchMessage(want, have);
    final URL resourceURL;
    try {
        resourceURL = new URL(repositoryURL.toString() + "/repo/batchobjects");
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

    final HttpURLConnection connection;
    try {
        final Gson gson = new Gson();
        OutputStream out;
        final Writer writer;
        connection = (HttpURLConnection) resourceURL.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        out = connection.getOutputStream();
        writer = new OutputStreamWriter(out);
        gson.toJson(message, writer);
        writer.flush();
        out.flush();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    final HttpUtils.ReportingInputStream in = HttpUtils.getResponseStream(connection);

    BinaryPackedObjects unpacker = new BinaryPackedObjects(local.objectDatabase());
    BinaryPackedObjects.Callback callback = new BinaryPackedObjects.Callback() {
        @Override
        public void callback(Supplier<RevObject> supplier) {
            RevObject object = supplier.get();
            progress.setProgress(progress.getProgress() + 1);
            if (object instanceof RevCommit) {
                RevCommit commit = (RevCommit) object;
                want.remove(commit.getId());
                have.removeAll(commit.getParentIds());
                have.add(commit.getId());
            } else if (object instanceof RevTag) {
                RevTag tag = (RevTag) object;
                want.remove(tag.getId());
                have.remove(tag.getCommitId());
                have.add(tag.getId());
            }
        }
    };

    Stopwatch sw = Stopwatch.createStarted();
    IngestResults ingestResults = unpacker.ingest(in, callback);
    sw.stop();

    String msg = String.format(
            "Processed %,d objects. Inserted: %,d. Existing: %,d. Time: %s. Compressed size: %,d bytes. Uncompressed size: %,d bytes.",
            ingestResults.total(), ingestResults.getInserted(), ingestResults.getExisting(), sw,
            in.compressedSize(), in.unCompressedSize());
    LOGGER.info(msg);
    progress.setDescription(msg);
}

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

private void unserializeAndDecryptEncryptedBallots(File encryptedBallotsFile,
        BallotCipherService ballotCipherService) throws ProcessInterruptedException {
    // Using a task here, so as to perform decryption without blocking the UI.
    final long maxObjects;
    try {/*from  ww w.  j  a  v  a  2s .c om*/
        maxObjects = propertyConfigurationService.getConfigValueAsLong(STREAM_MAX_OBJECTS);
    } catch (PropertyConfigurationException e) {
        throw new ProcessInterruptedException(
                String.format(resources.getString("ballot_decryption.undefined_property"), STREAM_MAX_OBJECTS),
                e);
    }

    final long maxBytes;
    try {
        maxBytes = propertyConfigurationService.getConfigValueAsLong(COMMON_CRYPTO_STREAM_MAX_BYTES);
    } catch (PropertyConfigurationException e) {
        throw new ProcessInterruptedException(
                String.format(resources.getString("ballot_decryption.undefined_property"),
                        COMMON_CRYPTO_STREAM_MAX_BYTES),
                e);
    }

    Task<List<EncryptedBallotAndWrappedKey>> unserializeEncryptedBallotsTask = new UnserializeEncryptedBallotsTask(
            encryptedBallotsFile, maxObjects, maxBytes);

    Stopwatch fileOpening = Stopwatch.createStarted();

    // Handle success
    unserializeEncryptedBallotsTask.setOnSucceeded(event -> {
        List<EncryptedBallotAndWrappedKey> encryptedBallots = unserializeEncryptedBallotsTask.getValue();
        fileOpening.stop();
        consoleOutputController.logOnScreen(String.format(
                resources.getString("ballot_decryption.enc_ballots_loaded"), formatElapsedTime(fileOpening)));
        consoleOutputController.logOnScreen(String
                .format(resources.getString("ballot_decryption.number_of_ballots"), encryptedBallots.size()));
        consoleOutputController.setStepCount(encryptedBallots.size() / DecryptionService.STEP_SIZE);

        // Once the ballots are deserialized, they can be decrypted
        performBallotDecryption(ballotCipherService, encryptedBallots);
    });

    // Handle failure
    unserializeEncryptedBallotsTask.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(unserializeEncryptedBallotsTask);
}

From source file:org.apache.bookkeeper.replication.ReplicationWorker.java

/**
 * Replicates the under replicated fragments from failed bookie ledger to
 * targetBookie// w ww  .j  a  v a 2  s .  c  om
 */
private void rereplicate() throws InterruptedException, BKException, UnavailableException {
    long ledgerIdToReplicate = underreplicationManager.getLedgerToRereplicate();

    Stopwatch stopwatch = new Stopwatch().start();
    boolean success = false;
    try {
        success = rereplicate(ledgerIdToReplicate);
    } finally {
        long latencyMillis = stopwatch.stop().elapsedMillis();
        if (success) {
            rereplicateOpStats.registerSuccessfulEvent(latencyMillis, TimeUnit.MILLISECONDS);
        } else {
            rereplicateOpStats.registerFailedEvent(latencyMillis, TimeUnit.MILLISECONDS);
        }
    }
}