java.time.Duration Java Examples

The following examples show how to use java.time.Duration. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FutureTest.java    From future with Apache License 2.0 6 votes vote down vote up
@Test
public void joinConcurrentResults() throws CheckedFutureException {
  List<Promise<Integer>> promises = Stream.generate(() -> Promise.<Integer>apply()).limit(20000).collect(toList());
  ExecutorService ex = Executors.newFixedThreadPool(10);
  try {
    Future<Void> future = Future.join(promises);
    for (Promise<Integer> p : promises) {
      ex.submit(() -> {
        p.setValue(p.hashCode());
      });
    }
    future.get(Duration.ofSeconds(1));
  } finally {
    ex.shutdown();
  }
}
 
Example #2
Source File: FluxSwitchOnFirstTest.java    From reactor-core with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnCorrectContextIfLoosingChain() {
    @SuppressWarnings("unchecked")
    Signal<? extends Long>[] first = new Signal[1];

    Flux<Long> switchTransformed = Flux.<Long>empty()
            .switchOnFirst((f, innerFlux) -> {
                first[0] = f;
                return innerFlux;
            })
            .subscriberContext(Context.of("a", "c"))
            .subscriberContext(Context.of("c", "d"));

    StepVerifier.create(switchTransformed, 0)
            .expectSubscription()
            .thenRequest(1)
            .expectAccessibleContext()
            .contains("a", "c")
            .contains("c", "d")
            .then()
            .expectComplete()
            .verify(Duration.ofSeconds(5));

    Assertions.assertThat(first).containsExactly(Signal.complete(Context.of("a", "c").put("c", "d")));
}
 
Example #3
Source File: ProfileTaskCache.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public ProfileTaskCache(ModuleManager moduleManager, CoreModuleConfig moduleConfig) {
    this.moduleManager = moduleManager;

    long initialSize = moduleConfig.getMaxSizeOfProfileTask() / 10L;
    int initialCapacitySize = (int) (initialSize > Integer.MAX_VALUE ? Integer.MAX_VALUE : initialSize);

    profileTaskDownstreamCache = CacheBuilder.newBuilder()
                                             .initialCapacity(initialCapacitySize)
                                             .maximumSize(moduleConfig.getMaxSizeOfProfileTask())
                                             // remove old profile task data
                                             .expireAfterWrite(Duration.ofMinutes(1))
                                             .build();

    profileTaskIdCache = CacheBuilder.newBuilder()
                                     .initialCapacity(initialCapacitySize)
                                     .maximumSize(moduleConfig.getMaxSizeOfProfileTask())
                                     .build();
}
 
Example #4
Source File: AbstractOffHeapStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testInstallMapping() throws Exception {
  offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)));

  assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).get(), equalTo("one"));

  validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InstallMappingOutcome.PUT));

  timeSource.advanceTime(20);

  try {
    offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("un", timeSource.getTimeMillis(), 15));
    fail("expected AssertionError");
  } catch (AssertionError ae) {
    // expected
  }
}
 
Example #5
Source File: QuoteByDestinationAmountRequestOerCodec.java    From java-ilp-core with Apache License 2.0 6 votes vote down vote up
@Override
public QuoteByDestinationAmountRequest read(CodecContext context, InputStream inputStream)
    throws IOException {

  Objects.requireNonNull(context);
  Objects.requireNonNull(inputStream);

  /* read the Interledger Address. */
  final InterledgerAddress destinationAccount =
      context.read(InterledgerAddress.class, inputStream);

  /* read the destination amount, which is a uint64 */
  final BigInteger destinationAmount = context.read(OerUint64.class, inputStream).getValue();

  /* read the destination hold duration which is a unit32 */
  final long destinationHoldDuration = context.read(OerUint32.class, inputStream).getValue();

  return QuoteByDestinationAmountRequest.Builder.builder().destinationAccount(destinationAccount)
      .destinationAmount(destinationAmount)
      .destinationHoldDuration(Duration.of(destinationHoldDuration, ChronoUnit.MILLIS)).build();
}
 
Example #6
Source File: TokenBucketTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void testBuilder2() {
    final TokenBucket tb1 =
            TokenBucket.builder()
                       .limit(100L, 1000L, Duration.ofSeconds(60L))
                       .build();

    final BandwidthLimit[] limits1 = tb1.limits();
    assertThat(limits1.length).isEqualTo(1);

    assertThat(limits1[0].limit()).isEqualTo(100L);
    assertThat(limits1[0].overdraftLimit()).isEqualTo(1000L);
    assertThat(limits1[0].initialSize()).isEqualTo(0L);
    assertThat(limits1[0].period()).isEqualTo(Duration.ofSeconds(60L));

    assertThat(tb1.lowestLimit()).isSameAs(limits1[0]);
    assertThat(tb1.toSpecString()).isEqualTo("100, 100;window=60;burst=1000");
}
 
Example #7
Source File: DebugServerTransportTest.java    From bazel with Apache License 2.0 6 votes vote down vote up
@Test
public void testConnectAndPostEvent() throws Exception {
  ServerSocket serverSocket = getServerSocket();
  Future<DebugServerTransport> future =
      executor.submit(
          () ->
              DebugServerTransport.createAndWaitForClient(
                  events.reporter(), serverSocket, false));
  MockDebugClient client = new MockDebugClient();
  client.connect(Duration.ofSeconds(10), serverSocket);

  DebugServerTransport serverTransport = future.get(10, TimeUnit.SECONDS);
  assertThat(serverTransport).isNotNull();
  DebugEvent event =
      DebugEvent.newBuilder()
          .setSequenceNumber(10)
          .setContinueExecution(ContinueExecutionResponse.getDefaultInstance())
          .build();
  serverTransport.postEvent(event);

  assertThat(client.readEvents()).containsExactly(event);
  serverTransport.close();
}
 
Example #8
Source File: MockDebugClient.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Connects to the debug server, and starts listening for events. */
void connect(ServerSocket serverSocket, Duration timeout) {
  long startTimeMillis = System.currentTimeMillis();
  IOException exception = null;
  while (System.currentTimeMillis() - startTimeMillis < timeout.toMillis()) {
    try {
      clientSocket = new Socket();
      clientSocket.connect(
          new InetSocketAddress(serverSocket.getInetAddress(), serverSocket.getLocalPort()), 100);
      readTask =
          readTaskExecutor.submit(
              () -> {
                while (true) {
                  eventReceived(DebugEvent.parseDelimitedFrom(clientSocket.getInputStream()));
                }
              });
      return;
    } catch (IOException e) {
      exception = e;
    }
  }
  throw new RuntimeException("Couldn't connect to the debug server", exception);
}
 
Example #9
Source File: CloudFormationStackSetTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void waitForStackStateStatus() throws InterruptedException {
	Mockito.when(client.describeStackSet(new DescribeStackSetRequest()
			.withStackSetName("foo")
	)).thenReturn(new DescribeStackSetResult()
			.withStackSet(new StackSet()
					.withStatus(StackSetStatus.ACTIVE)
			)
	).thenReturn(new DescribeStackSetResult()
			.withStackSet(new StackSet()
					.withStatus(StackSetStatus.DELETED)
			)
	);
	stackSet.waitForStackState(StackSetStatus.DELETED, Duration.ofMillis(5));

	Mockito.verify(client, Mockito.atLeast(2))
			.describeStackSet(Mockito.any(DescribeStackSetRequest.class));
}
 
Example #10
Source File: DefaultManyReconcilerTest.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
private void newReconcilerWithRegistrations(Function<String, List<Mono<Function<String, String>>>> reconcilerActionsProvider,
                                            String... idAndInitialValuePairs) throws InterruptedException {
    Preconditions.checkArgument((idAndInitialValuePairs.length % 2) == 0, "Expected pairs of id/value");

    CloseableReference<Scheduler> reconcilerSchedulerRef = CloseableReference.referenceOf(Schedulers.newSingle("reconciler"), Scheduler::dispose);
    CloseableReference<Scheduler> notificationSchedulerRef = CloseableReference.referenceOf(Schedulers.newSingle("notification"), Scheduler::dispose);

    reconciler = new DefaultManyReconciler<>(
            "junit",
            Duration.ofMillis(1),
            Duration.ofMillis(2),
            reconcilerActionsProvider,
            reconcilerSchedulerRef,
            notificationSchedulerRef,
            titusRuntime
    );

    for (int i = 0; i < idAndInitialValuePairs.length; i += 2) {
        reconciler.add(idAndInitialValuePairs[i], idAndInitialValuePairs[i + 1]).block(TIMEOUT);
    }

    reconciler.changes().subscribe(changesSubscriber = new TitusRxSubscriber<>());
    List<SimpleReconcilerEvent<String>> snapshot = changesSubscriber.takeNext(TIMEOUT);
    assertThat(snapshot).hasSize(idAndInitialValuePairs.length / 2);
}
 
Example #11
Source File: IntegrationTestBase.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
protected static void createKinesisStream() {
    kinesis = KinesisClient.builder().credentialsProvider(CREDENTIALS_PROVIDER_CHAIN).region(Region.US_WEST_2).build();

    kinesis.createStream(CreateStreamRequest.builder().streamName(KINESIS_STREAM_NAME).shardCount(1).build());

    StreamDescription description = kinesis.describeStream(DescribeStreamRequest.builder().streamName(KINESIS_STREAM_NAME).build())
            .streamDescription();
    streamArn = description.streamARN();

    // Wait till stream is active (less than a minute)
    Instant start = Instant.now();
    while (StreamStatus.ACTIVE != description.streamStatus()) {
        if (Duration.between(start, Instant.now()).toMillis() > MAX_WAIT_TIME.toMillis()) {
            throw new RuntimeException("Timed out waiting for stream to become active");
        }
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) {
            // Ignored or expected.
        }

        description = kinesis.describeStream(DescribeStreamRequest.builder().streamName(KINESIS_STREAM_NAME).build())
                .streamDescription();
    }
}
 
Example #12
Source File: SQLiteArtifactCacheTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoStoreMisses() throws Exception {
  artifactCache = cache(Optional.of(0L));
  Timestamp time = Timestamp.from(Instant.now().minus(Duration.ofDays(7)));

  writeFileArtifact(fileA);
  writeFileArtifact(fileB);

  artifactCache.insertContent(contentHashA, BorrowablePath.notBorrowablePath(fileA), time);
  artifactCache.insertContent(contentHashB, BorrowablePath.notBorrowablePath(fileB), time);

  assertThat(artifactCache.directoryFileContentHashes(), Matchers.hasSize(2));

  artifactCache.store(artifactInfoC, BorrowablePath.notBorrowablePath(emptyFile));

  // remove fileA and fileB and stop when size limit reached, leaving fileC
  artifactCache.removeOldContent().get();

  assertThat(artifactCache.directoryFileContentHashes(), Matchers.empty());
  assertThat(artifactCache.inlinedArtifactContentHashes(), Matchers.contains(contentHashC));
}
 
Example #13
Source File: ZestGuidance.java    From JQF with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Creates a new guidance instance.
 *
 * @param testName the name of test to display on the status screen
 * @param duration the amount of time to run fuzzing for, where
 *                 {@code null} indicates unlimited time.
 * @param outputDirectory the directory where fuzzing results will be written
 * @throws IOException if the output directory could not be prepared
 */
public ZestGuidance(String testName, Duration duration, File outputDirectory) throws IOException {
    this.testName = testName;
    this.maxDurationMillis = duration != null ? duration.toMillis() : Long.MAX_VALUE;
    this.outputDirectory = outputDirectory;
    this.blind = Boolean.getBoolean("jqf.ei.TOTALLY_RANDOM");
    this.validityFuzzing = !Boolean.getBoolean("jqf.ei.DISABLE_VALIDITY_FUZZING");
    prepareOutputDirectory();

    // Try to parse the single-run timeout
    String timeout = System.getProperty("jqf.ei.TIMEOUT");
    if (timeout != null && !timeout.isEmpty()) {
        try {
            // Interpret the timeout as milliseconds (just like `afl-fuzz -t`)
            this.singleRunTimeoutMillis = Long.parseLong(timeout);
        } catch (NumberFormatException e1) {
            throw new IllegalArgumentException("Invalid timeout duration: " + timeout);
        }
    }
}
 
Example #14
Source File: SlaIT.java    From digdag with Apache License 2.0 5 votes vote down vote up
@Test
public void verifyAlertIsRetried()
        throws Exception
{
    mockWebServer.setDispatcher(new QueueDispatcher());
    mockWebServer.enqueue(new MockResponse().setResponseCode(500).setBody("FAIL"));
    mockWebServer.enqueue(new MockResponse().setResponseCode(200));
    Id attemptId = pushAndStart("duration_alert_enabled.dig", Duration.ofSeconds(5));
    RecordedRequest recordedRequest1 = mockWebServer.takeRequest(30, TimeUnit.SECONDS);
    RecordedRequest recordedRequest2 = mockWebServer.takeRequest(30, TimeUnit.SECONDS);
    verifyNotification(attemptId, recordedRequest1);
    verifyNotification(attemptId, recordedRequest2);
}
 
Example #15
Source File: TCKDuration.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test()
@UseDataProvider("data_parseSuccess")
public void factory_parse_lowerCase(String text, long expectedSeconds, int expectedNanoOfSecond) {
    Duration test = Duration.parse(text.toLowerCase(Locale.ENGLISH));
    assertEquals(test.getSeconds(), expectedSeconds);
    assertEquals(test.getNano(), expectedNanoOfSecond);
}
 
Example #16
Source File: TimeLimiterTransformerObservableTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void timeoutEmpty() {
    given(timeLimiter.getTimeLimiterConfig())
        .willReturn(toConfig(Duration.ZERO));
    TestObserver<?> observer = Observable.empty()
        .delay(1, TimeUnit.MINUTES)
        .compose(TimeLimiterTransformer.of(timeLimiter))
        .test();

    testScheduler.advanceTimeBy(1, TimeUnit.MINUTES);

    observer.assertError(TimeoutException.class);
    then(timeLimiter).should()
        .onError(any(TimeoutException.class));
}
 
Example #17
Source File: DatabusResourcePoller.java    From emodb with Apache License 2.0 5 votes vote down vote up
DatabusPollRunnable(AsyncContext asyncContext, KeepAliveRunnable keepAliveRunnable, Subject subject, SubjectDatabus databus,
                    Duration claimTtl, int limit, String subscription, PeekOrPollResponseHelper helper,
                    long longPollStopTime, Timer.Context timerContext) {
    _asyncContext = asyncContext;
    _keepAliveRunnable = keepAliveRunnable;
    _subject = subject;
    _databus = databus;
    _claimTtl = claimTtl;
    _limit = limit;
    _subscription = subscription;
    _helper = helper;
    _longPollStopTime = longPollStopTime;
    _timerContext = timerContext;
}
 
Example #18
Source File: DelayTest.java    From cloudformation-cli-java-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void multipleOfDelay() {
    final Delay fixed = MultipleOf.multipleOf().delay(Duration.ofSeconds(5)).timeout(Duration.ofSeconds(105)).build();
    Duration next = Duration.ZERO;
    long accrued = 0L;
    int attempt = 1;
    while ((next = fixed.nextDelay(attempt)) != Duration.ZERO) {
        attempt++;
        accrued += next.getSeconds();
    }
    assertThat(5 + 10 + 15 + 20 + 25 + 30).isEqualTo(accrued);
    assertThat(6).isEqualTo(attempt);
}
 
Example #19
Source File: PubSubSource.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Actually build the desired instance of the PubSubSourceBuilder.
 *
 * @return a brand new SourceFunction
 * @throws IOException              in case of a problem getting the credentials
 * @throws IllegalArgumentException in case required fields were not specified.
 */
public PubSubSource<OUT> build() throws IOException {
	if (credentials == null) {
		credentials = defaultCredentialsProviderBuilder().build().getCredentials();
	}

	if (pubSubSubscriberFactory == null) {
		pubSubSubscriberFactory = new DefaultPubSubSubscriberFactory(ProjectSubscriptionName.format(projectName, subscriptionName),
																	3,
																	Duration.ofSeconds(15),
																	100);
	}

	return new PubSubSource<>(deserializationSchema, pubSubSubscriberFactory, credentials, new AcknowledgeOnCheckpointFactory(), new GuavaFlinkConnectorRateLimiter(), messagePerSecondRateLimit);
}
 
Example #20
Source File: ControlPoint.java    From PGM with GNU Affero General Public License v3.0 5 votes vote down vote up
/** Progress toward the neutral state */
private void progressUncapture(Competitor dominantTeam, Duration dominantTime) {
  this.capturingTime = this.capturingTime.plus(dominantTime);

  if (!TimeUtils.isShorterThan(this.capturingTime, this.definition.getTimeToCapture())) {
    // If uncapture is complete, recurse with the dominant team's remaining time
    dominantTime = this.capturingTime.minus(this.definition.getTimeToCapture());
    this.capturingTime = Duration.ZERO;
    this.controllingTeam = null;
    this.dominate(dominantTeam, dominantTime);
  }
}
 
Example #21
Source File: MicrometerHttpClientMetricsRecorder.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void recordResponseTime(SocketAddress remoteAddress, String uri, String method, String status, Duration time) {
	String address = Metrics.formatSocketAddress(remoteAddress);
	Timer responseTime = responseTimeCache.computeIfAbsent(new MeterKey(uri, address, method, status),
			key -> filter(responseTimeBuilder.tags(REMOTE_ADDRESS, address, URI, uri, METHOD, method, STATUS, status)
			                                 .register(REGISTRY)));
	if (responseTime != null) {
		responseTime.record(time);
	}
}
 
Example #22
Source File: MetricUpdater.java    From vespa with Apache License 2.0 5 votes vote down vote up
@Override
public void schedule(Runnable runnable, Duration frequency) {
    long frequencyMillis = frequency.toMillis();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            runnable.run();
        }
    }, frequencyMillis, frequencyMillis) ;
}
 
Example #23
Source File: RemoteMepEntryTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception, CfmConfigException {
    rmep1 = DefaultRemoteMepEntry
            .builder(MepId.valueOf((short) 1), RemoteMepState.RMEP_IDLE)
            .failedOrOkTime(Duration.ofSeconds(5))
            .macAddress(MacAddress.valueOf("AA:BB:CC:DD:EE:FF"))
            .rdi(true)
            .portStatusTlvType(PortStatusTlvType.PS_UP)
            .interfaceStatusTlvType(InterfaceStatusTlvType.IS_UP)
            .senderIdTlvType(SenderIdTlvType.SI_MAC_ADDRESS)
            .build();
}
 
Example #24
Source File: ApiPortPort.java    From logbook-kai with MIT License 5 votes vote down vote up
/**
 * 泊地修理タイマーを更新する
 */
private void akashiTimer() {
    long timer = AppCondition.get().getAkashiTimer();
    if (System.currentTimeMillis() - timer >= Duration.ofMinutes(20).toMillis()) {
        AppCondition.get().setAkashiTimer(System.currentTimeMillis());
    }
}
 
Example #25
Source File: AbstractPersistenceSupervisor.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
private Duration calculateRestartDelay() {
    final Duration minBackOff = exponentialBackOffConfig.getMin();
    final Duration maxBackOff = exponentialBackOffConfig.getMax();
    final Instant now = Instant.now();
    final Duration sinceLastError = Duration.between(lastRestart, now);
    lastRestart = now;
    if (maxBackOff.minus(sinceLastError.dividedBy(2L)).isNegative()) {
        // no restart for 2*maxBackOff; reset to minBackOff.
        return minBackOff;
    } else {
        // increase delay.
        final double randomFactor = exponentialBackOffConfig.getRandomFactor();
        return calculateNextBackOff(minBackOff, restartDelay, maxBackOff, randomFactor);
    }
}
 
Example #26
Source File: RedeliveryTests.java    From stan.java with Apache License 2.0 5 votes vote down vote up
private void checkTime(String label, Instant time1, Instant time2, Duration expected,
                       Duration tolerance) {
    Duration duration = Duration.between(time1, time2);
    Duration lowerBoundary = expected.minus(tolerance);
    Duration upperBoundary = expected.plus(tolerance);
    if ((duration.compareTo(lowerBoundary) < 0) || (duration.compareTo(upperBoundary) > 0)) {
        fail(String.format("%s not in range: %s (expected %s +/- %s)", label, duration,
                expected, tolerance));
    }
}
 
Example #27
Source File: KafkaPriceProducer.java    From smallrye-reactive-messaging with Apache License 2.0 5 votes vote down vote up
@Outgoing("prices-out")
public Multi<Double> generate() {
    // Build an infinite stream of random prices
    // It emits a price every 4 seconds
    return Multi.createFrom().ticks().every(Duration.ofSeconds(4))
            .map(x -> random.nextDouble());
}
 
Example #28
Source File: TimeDurationTest.java    From diirt with MIT License 5 votes vote down vote up
@Test
public void compare2() {
    Duration duration1 = Duration.ofMillis(500);
    Duration duration2 = Duration.ofMillis(500);
    assertThat(duration1, not(greaterThan(duration2)));
    assertThat(duration2, not(lessThan(duration1)));
    assertThat(duration1, comparesEqualTo(duration2));
    assertThat(duration2, comparesEqualTo(duration1));
}
 
Example #29
Source File: EthSchedulerTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void scheduleFutureTask_completesWhenScheduledTaskIsCancelled() {
  final CompletableFuture<Object> future = new CompletableFuture<>();
  final CompletableFuture<Object> result =
      ethScheduler.scheduleFutureTask(() -> future, Duration.ofMillis(100));

  assertThat(result.isDone()).isFalse();
  future.cancel(false);
  assertThat(result.isDone()).isTrue();
  assertThat(result.isCompletedExceptionally()).isTrue();
  assertThat(result.isCancelled()).isTrue();
}
 
Example #30
Source File: SingleRateLimiterTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEmitEvent() {
    given(rateLimiter.reservePermission()).willReturn(Duration.ofSeconds(0).toNanos());

    Single.just(1)
        .compose(RateLimiterOperator.of(rateLimiter))
        .test()
        .assertResult(1);
}