Java Code Examples for java.time.Duration#ofMillis()

The following examples show how to use java.time.Duration#ofMillis() . 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: OpticalConnectivityTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks the construction of OpticalConnectivity object.
 */
@Test
public void testCreate() {
    Bandwidth bandwidth = Bandwidth.bps(100);
    Duration latency = Duration.ofMillis(10);

    // Mock 3-nodes linear topology
    ConnectPoint cp12 = createConnectPoint(1, 2);
    ConnectPoint cp21 = createConnectPoint(2, 1);
    ConnectPoint cp22 = createConnectPoint(2, 2);
    ConnectPoint cp31 = createConnectPoint(3, 1);

    Link link1 = createLink(cp12, cp21);
    Link link2 = createLink(cp22, cp31);
    List<Link> links = Stream.of(link1, link2).collect(Collectors.toList());

    OpticalConnectivityId cid = OpticalConnectivityId.of(1L);
    OpticalConnectivity oc = new OpticalConnectivity(cid, links, bandwidth, latency,
            Collections.emptySet(), Collections.emptySet());

    assertNotNull(oc);
    assertEquals(oc.id(), cid);
    assertEquals(oc.links(), links);
    assertEquals(oc.bandwidth(), bandwidth);
    assertEquals(oc.latency(), latency);
}
 
Example 2
Source File: StepDistributionSummaryTest.java    From micrometer with Apache License 2.0 6 votes vote down vote up
@Issue("#1814")
@Test
void meanShouldWorkIfTotalNotCalled() {
    Duration stepDuration = Duration.ofMillis(10);
    MockClock clock = new MockClock();
    StepDistributionSummary summary = new StepDistributionSummary(
            mock(Meter.Id.class),
            clock,
            DistributionStatisticConfig.builder().expiry(stepDuration).bufferLength(2).build(),
            1.0,
            stepDuration.toMillis(),
            false
    );

    clock.add(stepDuration);
    assertThat(summary.mean()).isEqualTo(0.0);

    clock.add(Duration.ofMillis(1));
    summary.record(50);
    summary.record(100);

    clock.add(stepDuration);
    assertThat(summary.mean()).isEqualTo(75.0);
}
 
Example 3
Source File: ThrottlerCalculatorTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the ability to properly calculate DurableDataLog-related delays.
 */
@Test
public void testDurableDataLog() {
    val halfRatio = 0.5;
    val maxWriteSize = 12345;
    val maxQueueCount = 123;
    val maxOutstandingBytes = maxWriteSize * maxQueueCount;
    val minThrottleThreshold = (int) (maxOutstandingBytes * ThrottlerCalculator.DURABLE_DATALOG_THROTTLE_THRESHOLD_FRACTION / maxWriteSize);
    val maxThrottleThreshold = (int) ((double) maxOutstandingBytes / maxWriteSize);
    val writeSettings = new WriteSettings(maxWriteSize, Duration.ofMillis(1234), maxOutstandingBytes);
    val thresholdMillis = (int) (writeSettings.getMaxWriteTimeout().toMillis() * ThrottlerCalculator.DURABLE_DATALOG_THROTTLE_THRESHOLD_FRACTION);
    val queueStats = new AtomicReference<QueueStats>(null);
    val tc = ThrottlerCalculator.builder().durableDataLogThrottler(writeSettings, queueStats::get).build();
    val noThrottling = new QueueStats[]{
            createStats(1, halfRatio, thresholdMillis - 1),
            createStats(minThrottleThreshold + 1, 1.0, thresholdMillis),
            createStats(maxThrottleThreshold * 2, 1.0, thresholdMillis)};
    val gradualThrottling = new QueueStats[]{
            createStats((int) (minThrottleThreshold / halfRatio) + 2, halfRatio, thresholdMillis + 1),
            createStats((int) (minThrottleThreshold / halfRatio) + 10, halfRatio, thresholdMillis + 1),
            createStats((int) (maxOutstandingBytes / halfRatio), halfRatio, thresholdMillis + 1)};
    val maxThrottling = new QueueStats[]{
            createStats((int) (maxOutstandingBytes / halfRatio) + 1, halfRatio, thresholdMillis + 1),
            createStats((int) (maxOutstandingBytes / halfRatio) * 2, halfRatio, thresholdMillis + 1)};
    testThrottling(tc, queueStats, noThrottling, gradualThrottling, maxThrottling);
}
 
Example 4
Source File: RetryerTest.java    From mug with Apache License 2.0 6 votes vote down vote up
@Test public void testCustomDelay() throws Exception {
  TestDelay<IOException> delay = new TestDelay<IOException>() {
    @Override public Duration duration() {
      return Duration.ofMillis(1);
    }
  };
  upon(IOException.class, asList(delay).stream());  // to make sure the stream overload works.
  IOException exception = new IOException();
  when(action.run()).thenThrow(exception).thenReturn("fixed");
  CompletionStage<String> stage = retry(action::run);
  elapse(Duration.ofMillis(1));
  assertCompleted(stage).isEqualTo("fixed");
  verify(action, times(2)).run();
  assertThat(delay.before).isSameAs(exception);
  assertThat(delay.after).isSameAs(exception);
}
 
Example 5
Source File: ParallelWebKafkaConsumer.java    From kafka-webview with MIT License 5 votes vote down vote up
/**
 * Constructor.
 * @param kafkaConsumerFactory Factor for creating KafkaConsumer instances.
 * @param clientConfig Client configuration.
 * @param executorService ExecutorService to submit parallel consuming tasks to.
 */
public ParallelWebKafkaConsumer(
    final KafkaConsumerFactory kafkaConsumerFactory,
    final ClientConfig clientConfig,
    final ExecutorService executorService
) {
    this.kafkaConsumerFactory = kafkaConsumerFactory;
    this.clientConfig = clientConfig;
    this.pollTimeoutDuration = Duration.ofMillis(clientConfig.getPollTimeoutMs());
    this.executorService = executorService;
}
 
Example 6
Source File: WebDriverWaitTest.java    From selenium with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void shouldSilentlyCaptureNoSuchFrameExceptions() {
  final ExpectedCondition<WebElement> condition = mock(ExpectedCondition.class);
  when(condition.apply(mockDriver))
      .thenThrow(new NoSuchFrameException("foo"))
      .thenReturn(mockElement);

  TickingClock clock = new TickingClock();
  Wait<WebDriver> wait =
      new WebDriverWait(mockDriver, Duration.ofSeconds(5), Duration.ofMillis(500), clock, clock);
  wait.until(condition);
}
 
Example 7
Source File: ZooKeeperServiceRunner.java    From pravega with Apache License 2.0 5 votes vote down vote up
private static boolean waitForSSLServerUp(String address, long timeout, String keyStore, String keyStorePasswdPath,
                                          String trustStore, String trustStorePasswordPath) {
    TimeoutTimer timeoutTimer = new TimeoutTimer(Duration.ofMillis(timeout));
    String[] split = address.split(":");
    String host = split[0];
    int port = Integer.parseInt(split[1]);

    while (true) {
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            TrustManagerFactory trustManager = getTrustManager(trustStore, trustStorePasswordPath);
            KeyManagerFactory keyFactory = getKeyManager(keyStore, keyStorePasswdPath);
            context.init(keyFactory.getKeyManagers(), trustManager.getTrustManagers(), null);

            try (Socket sock = context.getSocketFactory().createSocket(new Socket(host, port), host, port, true);
                 OutputStream outstream = sock.getOutputStream()) {
                outstream.write("stat".getBytes());
                outstream.flush();

                BufferedReader reader = new BufferedReader(new InputStreamReader(sock.getInputStream()));
                String line = reader.readLine();
                if (line != null && line.startsWith("Zookeeper version:")) {
                    log.info("Server UP");
                    return true;
                }
            }
        } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException
                | KeyManagementException | UnrecoverableKeyException e) {
            // ignore as this is expected
            log.warn("server  {} not up.", address,  e);
        }

        if (!timeoutTimer.hasRemaining()) {
            break;
        }
        Exceptions.handleInterrupted(() -> Thread.sleep(250));
    }
    return false;
}
 
Example 8
Source File: MultiplexedChannelRecordTest.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Test
public void idleTimerDoesNotApplyBeforeFirstChannelIsCreated() throws InterruptedException {
    int idleTimeoutMillis = 1000;
    EmbeddedChannel channel = newHttp2Channel();
    MultiplexedChannelRecord record = new MultiplexedChannelRecord(channel, 2, Duration.ofMillis(idleTimeoutMillis));

    Thread.sleep(idleTimeoutMillis * 2);
    channel.runPendingTasks();

    assertThat(channel.isOpen()).isTrue();
}
 
Example 9
Source File: LoggerFormatterTest.java    From cucumber-performance with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testLogWithChildren() {
	LoggerFormatter stf = null;
	try {
		stf = new LoggerFormatter(new AppendableBuilder("file://C:/test/log.json"));
		GroupResult gr = new GroupResult("test", new Result(Status.PASSED, Duration.ofMillis(1000), null), LocalDateTime.now(), LocalDateTime.now());
		List<String> pickletags = new ArrayList<String>();
		List<GroupResult> list = new ArrayList<GroupResult>();
		pickletags.add("mytag");
		List<io.cucumber.plugin.event.TestStep> teststeps = new ArrayList<io.cucumber.plugin.event.TestStep>();
		teststeps.add(new TestStep("my step"));
		ScenarioResult scnr = new ScenarioResult("test", new TestCase(0, URI.create("testcases/testCase"), "testCase", "scenario", pickletags,teststeps),new Result(Status.PASSED, Duration.ofMillis(1000L), null), LocalDateTime.now(), LocalDateTime.now());
		StepResult stpr = new StepResult("test", new TestStep("my step"), new Result(Status.PASSED, Duration.ofMillis(222L), null), LocalDateTime.now(), LocalDateTime.now());
		scnr.addChildResult(stpr);
		gr.addChildResult(scnr);
		list.add(gr);
		list.add(new GroupResult("test2", new Result(Status.PASSED, Duration.ofMillis(1000L), null), LocalDateTime.now(), LocalDateTime.now()));
		PluginFactory pf = new PluginFactory();
		PerfRuntimeOptions options = new PerfRuntimeOptions();
		Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options);
		plugins.addPlugin(stf);
		plugins.setEventBusOnPlugins(eventBus);
		eventBus.send(new SimulationStarted(eventBus.getTime(),eventBus.getTimeMillis(), "test"));
		for (GroupResult res : list) {
			eventBus.send(new GroupFinished(eventBus.getTime(),eventBus.getTimeMillis(),0, new PerfGroup("group", "test.feature", 1, 10, null),res));
		}
		
	} catch (CucumberException e) {
		fail("Issue");
	}
	eventBus.send(new SimulationFinished(eventBus.getTime(),eventBus.getTimeMillis(), null));
	List<GroupResult> resultList = new ArrayList<GroupResult>();
	List<Map<String, Object>> json = (List<Map<String, Object>>) getFileJSON("C:/test/log.json",resultList.getClass());
	json.remove(0);
	resultList = stf.createGroupResultList(json);
	assertEquals((long)222,(long)resultList.get(0).getChildResults().get(0).getChildResults().get(0).getResultDuration().toMillis());
	assertTrue(deleteFile("C:/test/log.json"));
}
 
Example 10
Source File: HttpUrlConnectionSenderTests.java    From micrometer with Apache License 2.0 5 votes vote down vote up
@Test
void customReadTimeoutHonored(@WiremockResolver.Wiremock WireMockServer server) throws Throwable {
    this.httpSender = new HttpUrlConnectionSender(Duration.ofSeconds(1), Duration.ofMillis(1));
    server.stubFor(any(urlEqualTo("/metrics")).willReturn(ok().withFixedDelay(5)));

    assertThatExceptionOfType(SocketTimeoutException.class)
            .isThrownBy(() -> httpSender.post(server.baseUrl() + "/metrics").send());
}
 
Example 11
Source File: MessageFormatterTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
@Test
public void withCustomFormatterFailDescriptionHasArgs() {
	DefaultStepVerifierBuilder.Event event = new DefaultStepVerifierBuilder.NoEvent(Duration.ofMillis(5),
			"eventDescription");

	assertThat(withCustomFormatter.fail(event, "details = %s", "bar"))
			.hasMessage("[withCustomFormatter] expectation \"eventDescription\" failed (details = String=>bar)");
}
 
Example 12
Source File: RetryableTest.java    From triplea with GNU General Public License v3.0 5 votes vote down vote up
@Test
@DisplayName("We should only sleep between retries, do not sleep after the last attempt")
void noSleepAfterLastRetry() {
  final int maxAttempts = 3;
  final Duration backOff = Duration.ofMillis(1);
  Retryable.builder(threadSleeper)
      .withMaxAttempts(maxAttempts)
      .withFixedBackOff(backOff)
      .withTask(() -> false)
      .buildAndExecute();
  verify(threadSleeper, times(maxAttempts - 1)).accept(backOff);
}
 
Example 13
Source File: PeerExchange_IT.java    From bt with Apache License 2.0 4 votes vote down vote up
@Override
public Duration getTrackerQueryInterval() {
    return Duration.ofMillis(100);
}
 
Example 14
Source File: KafkaEgressSpecJsonParser.java    From flink-statefun with Apache License 2.0 4 votes vote down vote up
static Duration exactlyOnceDeliveryTxnTimeout(JsonNode json) {
  long transactionTimeout = Selectors.longAt(json, DELIVERY_EXACTLY_ONCE_TXN_TIMEOUT_POINTER);
  return Duration.ofMillis(transactionTimeout);
}
 
Example 15
Source File: ThrottlingController.java    From datakernel with Apache License 2.0 4 votes vote down vote up
@JmxAttribute
public Duration getGcTime() {
	return Duration.ofMillis(gcTimeMillis);
}
 
Example 16
Source File: DurationParser.java    From kafka-connect-couchbase with Apache License 2.0 4 votes vote down vote up
public static Duration parseDuration(String s) {
  return Duration.ofMillis(parseDuration(s, TimeUnit.MILLISECONDS));
}
 
Example 17
Source File: Json.java    From immutables with Apache License 2.0 4 votes vote down vote up
Duration took() {
  return Duration.ofMillis(took);
}
 
Example 18
Source File: LockKeyColumnValueStoreTest.java    From titan1withtp3.1 with Apache License 2.0 4 votes vote down vote up
@Test
public void testLocksOnMultipleStores() throws Exception {

    final int numStores = 6;
    Preconditions.checkState(numStores % 3 == 0);
    final StaticBuffer key  = BufferUtil.getLongBuffer(1);
    final StaticBuffer col  = BufferUtil.getLongBuffer(2);
    final StaticBuffer val2 = BufferUtil.getLongBuffer(8);

    // Create mocks
    LockerProvider mockLockerProvider = createStrictMock(LockerProvider.class);
    Locker mockLocker = createStrictMock(Locker.class);

    // Create EVCSManager with mockLockerProvider
    ExpectedValueCheckingStoreManager expManager =
            new ExpectedValueCheckingStoreManager(manager[0], "multi_store_lock_mgr",
                    mockLockerProvider, Duration.ofMillis(100L));

    // Begin EVCTransaction
    BaseTransactionConfig txCfg = StandardBaseTransactionConfig.of(times);
    ExpectedValueCheckingTransaction tx = expManager.beginTransaction(txCfg);

    // openDatabase calls getLocker, and we do it numStores times
    expect(mockLockerProvider.getLocker(anyObject(String.class))).andReturn(mockLocker).times(numStores);

    // acquireLock calls writeLock, and we do it 2/3 * numStores times
    mockLocker.writeLock(eq(new KeyColumn(key, col)), eq(tx.getConsistentTx()));
    expectLastCall().times(numStores / 3 * 2);

    // mutateMany calls checkLocks, and we do it 2/3 * numStores times
    mockLocker.checkLocks(tx.getConsistentTx());
    expectLastCall().times(numStores / 3 * 2);

    replay(mockLockerProvider);
    replay(mockLocker);

    /*
     * Acquire a lock on several distinct stores (numStores total distinct
     * stores) and build mutations.
     */
    ImmutableMap.Builder<String, Map<StaticBuffer, KCVMutation>> builder = ImmutableMap.builder();
    for (int i = 0; i < numStores; i++) {
        String storeName = "multi_store_lock_" + i;
        KeyColumnValueStore s = expManager.openDatabase(storeName);

        if (i % 3 < 2)
            s.acquireLock(key, col, null, tx);

        if (i % 3 > 0)
            builder.put(storeName, ImmutableMap.of(key, new KCVMutation(ImmutableList.of(StaticArrayEntry.of(col, val2)), ImmutableList.<StaticBuffer>of())));
    }

    // Mutate
    expManager.mutateMany(builder.build(), tx);

    // Shutdown
    expManager.close();

    // Check the mocks
    verify(mockLockerProvider);
    verify(mockLocker);
}
 
Example 19
Source File: NetworkBufferPool.java    From flink with Apache License 2.0 4 votes vote down vote up
@VisibleForTesting
public NetworkBufferPool(int numberOfSegmentsToAllocate, int segmentSize, int numberOfSegmentsToRequest) {
	this(numberOfSegmentsToAllocate, segmentSize, numberOfSegmentsToRequest, Duration.ofMillis(Integer.MAX_VALUE));
}
 
Example 20
Source File: RetentionByTopicFunction.java    From data-highway with Apache License 2.0 4 votes vote down vote up
private Duration retention(Entry<ConfigResource, Config> e) {
  return Duration.ofMillis(parseLong(e.getValue().get("retention.ms").value()));
}