Java Code Examples for java.time.Duration#ofMillis()
The following examples show how to use
java.time.Duration#ofMillis() .
These examples are extracted from open source projects.
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 Project: onos File: OpticalConnectivityTest.java License: Apache License 2.0 | 6 votes |
/** * 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 Project: mug File: RetryerTest.java License: Apache License 2.0 | 6 votes |
@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 3
Source Project: pravega File: ThrottlerCalculatorTests.java License: Apache License 2.0 | 6 votes |
/** * 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 Project: micrometer File: StepDistributionSummaryTest.java License: Apache License 2.0 | 6 votes |
@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 5
Source Project: triplea File: RetryableTest.java License: GNU General Public License v3.0 | 5 votes |
@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 6
Source Project: reactor-core File: MessageFormatterTest.java License: Apache License 2.0 | 5 votes |
@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 7
Source Project: kafka-webview File: ParallelWebKafkaConsumer.java License: MIT License | 5 votes |
/** * 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 8
Source Project: micrometer File: HttpUrlConnectionSenderTests.java License: Apache License 2.0 | 5 votes |
@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 9
Source Project: cucumber-performance File: LoggerFormatterTest.java License: MIT License | 5 votes |
@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 Project: aws-sdk-java-v2 File: MultiplexedChannelRecordTest.java License: Apache License 2.0 | 5 votes |
@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 11
Source Project: pravega File: ZooKeeperServiceRunner.java License: Apache License 2.0 | 5 votes |
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 12
Source Project: selenium File: WebDriverWaitTest.java License: Apache License 2.0 | 5 votes |
@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 13
Source Project: bt File: PeerExchange_IT.java License: Apache License 2.0 | 4 votes |
@Override public Duration getTrackerQueryInterval() { return Duration.ofMillis(100); }
Example 14
Source Project: data-highway File: RetentionByTopicFunction.java License: Apache License 2.0 | 4 votes |
private Duration retention(Entry<ConfigResource, Config> e) { return Duration.ofMillis(parseLong(e.getValue().get("retention.ms").value())); }
Example 15
Source Project: flink File: NetworkBufferPool.java License: Apache License 2.0 | 4 votes |
@VisibleForTesting public NetworkBufferPool(int numberOfSegmentsToAllocate, int segmentSize, int numberOfSegmentsToRequest) { this(numberOfSegmentsToAllocate, segmentSize, numberOfSegmentsToRequest, Duration.ofMillis(Integer.MAX_VALUE)); }
Example 16
Source Project: immutables File: Json.java License: Apache License 2.0 | 4 votes |
Duration took() { return Duration.ofMillis(took); }
Example 17
Source Project: kafka-connect-couchbase File: DurationParser.java License: Apache License 2.0 | 4 votes |
public static Duration parseDuration(String s) { return Duration.ofMillis(parseDuration(s, TimeUnit.MILLISECONDS)); }
Example 18
Source Project: datakernel File: ThrottlingController.java License: Apache License 2.0 | 4 votes |
@JmxAttribute public Duration getGcTime() { return Duration.ofMillis(gcTimeMillis); }
Example 19
Source Project: flink-statefun File: KafkaEgressSpecJsonParser.java License: Apache License 2.0 | 4 votes |
static Duration exactlyOnceDeliveryTxnTimeout(JsonNode json) { long transactionTimeout = Selectors.longAt(json, DELIVERY_EXACTLY_ONCE_TXN_TIMEOUT_POINTER); return Duration.ofMillis(transactionTimeout); }
Example 20
Source Project: titan1withtp3.1 File: LockKeyColumnValueStoreTest.java License: Apache License 2.0 | 4 votes |
@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); }