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: ZestGuidance.java From JQF with BSD 2-Clause "Simplified" License | 6 votes |
/** * 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 #2
Source File: FluxSwitchOnFirstTest.java From reactor-core with Apache License 2.0 | 6 votes |
@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 |
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 |
@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 |
@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 |
@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 |
@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: CloudFormationStackSetTest.java From pipeline-aws-plugin with Apache License 2.0 | 6 votes |
@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 #9
Source File: DefaultManyReconcilerTest.java From titus-control-plane with Apache License 2.0 | 6 votes |
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 #10
Source File: IntegrationTestBase.java From aws-sdk-java-v2 with Apache License 2.0 | 6 votes |
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 #11
Source File: MockDebugClient.java From bazel with Apache License 2.0 | 6 votes |
/** 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 #12
Source File: SQLiteArtifactCacheTest.java From buck with Apache License 2.0 | 6 votes |
@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: FutureTest.java From future with Apache License 2.0 | 6 votes |
@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 #14
Source File: ImagePreprocessingService.java From NetDiscovery with Apache License 2.0 | 5 votes |
private Observable<ByteBuffer> preprocess(Mat image) { return Observable.fromCallable(() -> { Instant start = Instant.now(); Mat resized = new Mat(); Imgproc.resize(image, resized, new Size(0, 0), 1.2, 1.2, Imgproc.INTER_CUBIC); image.release(); Mat grey = new Mat(); Imgproc.cvtColor(resized, grey, Imgproc.COLOR_RGB2GRAY); resized.release(); Mat binary = new Mat(); Imgproc.adaptiveThreshold(grey, binary, 255, Imgproc.ADAPTIVE_THRESH_GAUSSIAN_C, Imgproc.THRESH_BINARY, 21, 1); grey.release(); MatOfByte bytes = new MatOfByte(); Imgcodecs.imencode(".png", binary, bytes); binary.release(); ByteBuffer buffer = ByteBuffer.wrap(bytes.toArray()); bytes.release(); log.info("Preprocessing of image took {} millis", Duration.between(start, Instant.now()).toMillis()); return buffer; }); }
Example #15
Source File: SwipeSteps.java From colibri-ui with Apache License 2.0 | 5 votes |
protected void verticalSwipe(String elementName, int swipeLength, int duration) { WebElement webElement = getWebElementByName(elementName); new TouchAction(driver) .press(element(webElement)) .waitAction(waitOptions(Duration.ofSeconds(duration))) .moveTo(point(0, swipeLength)) .release().perform(); }
Example #16
Source File: DockerSessionFactory.java From selenium with Apache License 2.0 | 5 votes |
private void waitForServerToStart(HttpClient client, Duration duration) { Wait<Object> wait = new FluentWait<>(new Object()) .withTimeout(duration) .ignoring(UncheckedIOException.class); wait.until(obj -> { HttpResponse response = client.execute(new HttpRequest(GET, "/status")); LOG.fine(string(response)); return 200 == response.getStatus(); }); }
Example #17
Source File: AsyncHttpServerTest.java From rapidoid with Apache License 2.0 | 5 votes |
@Test public void testAsyncHttpServer() { On.req(req -> { U.must(!req.isAsync()); req.async(); U.must(req.isAsync()); async(() -> { IO.write(req.out(), "O"); async(() -> { IO.write(req.out(), "K"); try { req.out().close(); } catch (IOException e) { e.printStackTrace(); } req.done(); }); }); return req; }); assertTimeout(Duration.ofSeconds(20), () -> { Self.get("/").expect("OK").execute(); Self.get("/").expect("OK").benchmark(1, 100, REQUESTS); Self.post("/").expect("OK").benchmark(1, 100, REQUESTS); }); }
Example #18
Source File: StatisticsFormatterTest.java From cucumber-performance with MIT License | 5 votes |
@Test public void testGetMax() { List<GroupResult> res = new ArrayList<GroupResult>(); res.add(new GroupResult("test", new Result(Status.PASSED, Duration.ofMillis(1000), null), LocalDateTime.now(),LocalDateTime.now())); res.add(new GroupResult("test", new Result(Status.PASSED, Duration.ofMillis(1200), null), LocalDateTime.now(),LocalDateTime.now())); PluginFactory pf = new PluginFactory(); PerfRuntimeOptions options = new PerfRuntimeOptions(); Plugins plugins = new Plugins(this.getClass().getClassLoader(), pf, options); plugins.setEventBusOnPlugins(eventBus); value = (long)1200000000; type = "max"; eventBus.registerHandlerFor(StatisticsFinished.class, statsEventhandler); eventBus.send(new SimulationFinished(eventBus.getTime(),eventBus.getTimeMillis(), new SimulationResult("test",new Result(Status.PASSED, Duration.ofMillis(0), null), LocalDateTime.parse("2007-12-12T05:20:22"),LocalDateTime.parse("2007-12-12T05:25:22"), res))); }
Example #19
Source File: KafkaSampleApplicationTest.java From vertx-spring-boot with Apache License 2.0 | 5 votes |
private List<String> getLoggedMessages() { return client.get() .accept(TEXT_EVENT_STREAM) .exchange() .expectStatus() .isOk() .returnResult(String.class) .getResponseBody() .collectList() .block(Duration.ofSeconds(2)); }
Example #20
Source File: SlaIT.java From digdag with Apache License 2.0 | 5 votes |
@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 #21
Source File: CredentialsServiceImpl.java From enmasse with Apache License 2.0 | 5 votes |
private Duration calculateRemainingTtl(final TenantKey tenant, final MetadataValue<?> result) { if (result.getLifespan() > 0 && result.getCreated() > 0) { final Instant eol = ofEpochMilli(result.getCreated()) .plus(ofSeconds(result.getLifespan())); return between(now(), eol); } else { return getStoreTtl(tenant); } }
Example #22
Source File: GraphQLMetricHandlerTest.java From stream-registry with Apache License 2.0 | 5 votes |
@Test public void failure() throws Throwable { RuntimeException failed = new RuntimeException("failed"); when(delegate.byKey(key)).thenThrow(failed); try { underTest.invoke(null, method, new Object[] { key }); fail("Expected exception"); } catch (RuntimeException e) { assertThat(e, is(failed)); } verify(registry).timer("graphql_api", tags.and("result", "failure").and("authentication_group", ANONYMOUS.name())); verify(timer).record(any(Duration.class)); }
Example #23
Source File: TCKDuration.java From openjdk-jdk9 with GNU General Public License v2.0 | 5 votes |
@Test(dataProvider="PlusSeconds") public void plusSeconds_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) { Duration t = Duration.ofSeconds(seconds, nanos); t = t.plusSeconds(amount); assertEquals(t.getSeconds(), expectedSeconds); assertEquals(t.getNano(), expectedNanoOfSecond); }
Example #24
Source File: FluxSampleTimeoutTest.java From reactor-core with Apache License 2.0 | 5 votes |
@Test public void sourceTerminatesBeforeSamplingEmitsLast() { Flux<Integer> source = Flux.just(1, 2).hide(); Duration duration = StepVerifier.create(source .sampleTimeout(i -> Mono.delay(Duration.ofMillis(250)))) .expectNext(2) .verifyComplete(); //sanity check on the sequence duration assertThat(duration.toMillis()).isLessThan(250); }
Example #25
Source File: EthSchedulerTest.java From besu with Apache License 2.0 | 5 votes |
@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 #26
Source File: TimeDurationTest.java From diirt with MIT License | 5 votes |
@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 #27
Source File: TCKDuration.java From j2objc with Apache License 2.0 | 5 votes |
@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 #28
Source File: TimeLimiterTransformerObservableTest.java From resilience4j with Apache License 2.0 | 5 votes |
@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 #29
Source File: KafkaPriceProducer.java From smallrye-reactive-messaging with Apache License 2.0 | 5 votes |
@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 #30
Source File: FluxFirstNonEmptyEmittingTests.java From spring-cloud-commons with Apache License 2.0 | 5 votes |
@Test public void neverAndEmpty() { StepVerifier .withVirtualTime( () -> CloudFlux.firstNonEmpty(Flux.never(), Flux.empty())) .expectSubscription().expectNoEvent(Duration.ofDays(1)).thenCancel() .verifyThenAssertThat().hasNotDiscardedElements().hasNotDroppedElements() .hasNotDroppedErrors(); }