Example usage for java.time Duration ofSeconds

List of usage examples for java.time Duration ofSeconds

Introduction

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

Prototype

public static Duration ofSeconds(long seconds) 

Source Link

Document

Obtains a Duration representing a number of seconds.

Usage

From source file:com.offbynull.voip.kademlia.AdvertiseSubcoroutine.java

@Override
public Void run(Continuation cnt) throws Exception {
    Context ctx = (Context) cnt.getContext();

    while (true) {
        // Sleep for a bit
        new SleepSubcoroutine.Builder().sourceAddress(subAddress).duration(Duration.ofSeconds(5L))
                .timerAddress(timerAddress).build().run(cnt);

        List<Node> closestNodes = new FindSubcoroutine(subAddress.appendSuffix("find"), state, baseId, 20, true,
                true).run(cnt);/*from   w  w w  .  j  a  v  a 2  s.c o  m*/
        for (Node node : closestNodes) {
            RouterChangeSet changeSet = router.touch(ctx.getTime(), node); // since we set ignoreSelf to true, node will never == baseId
            graphHelper.applyRouterChanges(ctx, changeSet);
        }
    }
}

From source file:no.digipost.api.useragreements.client.response.ResponseUtilsTest.java

@Test
public void parsesSecondsFromRetryAfterHeaderIn429Response() {
    HttpResponse tooManyRequestsErrorResponse = tooManyRequestsResponseWithRetryAfter("10");
    try {//ww w.j a v  a 2 s.  c o m
        ResponseUtils.mapOkResponseOrThrowException(tooManyRequestsErrorResponse, Function.identity());
        fail("should have thrown exception");
    } catch (TooManyRequestsException tooManyRequests) {
        assertThat(tooManyRequests, where(TooManyRequestsException::getDelayUntilNextAllowedRequest,
                contains(Duration.ofSeconds(10))));
        assertThat(tooManyRequests, where(Throwable::getSuppressed, emptyArray()));
    }
}

From source file:com.microsoft.azure.servicebus.samples.managingentity.ManagingEntity.java

private void createQueue(String queueName) {

    // Name of the queue is a required parameter.
    // All other queue properties have defaults, and hence optional.
    QueueDescription queueDescription = new QueueDescription(queueName);

    // The duration of a peek lock; that is, the amount of time that a message is locked from other receivers.
    queueDescription.setLockDuration(Duration.ofSeconds(45));

    // Size of the Queue. For non-partitioned entity, this would be the size of the queue.
    // For partitioned entity, this would be the size of each partition.
    queueDescription.setMaxSizeInMB(2048);

    // This value indicates if the queue requires guard against duplicate messages.
    // Find out more in DuplicateDetection sample.
    queueDescription.setRequiresDuplicateDetection(false);

    // Since RequiresDuplicateDetection is false, the following need not be specified and will be ignored.
    // queueDescription.setDuplicationDetectionHistoryTimeWindow(Duration.ofMinutes(2));

    // This indicates whether the queue supports the concept of session.
    queueDescription.setRequiresSession(false);

    // The default time to live value for the messages.
    // Find out more in "TimeToLive" sample.
    queueDescription.setDefaultMessageTimeToLive(Duration.ofDays(7));

    // Duration of idle interval after which the queue is automatically deleted.
    queueDescription.setAutoDeleteOnIdle(ManagementClientConstants.MAX_DURATION);

    // Decides whether an expired message due to TTL should be dead-lettered.
    // Find out more in "TimeToLive" sample.
    queueDescription.setEnableDeadLetteringOnMessageExpiration(false);

    // The maximum delivery count of a message before it is dead-lettered.
    // Find out more in "DeadletterQueue" sample.
    queueDescription.setMaxDeliveryCount(8);

    // Creating only one partition.
    // Find out more in PartitionedQueues sample.
    queueDescription.setEnablePartitioning(false);

    try {//w  w w.  j a  v  a  2 s  .co  m
        this.managementClient.createQueueAsync(queueDescription).get();
    } catch (InterruptedException e) {
        System.out.println("Encountered exception while creating Queue - \n" + e.toString());
    } catch (ExecutionException e) {
        if (e.getCause() instanceof ServiceBusException) {
            System.out.println("Encountered ServiceBusException while creating Queue - \n" + e.toString());
        }
        System.out.println("Encountered exception while creating Queue - \n" + e.toString());
    }
}

From source file:com.ibasco.agql.protocols.valve.source.query.pojos.SourcePlayer.java

@Override
public String toString() {
    return new ToStringBuilder(this, ToStringStyle.NO_CLASS_NAME_STYLE).append("index", getIndex())
            .append("name", getName()).append("score", getScore())
            .append("duration (mins)", Duration.ofSeconds((long) getDuration()).toMinutes()).toString();
}

From source file:de.bytefish.fcmjava.client.http.apache.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }//from www  .ja  v a 2s.  c om

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}

From source file:org.springframework.boot.webservices.client.HttpWebServiceMessageSenderBuilderTests.java

@Test
public void buildUsesHttpComponentsByDefault() {
    ClientHttpRequestMessageSender messageSender = build(new HttpWebServiceMessageSenderBuilder()
            .setConnectTimeout(Duration.ofSeconds(5)).setReadTimeout(Duration.ofSeconds(2)));
    ClientHttpRequestFactory requestFactory = messageSender.getRequestFactory();
    assertThat(requestFactory).isInstanceOf(HttpComponentsClientHttpRequestFactory.class);
    RequestConfig requestConfig = (RequestConfig) ReflectionTestUtils.getField(requestFactory, "requestConfig");
    assertThat(requestConfig).isNotNull();
    assertThat(requestConfig.getConnectTimeout()).isEqualTo(5000);
    assertThat(requestConfig.getSocketTimeout()).isEqualTo(2000);
}

From source file:de.bytefish.fcmjava.client.interceptors.response.utils.RetryHeaderUtils.java

private static boolean tryGetFromDate(String dateAsString, OutParameter<Duration> result) {

    // Try to convert the String to a RFC1123-compliant Zoned DateTime
    OutParameter<ZonedDateTime> resultDate = new OutParameter<ZonedDateTime>();

    if (!tryToConvertToDate(dateAsString, resultDate)) {
        return false;
    }/*from  w ww  . j  a  va  2  s  .  c  o  m*/

    // Get the UTC Now DateTime and the Retry DateTime in UTC Time Zone:
    ZonedDateTime utcNowDateTime = DateUtils.getUtcNow();
    ZonedDateTime nextRetryDateTime = resultDate.get().withZoneSameInstant(ZoneOffset.UTC);

    // Calculate Duration between both as the Retry Delay:
    Duration durationToNextRetryTime = Duration.between(utcNowDateTime, nextRetryDateTime);

    // Negative Retry Delays should not be allowed:
    if (durationToNextRetryTime.getSeconds() < 0) {
        durationToNextRetryTime = Duration.ofSeconds(0);
    }

    // Set it as Result:
    result.set(durationToNextRetryTime);

    // And return success:
    return true;
}

From source file:JobsBasedMultipart.java

private static void multipartUpload(MantaClient mantaClient) {
    // instantiated with a reference to the class the actually connects to Manta
    JobsMultipartManager multipart = new JobsMultipartManager(mantaClient);

    String uploadObject = "/username/stor/test/file";

    /* I'm using File objects below, but I could be using byte[] arrays,
     * Strings, or InputStreams as well. */
    File part1file = new File("part-1.data");
    File part2file = new File("part-2.data");
    File part3file = new File("part-3.data");

    // We can set any metadata for the final object
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-test-metadata", "any value");

    // We can set any header for the final object
    MantaHttpHeaders headers = new MantaHttpHeaders();
    headers.setContentType("text/plain");

    // We catch network errors and handle them here
    try {/* ww  w.  j a v a  2  s  .c  o  m*/
        // We get a response object
        JobsMultipartUpload upload = multipart.initiateUpload(uploadObject);

        // It contains a UUID transaction id
        UUID id = upload.getId();
        // It also contains the path of the final object
        String uploadPath = upload.getPath();

        // Everywhere below that we specified "upload" we could also just
        // use the upload transaction id

        List<MantaMultipartUploadPart> parts = new ArrayList<>();

        // We can add the parts in any order
        MantaMultipartUploadPart part2 = multipart.uploadPart(upload, 2, part2file);
        // Each put of a part is a synchronous operation
        MantaMultipartUploadPart part1 = multipart.uploadPart(upload, 1, part1file);
        // Although in a later version we could make an async option
        MantaMultipartUploadPart part3 = multipart.uploadPart(upload, 3, part3file);

        parts.add(part1);
        parts.add(part3);
        parts.add(part2);

        // If we want to give up now, we could always abort
        // multipart.abort(upload);

        // We've uploaded all of the parts, now lets join them
        multipart.complete(upload, parts.stream());

        // If we want to pause execution until it is committed
        int timesToPoll = 10;
        multipart.waitForCompletion(upload, Duration.ofSeconds(5), timesToPoll, uuid -> {
            throw new RuntimeException("Multipart completion timed out");
        });

    } catch (MantaClientHttpResponseException e) {
        // This catch block is for when we actually have a response code from Manta

        // We can handle specific HTTP responses here
        if (e.getStatusCode() == 503) {
            System.out.println("Manta is unavailable. Please try again");
            return;
        }

        // We could rethrow as a more detailed exception as below
        throw new RuntimeException(e);
    } catch (IOException e) {
        // This catch block is for general network failures
        // Note: MantaClientHttpResponseException inherits from IOException
        // so if it is not explicitly caught, it would go to this block

        ContextedRuntimeException exception = new ContextedRuntimeException(
                "A network error occurred when doing a multipart upload to"
                        + "Manta. See context for details.");
        // We should all of the diagnostic context that we need
        exception.setContextValue("parts", "[part-1.data, part-2.data, part-3.data]");

        // We rethrow the exception with additional detail
        throw exception;
    }
}

From source file:com.microsoft.azure.servicebus.samples.autoforward.AutoForward.java

IMessage createMessage(String label) {
    // Create a Service Bus message.
    IMessage msg = new Message(("This is the body of message \"" + label + "\".").getBytes(UTF_8));
    msg.setProperties(new HashMap<String, String>() {
        {//from  ww  w  .j a  v  a2  s .  c om
            put("Priority", "1");
            put("Importance", "High");
        }
    });
    msg.setLabel(label);
    msg.setTimeToLive(Duration.ofSeconds(90));
    return msg;
}

From source file:com.orange.cloud.servicebroker.filter.securitygroups.filter.DeleteSecurityGroup.java

@Override
public void run(DeleteServiceInstanceBindingRequest request, Void response) {
    securityGroupId(request.getBindingId())
            .then(securityGroupId -> cloudFoundryClient.securityGroups()
                    .delete(DeleteSecurityGroupRequest.builder().securityGroupId(securityGroupId).build()))
            .doOnError(resp -> log.error("Fail to delete security group {}", request.getBindingId()))
            .timeout(Duration.ofSeconds(60))
            .subscribe(resp -> log.debug("Security group {} deleted", request.getBindingId()));

}