Example usage for java.time Duration between

List of usage examples for java.time Duration between

Introduction

In this page you can find the example usage for java.time Duration between.

Prototype

public static Duration between(Temporal startInclusive, Temporal endExclusive) 

Source Link

Document

Obtains a Duration representing the duration between two temporal objects.

Usage

From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.java

private void canUploadMultipartBinary(final long sizeInMb, final int noOfParts) throws IOException {
    final long size = sizeInMb * 1024L * 1024L;

    File[] parts = new File[noOfParts];

    for (int i = 0; i < noOfParts; i++) {
        parts[i] = createTemporaryDataFile(size, 1);
    }/*from  ww  w . j av  a2  s.c  o  m*/

    final File expectedFile = concatenateFiles(parts);
    final byte[] expectedMd5 = md5(expectedFile);

    final String name = uploadName("can-upload-5mb-multipart-binary");
    final String path = testPathPrefix + name;

    final EncryptedMultipartUpload<JobsMultipartUpload> upload = multipart.initiateUpload(path);

    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        File part = parts[i];
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    Instant start = Instant.now();
    multipart.complete(upload, uploadedParts.stream());
    multipart.getWrapped().waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
        fail("Completion operation didn't succeed within timeout");
        return null;
    });
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);
    assertEquals(status, MantaMultipartStatus.COMPLETED);

    // If we are using encryption the remote md5 is the md5 of the
    // cipher text.  To prove we uploaded the right bytes and can
    // get them back again, we need to download and calculate.

    final byte[] remoteMd5;
    try (MantaObjectInputStream gotObject = mantaClient.getAsInputStream(path)) {
        remoteMd5 = DigestUtils.md5(gotObject);
    }

    if (!Arrays.equals(remoteMd5, expectedMd5)) {
        StringBuilder builder = new StringBuilder();
        builder.append("MD5 values do not match - job id: ").append(multipart.getWrapped().findJob(upload));
        fail(builder.toString());
    }

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Concatenating {} parts took {} seconds", parts.length, totalCompletionTime.toMillis() / 1000);
}

From source file:io.specto.hoverfly.junit.core.Hoverfly.java

/**
 * Blocks until the Hoverfly process becomes healthy, otherwise time out
 *//*from   w  w  w.  j  a  v a  2 s .co m*/
private void waitForHoverflyToBecomeHealthy() {
    final Instant now = Instant.now();

    while (Duration.between(now, Instant.now()).getSeconds() < BOOT_TIMEOUT_SECONDS) {
        if (hoverflyClient.getHealth())
            return;
        try {
            // TODO: prefer executors and tasks to threads
            Thread.sleep(RETRY_BACKOFF_INTERVAL_MS);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    throw new IllegalStateException("Hoverfly has not become healthy in " + BOOT_TIMEOUT_SECONDS + " seconds");
}

From source file:com.coinblesk.server.controller.PaymentController.java

License:asdf

@RequestMapping(value = "/signverify", method = POST, consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE)
@ResponseBody/*from   ww w .j av  a  2 s .c om*/
public SignVerifyTO signVerify(@RequestBody SignVerifyTO request) {
    final String tag = "{signverify}";
    final Instant startTime = Instant.now();
    String clientPubKeyHex = "(UNKNOWN)";

    try {
        final NetworkParameters params = appConfig.getNetworkParameters();
        final Keys keys;
        final ECKey clientKey = ECKey.fromPublicOnly(request.publicKey());
        clientPubKeyHex = clientKey.getPublicKeyAsHex();
        final ECKey serverKey;
        final Transaction transaction;
        final List<TransactionSignature> clientSigs;

        // clear payeeSig since client sig does not cover it
        final TxSig payeeSigInput = request.payeeMessageSig();
        request.payeeMessageSig(null);
        final byte[] payeePubKey = request.payeePublicKey();
        request.payeePublicKey(null);

        // NFC has a hard limit of 245, thus we have no space for the date
        // yet.
        final SignVerifyTO error = ToUtils.checkInput(request, false);
        if (error != null) {
            LOG.info("{} - clientPubKey={} - input error - type={}", tag, clientPubKeyHex, error.type());
            return error;
        }

        LOG.debug("{} - clientPubKey={} - request", tag, clientPubKeyHex);
        keys = keyService.getByClientPublicKey(clientKey.getPubKey());
        if (keys == null || keys.clientPublicKey() == null || keys.serverPrivateKey() == null
                || keys.serverPublicKey() == null) {
            LOG.debug("{} - clientPubKey={} - KEYS_NOT_FOUND", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.KEYS_NOT_FOUND);
        }
        serverKey = ECKey.fromPrivateAndPrecalculatedPublic(keys.serverPrivateKey(), keys.serverPublicKey());

        if (keys.timeLockedAddresses().isEmpty()) {
            LOG.debug("{} - clientPubKey={} - ADDRESS_EMPTY", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.ADDRESS_EMPTY, serverKey);
        }

        /*
         * Got a transaction in the request - sign
         */
        if (request.transaction() != null) {
            transaction = new Transaction(params, request.transaction());
            LOG.debug("{} - clientPubKey={} - transaction from input: \n{}", tag, clientPubKeyHex, transaction);

            List<TransactionOutput> outputsToAdd = new ArrayList<>();
            // if amount to spend && address provided, add corresponding
            // output
            if (request.amountToSpend() > 0 && request.addressTo() != null && !request.addressTo().isEmpty()) {
                TransactionOutput txOut = transaction.addOutput(Coin.valueOf(request.amountToSpend()),
                        Address.fromBase58(params, request.addressTo()));
                outputsToAdd.add(txOut);
                LOG.debug("{} - added output={} to Tx={}", tag, txOut, transaction.getHash());
            }

            // if change amount is provided, we add an output to the most
            // recently created address of the client.
            if (request.amountChange() > 0) {
                Address changeAddress = keys.latestTimeLockedAddresses().toAddress(params);
                Coin changeAmount = Coin.valueOf(request.amountChange());
                TransactionOutput changeOut = transaction.addOutput(changeAmount, changeAddress);
                outputsToAdd.add(changeOut);
                LOG.debug("{} - added change output={} to Tx={}", tag, changeOut, transaction.getHash());
            }

            if (!outputsToAdd.isEmpty()) {
                outputsToAdd = BitcoinUtils.sortOutputs(outputsToAdd);
                transaction.clearOutputs();
                for (TransactionOutput to : outputsToAdd) {
                    transaction.addOutput(to);
                }
            }

        } else {
            LOG.debug("{} - clientPubKey={} - INPUT_MISMATCH", tag, clientPubKeyHex);
            return ToUtils.newInstance(SignVerifyTO.class, Type.INPUT_MISMATCH, serverKey);
        }

        // check signatures
        if (request.signatures() == null || (request.signatures().size() != transaction.getInputs().size())) {
            LOG.debug(
                    "{} - clientPubKey={} - INPUT_MISMATCH - number of signatures ({}) != number of inputs ({})",
                    tag, clientPubKeyHex, request.signatures().size(), transaction.getInputs().size());
            return ToUtils.newInstance(SignVerifyTO.class, Type.INPUT_MISMATCH, serverKey);
        }

        clientSigs = SerializeUtils.deserializeSignatures(request.signatures());
        SignVerifyTO responseTO = txService.signVerifyTransaction(transaction, clientKey, serverKey,
                clientSigs);
        SerializeUtils.signJSON(responseTO, serverKey);

        // if we know the receiver, we create an additional signature with
        // the key of the payee.
        if (maybeAppendPayeeSignature(request, payeePubKey, payeeSigInput, responseTO)) {
            LOG.debug("{} - created additional signature for payee.", tag);
        } else {
            LOG.debug("{} - payee unknown (no additional signature)");
        }

        return responseTO;
    } catch (Exception e) {
        LOG.error("{} - clientPubKey={} - SERVER_ERROR: ", tag, clientPubKeyHex, e);
        return new SignVerifyTO().currentDate(System.currentTimeMillis()).type(Type.SERVER_ERROR)
                .message(e.getMessage());
    } finally {
        LOG.debug("{} - clientPubKey={} - finished in {} ms", tag, clientPubKeyHex,
                Duration.between(startTime, Instant.now()).toMillis());
    }
}

From source file:org.ulyssis.ipp.reader.Reader.java

/**
 * Check whether this tag code has been seen at least config.getMinUpdateInterval()
 * ago. If not, the update should be ignored.
 *///ww  w  .  j a  v a 2s.  c  om
private boolean acceptUpdate(Instant now, TagId tag) {
    lastUpdate = now;
    boolean result = !lastUpdateForTag.containsKey(tag)
            || Duration.ofMillis(Config.getCurrentConfig().getMinUpdateInterval())
                    .minus(Duration.between(lastUpdateForTag.get(tag), now)).isNegative();
    if (result) {
        lastUpdateForTag.put(tag, now);
    }
    return result;
}

From source file:com.drunkendev.io.recurse.tests.RecursionTest.java

/**
 * Times a {@link Runnable} instance.//from  w  ww . ja  v  a2 s. co  m
 *
 * @param   r
 *          {@link Runnable} object to time.
 * @return  {@link Duration} object containing run-time length.
 */
public Duration time(Runnable r) {
    Instant start = Instant.now();
    r.run();
    Duration dur = Duration.between(start, Instant.now());
    System.out.format("Completed in: %s%n", dur.toString());
    return dur;
}

From source file:com.joyent.manta.client.multipart.JobsMultipartManagerIT.java

public void canAbortMultipartBinary() throws IOException {
    final long oneMB = 1024L * 1024L;

    File[] parts = new File[] { createTemporaryDataFile(oneMB, 1), createTemporaryDataFile(oneMB, 1),
            createTemporaryDataFile(oneMB, 1) };

    final String name = uploadName("can-abort-multipart-binary");
    final String path = testPathPrefix + name;

    final JobsMultipartUpload upload = multipart.initiateUpload(path);

    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        File part = parts[i];//from w  w w .  j av a2s  . c  o  m
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    multipart.complete(upload, uploadedParts);

    Instant start = Instant.now();
    multipart.abort(upload);

    boolean caught = false;

    try {
        multipart.waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
            fail("Completion operation didn't succeed within timeout");
            return null;
        });
    } catch (MantaMultipartException e) {
        if (e.getMessage().startsWith("Manta job backing multipart upload was "
                + "aborted. This upload was unable to be completed.")) {
            caught = true;
        }
    }

    assertTrue(caught, "Backing job aborted exception wasn't thrown");
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);
    assertEquals(status, MantaMultipartStatus.ABORTED);

    MantaJob job = multipart.findJob(upload);

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Aborting took {} seconds", totalCompletionTime.toMillis() / 1000);

    if (!job.getCancelled()) {
        fail("Job wasn't cancelled:" + job.toString());
    }

    assertFalse(mantaClient.existsAndIsAccessible(multipart.multipartUploadDir(upload.getId())),
            "Upload directory shouldn't be present after abort");
}

From source file:com.joyent.manta.benchmark.Benchmark.java

/**
 * Measures the total time to get an object from Manta.
 *
 * @param path path of the object to measure
 * @return two durations - full time in the JVM, server time processing
 * @throws IOException thrown when we can't access Manta over the network
 *//* ww w  .j  a  v  a2 s  .  c  o m*/
private static Duration[] measureGet(final String path) throws IOException {
    final Instant start = Instant.now();
    final String serverLatencyString;
    MantaObjectInputStream is = client.getAsInputStream(path);

    try {
        copyToTheEther(is);
        serverLatencyString = is.getHeader("x-response-time").toString();
    } finally {
        IOUtils.closeQuietly(is);
    }
    final Instant stop = Instant.now();

    Duration serverLatency = Duration.ofMillis(Long.parseLong(serverLatencyString));
    Duration fullLatency = Duration.between(start, stop);
    return new Duration[] { fullLatency, serverLatency };
}

From source file:com.joyent.manta.client.multipart.EncryptedJobsMultipartManagerIT.java

public void canAbortMultipartBinary() throws IOException {
    final long oneMB = 1024L * 1024L;

    File[] parts = new File[] { createTemporaryDataFile(oneMB, 1), createTemporaryDataFile(oneMB, 1),
            createTemporaryDataFile(oneMB, 1) };

    final String name = uploadName("can-abort-multipart-binary");
    final String path = testPathPrefix + name;

    final EncryptedMultipartUpload<JobsMultipartUpload> upload = multipart.initiateUpload(path);

    final ArrayList<MantaMultipartUploadTuple> uploadedParts = new ArrayList<>();

    for (int i = 0; i < parts.length; i++) {
        File part = parts[i];//from   w ww  .j a v a2  s .c om
        int partNumber = i + 1;
        MantaMultipartUploadTuple uploaded = multipart.uploadPart(upload, partNumber, part);
        uploadedParts.add(uploaded);
    }

    multipart.validateThatThereAreSequentialPartNumbers(upload);
    multipart.complete(upload, uploadedParts);

    Instant start = Instant.now();
    multipart.abort(upload);

    boolean caught = false;

    try {
        multipart.getWrapped().waitForCompletion(upload, (Function<UUID, Void>) uuid -> {
            fail("Completion operation didn't succeed within timeout");
            return null;
        });
    } catch (MantaMultipartException e) {
        if (e.getMessage().startsWith("Manta job backing multipart upload was "
                + "aborted. This upload was unable to be completed.")) {
            caught = true;
        }
    }

    assertTrue(caught, "Backing job aborted exception wasn't thrown");
    Instant end = Instant.now();

    MantaMultipartStatus status = multipart.getStatus(upload);
    assertEquals(status, MantaMultipartStatus.ABORTED);

    MantaJob job = multipart.getWrapped().findJob(upload);

    Duration totalCompletionTime = Duration.between(start, end);

    LOG.info("Aborting took {} seconds", totalCompletionTime.toMillis() / 1000);

    if (!job.getCancelled()) {
        fail("Job wasn't cancelled:" + job.toString());
    }

    assertFalse(mantaClient.existsAndIsAccessible(multipart.getWrapped().multipartUploadDir(upload.getId())),
            "Upload directory shouldn't be present after abort");
}

From source file:uk.q3c.krail.core.navigate.sitemap.DefaultFileSitemapLoader.java

public int runtime() {
    int diffInNano = Duration.between(startTime, endTime).getNano();
    return diffInNano;
}