List of usage examples for java.time Duration ofSeconds
public static Duration ofSeconds(long seconds)
From source file:org.bremersee.common.spring.autoconfigure.LdaptiveAutoConfiguration.java
private PoolConfig poolConfig() { PoolConfig pc = new PoolConfig(); pc.setMaxPoolSize(properties.getMaxPoolSize()); pc.setMinPoolSize(properties.getMinPoolSize()); pc.setValidateOnCheckIn(properties.isValidateOnCheckIn()); pc.setValidateOnCheckOut(properties.isValidateOnCheckOut()); if (properties.getValidatePeriod() > 0L) { pc.setValidatePeriod(Duration.ofSeconds(properties.getValidatePeriod())); }/* ww w . j a v a2 s . c o m*/ pc.setValidatePeriodically(properties.isValidatePeriodically()); return pc; }
From source file:ai.grakn.engine.controller.TasksControllerTest.java
@Test public void afterSendingTaskWithInterval_ItIsRecurringInStorage() { Duration interval = Duration.ofSeconds(1); send(Collections.emptyMap(),/*from w w w. jav a 2 s . co m*/ ImmutableMap.of(TASK_CLASS_NAME_PARAMETER, ShortExecutionMockTask.class.getName(), TASK_CREATOR_PARAMETER, this.getClass().getName(), TASK_RUN_AT_PARAMETER, Long.toString(now().toEpochMilli()), TASK_RUN_INTERVAL_PARAMETER, Long.toString(interval.toMillis()))); verify(manager).addTask(argThat(argument -> argument.schedule().interval().isPresent()), any()); verify(manager).addTask(argThat(argument -> argument.schedule().isRecurring()), any()); }
From source file:org.bremersee.common.spring.autoconfigure.LdaptiveAutoConfiguration.java
private PruneStrategy pruneStrategy() { // there may be other ways IdlePruneStrategy ips = new IdlePruneStrategy(); if (properties.getIdleTime() > 0L) { ips.setIdleTime(Duration.ofSeconds(properties.getIdleTime())); }/* w ww .j a va 2 s.co m*/ if (properties.getPrunePeriod() > 0L) { ips.setPrunePeriod(Duration.ofSeconds(properties.getPrunePeriod())); } return ips; }
From source file:org.springframework.cloud.deployer.spi.cloudfoundry.CloudFoundry2620AndEarlierTaskLauncher.java
@Override public void destroy(String appName) { getOptionalApplication(appName).doOnSuccess(a -> { if (a == null) logger.info("Did not destroy app {} as it did not exist", appName); }).then(app -> requestListServiceBindings(app.getId()) .flatMap(sb -> requestDeleteServiceBinding(sb.getId())).then(requestDeleteApplication(app.getId())) .doOnSuccess(v -> logger.info("Successfully destroyed app {}", appName)) .doOnError(e -> logger.error(String.format("Failed to destroy app %s", appName), e))) .timeout(Duration.ofSeconds(this.deploymentProperties.getApiTimeout())).subscribe(); }
From source file:no.digipost.api.useragreements.client.response.ResponseUtils.java
public static Optional<Duration> parseDelayDurationOfRetryAfterHeader(HttpResponse response, Clock clock) { return getValueOfFirstHeader(response, Headers.Retry_After).map(retryAfterValue -> { try {// w w w . j a v a 2 s.c o m long parsedSeconds = Long.parseLong(retryAfterValue); return Duration.ofSeconds(parsedSeconds); } catch (NumberFormatException secondsNotParseable) { try { Instant parsedInstant = RFC_1123_DATE_TIME.parse(retryAfterValue, Instant::from); return Duration.between(clock.instant(), parsedInstant); } catch (RuntimeException e) { e.addSuppressed(secondsNotParseable); throw e; } } }); }
From source file:io.pravega.segmentstore.server.reading.StorageReaderTests.java
/** * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read). * Test this both with successful and failed reads. *//* w w w . j a v a 2s . c o m*/ @Test public void testDependents() { final Duration waitTimeout = Duration.ofSeconds(5); TestStorage storage = new TestStorage(); CompletableFuture<Integer> signal = new CompletableFuture<>(); AtomicBoolean wasReadInvoked = new AtomicBoolean(); storage.readImplementation = () -> { if (wasReadInvoked.getAndSet(true)) { Assert.fail( "Read was invoked multiple times, which is a likely indicator that the requests were not chained."); } return signal; }; @Cleanup StorageReader reader = new StorageReader(SEGMENT_METADATA, storage, executorService()); // Create some reads. CompletableFuture<StorageReader.Result> c1 = new CompletableFuture<>(); CompletableFuture<StorageReader.Result> c2 = new CompletableFuture<>(); reader.execute(new StorageReader.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT)); reader.execute(new StorageReader.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT)); Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone()); signal.completeExceptionally(new IntentionalException()); AssertExtensions.assertThrows("The first read was not failed with the correct exception.", () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); AssertExtensions.assertThrows("The second read was not failed with the correct exception.", () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); }
From source file:com.github.aptd.simulation.datamodel.CXMLReader.java
@Override @SuppressWarnings("unchecked") public final IExperiment get(final IFactory p_factory, final String p_datamodel, final long p_simulationsteps, final boolean p_parallel, final String p_timemodel, final Supplier<RealDistribution> p_platformchangedurationdistributionsupplier, final int p_numberofpassengers, final double p_lightbarrierminfreetime, final double p_delayseconds) { try (final FileInputStream l_stream = new FileInputStream(p_datamodel)) { final Asimov l_model = (Asimov) m_context.createUnmarshaller().unmarshal(l_stream); // time definition final Instant l_starttime = ZonedDateTime.now(ZoneId.systemDefault()) .with(ChronoField.CLOCK_HOUR_OF_DAY, 8).with(ChronoField.MINUTE_OF_HOUR, 45) .with(ChronoField.SECOND_OF_MINUTE, 0).with(ChronoField.NANO_OF_SECOND, 0) .with(ChronoField.DAY_OF_MONTH, 3).with(ChronoField.MONTH_OF_YEAR, 10) .with(ChronoField.YEAR, 2017).toInstant(); final ITime l_time = "jump".equals(p_timemodel) ? new CJumpTime(l_starttime, p_simulationsteps) : new CStepTime(l_starttime, Duration.ofSeconds(1), p_simulationsteps); final CMessenger l_messenger = new CMessenger(); final Set<IAction> l_actionsfrompackage = CCommon.actionsFromPackage().collect(Collectors.toSet()); // asl agent definition final Map<String, String> l_agentdefs = agents(l_model.getAi()); // macro (train-network) and microscopic model final Map<String, IPlatform<?>> l_platform = platform(l_model.getNetwork(), l_agentdefs, p_factory, l_time);/*from ww w . jav a 2s. c o m*/ final Map<String, IStation<?>> l_station = station(l_model.getNetwork(), l_agentdefs, p_factory, l_time, l_platform); final Pair<Map<String, ITrain<?>>, Map<String, IDoor<?>>> l_train = train(l_model.getNetwork(), l_agentdefs, p_factory, l_time, p_lightbarrierminfreetime); final Map<String, IElement<?>> l_agents = new HashMap<>(); l_agents.putAll(l_platform); l_agents.putAll(l_station); l_agents.putAll(l_train.getLeft()); l_agents.putAll(l_train.getRight()); final CExperiment l_experiment = new CExperiment(p_simulationsteps, p_parallel, IStatistic.EMPTY, l_agents, l_time, l_messenger); // @todo create passengersources and their passenger generators according to scenario definition final IElement.IGenerator<IPassenger<?>> l_passengergenerator = passengergenerator(p_factory, "+!activate <-\n state/transition\n.", l_actionsfrompackage, l_time); l_experiment.addAgent("passengersource_test", passengersourcegenerator(p_factory, "+!activate <-\n state/transition\n.", l_actionsfrompackage, l_time).generatesingle(new UniformRealDistribution(0.0, 1.0), l_time.current().toEpochMilli(), p_numberofpassengers, l_passengergenerator, l_experiment, l_agents.get("toy-node-1"), p_platformchangedurationdistributionsupplier.get())); l_messenger.experiment(l_experiment); // experiment (executable model) return l_experiment; } catch (final Exception l_execption) { throw new CRuntimeException(l_execption); } }
From source file:io.pravega.segmentstore.server.reading.StorageReadManagerTests.java
/** * Tests the ability to queue dependent reads (subsequent reads that only want to read a part of a previous read). * Test this both with successful and failed reads. *//*from w ww . java 2s. c o m*/ @Test public void testDependents() { final Duration waitTimeout = Duration.ofSeconds(5); TestStorage storage = new TestStorage(); CompletableFuture<Integer> signal = new CompletableFuture<>(); AtomicBoolean wasReadInvoked = new AtomicBoolean(); storage.readImplementation = () -> { if (wasReadInvoked.getAndSet(true)) { Assert.fail( "Read was invoked multiple times, which is a likely indicator that the requests were not chained."); } return signal; }; @Cleanup StorageReadManager reader = new StorageReadManager(SEGMENT_METADATA, storage, executorService()); // Create some reads. CompletableFuture<StorageReadManager.Result> c1 = new CompletableFuture<>(); CompletableFuture<StorageReadManager.Result> c2 = new CompletableFuture<>(); reader.execute(new StorageReadManager.Request(0, 100, c1::complete, c1::completeExceptionally, TIMEOUT)); reader.execute(new StorageReadManager.Request(50, 100, c2::complete, c2::completeExceptionally, TIMEOUT)); Assert.assertFalse("One or more of the reads has completed prematurely.", c1.isDone() || c2.isDone()); signal.completeExceptionally(new IntentionalException()); AssertExtensions.assertThrows("The first read was not failed with the correct exception.", () -> c1.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); AssertExtensions.assertThrows("The second read was not failed with the correct exception.", () -> c2.get(waitTimeout.toMillis(), TimeUnit.MILLISECONDS), ex -> ex instanceof IntentionalException); }
From source file:reactivity.SseController.java
/** * Builds a new SSE containing the given {@link Artifact}. * * @param artifact the artifact// w w w . j a v a 2s . c om * @return the SSE */ private ServerSentEvent<Artifact> sse(final Artifact artifact) { return ServerSentEvent.<Artifact>builder(artifact).retry(Duration.ofSeconds(5)) .id(String.valueOf(artifact.getTimestamp())).build(); }
From source file:io.pravega.service.server.host.ZKSegmentContainerMonitorTest.java
@Test public void testShutdownNotYetStartedContainer() throws Exception { @Cleanup/* w w w . ja v a 2 s .co m*/ CuratorFramework zkClient = startClient(); initializeHostContainerMapping(zkClient); SegmentContainerRegistry containerRegistry = createMockContainerRegistry(); @Cleanup ZKSegmentContainerMonitor segMonitor = createContainerMonitor(containerRegistry, zkClient); segMonitor.initialize(Duration.ofSeconds(1)); // Simulate a container that takes a long time to start. Should be greater than a few monitor loops. ContainerHandle containerHandle = mock(ContainerHandle.class); when(containerHandle.getContainerId()).thenReturn(2); CompletableFuture<ContainerHandle> startupFuture = FutureHelpers .delayedFuture(() -> CompletableFuture.completedFuture(containerHandle), 3000, executorService()); when(containerRegistry.startContainer(eq(2), any())).thenReturn(startupFuture); // Use ZK to send that information to the Container Manager. HashMap<Host, Set<Integer>> currentData = deserialize(zkClient, PATH); currentData.put(PRAVEGA_SERVICE_ENDPOINT, Collections.singleton(2)); zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData)); // Verify it's not yet started. verify(containerRegistry, timeout(10000).atLeastOnce()).startContainer(eq(2), any()); assertEquals(0, segMonitor.getRegisteredContainers().size()); // Now simulate shutting it down. when(containerRegistry.stopContainer(any(), any())).thenReturn(CompletableFuture.completedFuture(null)); currentData.clear(); zkClient.setData().forPath(PATH, SerializationUtils.serialize(currentData)); verify(containerRegistry, timeout(10000).atLeastOnce()).stopContainer(any(), any()); Thread.sleep(2000); assertEquals(0, segMonitor.getRegisteredContainers().size()); }