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.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);/*w ww  .  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:no.digipost.api.useragreements.client.response.ResponseUtilsTest.java

@Test
public void parsesDateFromRetryAfterHeader() {
    Clock clock = Clock.fixed(Instant.now().truncatedTo(SECONDS), ZoneOffset.UTC);
    HttpResponse tooManyRequestsErrorResponse = tooManyRequestsResponseWithRetryAfter(
            RFC_1123_DATE_TIME.format(ZonedDateTime.now(clock).plusSeconds(42)));

    Optional<Duration> parsedDuration = ResponseUtils
            .parseDelayDurationOfRetryAfterHeader(tooManyRequestsErrorResponse, clock);
    assertThat(parsedDuration, contains(Duration.ofSeconds(42)));
}

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

@Override
public Void run(Continuation cnt) throws Exception {
    int idBitLength = baseId.getBitLength();
    int idByteLength = idBitLength / 8 + (idBitLength % 8 == 0 ? 0 : 1);
    byte[] idBytes = new byte[idByteLength];

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

        // Get closest nodes (from the router) to some random id
        secureRandom.nextBytes(idBytes);
        Id randomId = Id.create(idBytes, idBitLength);
        List<Node> nodesToPing = router.find(randomId, 5, true); // include stale nodes, because it may have come back up again / we may
                                                                 // have come back up again and we want to unstale it if we can contact
                                                                 // it

        // Ping them
        Address sourceAddress = subAddress.appendSuffix("refresh" + idGenerator.generate());
        MultiRequestSubcoroutine.Builder<PingResponse> multiReqBuilder = new MultiRequestSubcoroutine.Builder<PingResponse>()
                .sourceAddress(sourceAddress).timerAddress(timerAddress).request(new PingRequest(baseId))
                .addExpectedResponseType(PingResponse.class).attemptInterval(Duration.ofSeconds(2L))
                .maxAttempts(5);//from w w  w . j a  va 2  s .  com

        Map<String, Node> suffixToNode = new HashMap<>();
        for (Node node : nodesToPing) {
            String link = node.getLink();
            Address dstAddress = addressTransformer.toAddress(link);

            String suffix = idGenerator.generate();
            suffixToNode.put(suffix, node);

            multiReqBuilder.addDestinationAddress(suffix, dstAddress);
        }

        List<Response<PingResponse>> responses = multiReqBuilder.build().run(cnt);

        // Remove nodes that answered from suffixToNode
        for (Response<PingResponse> response : responses) {
            String suffix = response.getUniqueSourceAddressSuffix();
            suffixToNode.remove(suffix);
        }

        // Mark nodes that didn't answer as stale
        for (Node unresponsiveNode : suffixToNode.values()) {
            // DONT BOTHER WITH TRYING TO CALCULATE LOCKING/UNLOCKING LOGIC. THE LOGIC WILL BECOME EXTREMELY CONVOLUTED. THE QUERY
            // DID 5 REQUEST. IF NO ANSWER WAS GIVEN IN THE ALLOTED TIME, THEN MARK AS STALE!
            try {
                router.stale(unresponsiveNode);
            } catch (NodeNotFoundException nnfe) { // may have been removed (already marked as stale) / may not be in routing tree
                // Do nothing
            }
        }
    }
}

From source file:com.qwazr.externalizor.SimpleTime.java

public SimpleTime() {

    calNullValue = null;/* www  . j  ava  2  s  .  co m*/
    calValue = Calendar.getInstance();
    calValue.setTimeInMillis(RandomUtils.nextLong());
    calArray = new Calendar[] { calNullValue, calValue };
    calList = new ArrayList(Arrays.asList(calValue, calNullValue));

    dateNullValue = null;
    dateValue = new Date(RandomUtils.nextLong());
    dateArray = new Date[] { dateNullValue, dateValue };
    dateList = new ArrayList(Arrays.asList(dateValue, dateNullValue));

    durationNullValue = null;
    durationValue = Duration.ofSeconds(RandomUtils.nextLong());
    durationArray = new Duration[] { durationNullValue, durationValue };
    durationList = new ArrayList(Arrays.asList(durationValue, durationNullValue));

    instantNullValue = null;
    instantValue = Instant.ofEpochSecond(RandomUtils.nextLong(0, Instant.MAX.getEpochSecond()));
    instantArray = new Instant[] { instantNullValue, instantValue };
    instantList = new ArrayList(Arrays.asList(instantValue, instantNullValue));

    localTimeNullValue = null;
    localTimeValue = LocalTime.of(RandomUtils.nextInt(0, 24), RandomUtils.nextInt(0, 60),
            RandomUtils.nextInt(0, 60));
    localTimeArray = new LocalTime[] { localTimeNullValue, localTimeValue };
    localTimeList = new ArrayList(Arrays.asList(localTimeValue, localTimeNullValue));

    localDateNullValue = null;
    localDateValue = LocalDate.of(RandomUtils.nextInt(2000, 3000), RandomUtils.nextInt(1, 13),
            RandomUtils.nextInt(1, 29));
    localDateArray = new LocalDate[] { localDateNullValue, localDateValue };
    localDateList = new ArrayList(Arrays.asList(localDateValue, localDateNullValue));

    localDateTimeNullValue = null;
    localDateTimeValue = LocalDateTime.of(
            LocalDate.of(RandomUtils.nextInt(2000, 3000), RandomUtils.nextInt(1, 13),
                    RandomUtils.nextInt(1, 29)),
            LocalTime.of(RandomUtils.nextInt(0, 24), RandomUtils.nextInt(0, 60), RandomUtils.nextInt(0, 60)));
    localDateTimeArray = new LocalDateTime[] { localDateTimeNullValue, localDateTimeValue };
    localDateTimeList = new ArrayList(Arrays.asList(localDateTimeValue, localDateTimeNullValue));

    monthDayNullValue = null;
    monthDayValue = MonthDay.of(RandomUtils.nextInt(1, 13), RandomUtils.nextInt(1, 29));
    monthDayArray = new MonthDay[] { monthDayNullValue, monthDayValue };
    monthDayList = new ArrayList(Arrays.asList(monthDayValue, monthDayNullValue));

    periodNullValue = null;
    periodValue = Period.of(RandomUtils.nextInt(0, Year.MAX_VALUE), RandomUtils.nextInt(1, 13),
            RandomUtils.nextInt(1, 29));
    periodArray = new Period[] { periodNullValue, periodValue };
    periodList = new ArrayList(Arrays.asList(periodValue, periodNullValue));

    yearNullValue = null;
    yearValue = Year.of(RandomUtils.nextInt(0, Year.MAX_VALUE));
    yearArray = new Year[] { yearNullValue, yearValue };
    yearList = new ArrayList(Arrays.asList(yearValue, yearNullValue));

}

From source file:io.github.resilience4j.ratelimiter.RateLimiterAutoConfigurationTest.java

/**
 * The test verifies that a RateLimiter instance is created and configured properly when the DummyService is invoked and
 * that the RateLimiter records successful and failed calls.
 *//* w ww  .ja v a2s.c o m*/
@Test
public void testRateLimiterAutoConfiguration() throws IOException {
    assertThat(rateLimiterRegistry).isNotNull();
    assertThat(rateLimiterProperties).isNotNull();

    RateLimiter rateLimiter = rateLimiterRegistry.rateLimiter(DummyService.BACKEND);
    assertThat(rateLimiter).isNotNull();
    rateLimiter.getPermission(Duration.ZERO);
    await().atMost(2, TimeUnit.SECONDS).until(() -> rateLimiter.getMetrics().getAvailablePermissions() == 10);

    try {
        dummyService.doSomething(true);
    } catch (IOException ex) {
        // Do nothing.
    }
    dummyService.doSomething(false);

    assertThat(rateLimiter.getMetrics().getAvailablePermissions()).isEqualTo(8);
    assertThat(rateLimiter.getMetrics().getNumberOfWaitingThreads()).isEqualTo(0);

    assertThat(rateLimiter.getRateLimiterConfig().getLimitForPeriod()).isEqualTo(10);
    assertThat(rateLimiter.getRateLimiterConfig().getLimitRefreshPeriod()).isEqualTo(Duration.ofSeconds(1));
    assertThat(rateLimiter.getRateLimiterConfig().getTimeoutDuration()).isEqualTo(Duration.ofSeconds(0));

    // Test Actuator endpoints

    ResponseEntity<RateLimiterEndpointResponse> rateLimiterList = restTemplate
            .getForEntity("/actuator/ratelimiters", RateLimiterEndpointResponse.class);

    assertThat(rateLimiterList.getBody().getRateLimitersNames()).hasSize(2).containsExactly("backendA",
            "backendB");

    try {
        for (int i = 0; i < 11; i++) {
            dummyService.doSomething(false);
        }
    } catch (RequestNotPermitted e) {
        // Do nothing
    }

    ResponseEntity<RateLimiterEventsEndpointResponse> rateLimiterEventList = restTemplate
            .getForEntity("/actuator/ratelimiter-events", RateLimiterEventsEndpointResponse.class);

    List<RateLimiterEventDTO> eventsList = rateLimiterEventList.getBody().getEventsList();
    assertThat(eventsList).isNotEmpty();
    RateLimiterEventDTO lastEvent = eventsList.get(eventsList.size() - 1);
    assertThat(lastEvent.getRateLimiterEventType()).isEqualTo(RateLimiterEvent.Type.FAILED_ACQUIRE);

    await().atMost(2, TimeUnit.SECONDS).until(() -> rateLimiter.getMetrics().getAvailablePermissions() == 10);

    assertThat(rateLimiterAspect.getOrder()).isEqualTo(401);
}

From source file:io.pravega.test.system.framework.RemoteSequential.java

private CompletableFuture<Void> waitForJobCompletion(final String jobId) {
    return FutureHelpers.loop(() -> isTestRunning(jobId),
            () -> FutureHelpers.delayedFuture(Duration.ofSeconds(3), executorService), executorService);
}

From source file:com.microsoft.azure.servicebus.samples.timetolive.TimeToLive.java

CompletableFuture<Void> sendMessagesAsync(IMessageSender sendClient) {
    List<HashMap<String, String>> data = GSON.fromJson("[" + "{'name' = 'Einstein', 'firstName' = 'Albert'},"
            + "{'name' = 'Heisenberg', 'firstName' = 'Werner'}," + "{'name' = 'Curie', 'firstName' = 'Marie'},"
            + "{'name' = 'Hawking', 'firstName' = 'Steven'}," + "{'name' = 'Newton', 'firstName' = 'Isaac'},"
            + "{'name' = 'Bohr', 'firstName' = 'Niels'}," + "{'name' = 'Faraday', 'firstName' = 'Michael'},"
            + "{'name' = 'Galilei', 'firstName' = 'Galileo'},"
            + "{'name' = 'Kepler', 'firstName' = 'Johannes'},"
            + "{'name' = 'Kopernikus', 'firstName' = 'Nikolaus'}" + "]",
            new TypeToken<List<HashMap<String, String>>>() {
            }.getType());/* w w  w  . jav a  2  s  .c  o m*/

    List<CompletableFuture> tasks = new ArrayList<>();
    for (int i = 0; i < data.size(); i++) {
        final String messageId = Integer.toString(i);
        Message message = new Message(GSON.toJson(data.get(i), Map.class).getBytes(UTF_8));
        message.setContentType("application/json");
        message.setLabel(i % 2 == 0 ? "Scientist" : "Physicist");
        message.setMessageId(messageId);
        message.setTimeToLive(Duration.ofSeconds(15));
        System.out.printf("Message sending: Id = %s\n", message.getMessageId());
        tasks.add(sendClient.sendAsync(message).thenRunAsync(() -> {
            System.out.printf("\tMessage acknowledged: Id = %s\n", message.getMessageId());
        }));
    }
    return CompletableFuture.allOf(tasks.toArray(new CompletableFuture<?>[tasks.size()]));
}

From source file:com.microsoft.azure.servicebus.samples.receiveloop.ReceiveLoop.java

CompletableFuture receiveMessagesAsync(IMessageReceiver receiver) {

    CompletableFuture currentTask = new CompletableFuture();

    try {//from   w w  w . j a v  a2s .  co m
        CompletableFuture.runAsync(() -> {
            while (!currentTask.isCancelled()) {
                try {
                    IMessage message = receiver.receive(Duration.ofSeconds(60));
                    if (message != null) {
                        // receives message is passed to callback
                        if (message.getLabel() != null && message.getContentType() != null
                                && message.getLabel().contentEquals("Scientist")
                                && message.getContentType().contentEquals("application/json")) {

                            byte[] body = message.getBody();
                            Map scientist = GSON.fromJson(new String(body, UTF_8), Map.class);

                            System.out.printf(
                                    "\n\t\t\t\tMessage received: \n\t\t\t\t\t\tMessageId = %s, \n\t\t\t\t\t\tSequenceNumber = %s, \n\t\t\t\t\t\tEnqueuedTimeUtc = %s,"
                                            + "\n\t\t\t\t\t\tExpiresAtUtc = %s, \n\t\t\t\t\t\tContentType = \"%s\",  \n\t\t\t\t\t\tContent: [ firstName = %s, name = %s ]\n",
                                    message.getMessageId(), message.getSequenceNumber(),
                                    message.getEnqueuedTimeUtc(), message.getExpiresAtUtc(),
                                    message.getContentType(),
                                    scientist != null ? scientist.get("firstName") : "",
                                    scientist != null ? scientist.get("name") : "");
                        }
                        receiver.completeAsync(message.getLockToken());
                    }
                } catch (Exception e) {
                    currentTask.completeExceptionally(e);
                }
            }
            currentTask.complete(null);
        });
        return currentTask;
    } catch (Exception e) {
        currentTask.completeExceptionally(e);
    }
    return currentTask;
}

From source file:io.github.resilience4j.circuitbreaker.CircuitBreakerAutoConfigurationTest.java

/**
 * The test verifies that a CircuitBreaker instance is created and configured properly when the DummyService is invoked and
 * that the CircuitBreaker records successful and failed calls.
 *//*  ww  w. j av  a2 s  .  c  om*/
@Test
public void testCircuitBreakerAutoConfiguration() throws IOException {
    assertThat(circuitBreakerRegistry).isNotNull();
    assertThat(circuitBreakerProperties).isNotNull();

    try {
        dummyService.doSomething(true);
    } catch (IOException ex) {
        // Do nothing. The IOException is recorded by the CircuitBreaker as part of the recordFailurePredicate as a failure.
    }
    // The invocation is recorded by the CircuitBreaker as a success.
    dummyService.doSomething(false);

    CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker(DummyService.BACKEND);
    assertThat(circuitBreaker).isNotNull();

    assertThat(circuitBreaker.getMetrics().getNumberOfBufferedCalls()).isEqualTo(2);
    assertThat(circuitBreaker.getMetrics().getNumberOfSuccessfulCalls()).isEqualTo(1);
    assertThat(circuitBreaker.getMetrics().getNumberOfFailedCalls()).isEqualTo(1);

    // expect circuitbreaker is configured as defined in application.yml
    assertThat(circuitBreaker.getCircuitBreakerConfig().getRingBufferSizeInClosedState()).isEqualTo(6);
    assertThat(circuitBreaker.getCircuitBreakerConfig().getRingBufferSizeInHalfOpenState()).isEqualTo(2);
    assertThat(circuitBreaker.getCircuitBreakerConfig().getFailureRateThreshold()).isEqualTo(70f);
    assertThat(circuitBreaker.getCircuitBreakerConfig().getWaitDurationInOpenState())
            .isEqualByComparingTo(Duration.ofSeconds(5L));

    // expect circuitbreakers actuator endpoint contains both circuitbreakers
    ResponseEntity<CircuitBreakerEndpointResponse> circuitBreakerList = restTemplate
            .getForEntity("/actuator/circuitbreakers", CircuitBreakerEndpointResponse.class);
    assertThat(circuitBreakerList.getBody().getCircuitBreakers()).hasSize(2).containsExactly("backendA",
            "backendB");

    // expect circuitbreaker-event actuator endpoint recorded both events
    ResponseEntity<CircuitBreakerEventsEndpointResponse> circuitBreakerEventList = restTemplate
            .getForEntity("/actuator/circuitbreaker-events", CircuitBreakerEventsEndpointResponse.class);
    assertThat(circuitBreakerEventList.getBody().getCircuitBreakerEvents()).hasSize(2);

    circuitBreakerEventList = restTemplate.getForEntity("/actuator/circuitbreaker-events?name=backendA",
            CircuitBreakerEventsEndpointResponse.class);
    assertThat(circuitBreakerEventList.getBody().getCircuitBreakerEvents()).hasSize(2);

    // expect no health indicator for backendB, as it is disabled via properties
    ResponseEntity<HealthResponse> healthResponse = restTemplate.getForEntity("/actuator/health",
            HealthResponse.class);
    assertThat(healthResponse.getBody().getDetails()).isNotNull();
    assertThat(healthResponse.getBody().getDetails().get("backendACircuitBreaker")).isNotNull();
    assertThat(healthResponse.getBody().getDetails().get("backendBCircuitBreaker")).isNull();

    assertThat(
            circuitBreaker.getCircuitBreakerConfig().getRecordFailurePredicate().test(new RecordedException()))
                    .isTrue();
    assertThat(
            circuitBreaker.getCircuitBreakerConfig().getRecordFailurePredicate().test(new IgnoredException()))
                    .isFalse();

    // Verify that an exception for which recordFailurePredicate returns false and it is not included in
    // recordExceptions evaluates to false.
    assertThat(circuitBreaker.getCircuitBreakerConfig().getRecordFailurePredicate().test(new Exception()))
            .isFalse();

    // expect aspect configured as defined in application.yml
    assertThat(circuitBreakerAspect.getOrder()).isEqualTo(400);
}

From source file:keywhiz.KeywhizConfig.java

public Duration getStatusCacheExpiry() {
    if ((statusCacheExpiry == null) || (statusCacheExpiry.isEmpty())) {
        // Default to 1 second
        return Duration.ofSeconds(1);
    }/*from   www.j  a  v  a  2s . co m*/
    return Duration.parse(statusCacheExpiry);
}