Java Code Examples for java.time.Duration

The following are top voted examples for showing how to use java.time.Duration. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: spydra   File: PoolingTest.java   View source code 6 votes vote down vote up
@Test
public void mayCreateMoreClusters() throws Exception {
  String myClientId="some-client-id";
  ImmutableList<Cluster> clusters =
      ImmutableList.of(perfectCluster(myClientId), perfectCluster(myClientId));
  SpydraArgument arguments = new SpydraArgument();
  SpydraArgument.Pooling pooling = new SpydraArgument.Pooling();
  pooling.setLimit(2);
  pooling.setMaxAge(Duration.ofMinutes(30));
  arguments.setPooling(pooling);
  arguments.setClientId(myClientId);

  assertFalse(PoolingSubmitter.Conditions.mayCreateMoreClusters(clusters, arguments));

  pooling.setLimit(3);
  assertTrue(PoolingSubmitter.Conditions.mayCreateMoreClusters(clusters, arguments));
}
 
Example 2
Project: db-queue   File: PickTaskDaoTest.java   View source code 6 votes vote down vote up
@Test
public void pick_task_should_delay_with_linear_strategy() {
    QueueLocation location = generateUniqueLocation();
    Duration expectedDelay = Duration.ofMinutes(3L);
    ZonedDateTime beforePickingTask;
    ZonedDateTime afterPickingTask;
    TaskRecord taskRecord;
    RetryTaskStrategy retryTaskStrategy = new RetryTaskStrategy.LinearBackoff(
            QueueSettings.builder().withNoTaskTimeout(Duration.ZERO)
                    .withBetweenTaskTimeout(Duration.ZERO)
                    .withRetryInterval(Duration.ofMinutes(3))
                    .build());

    Long enqueueId = executeInTransaction(() -> queueDao.enqueue(location, new EnqueueParams<>()));

    for (int attempt = 1; attempt < 10; attempt++) {
        beforePickingTask = ZonedDateTime.now();
        taskRecord = resetProcessTimeAndPick(location, retryTaskStrategy, enqueueId);
        afterPickingTask = ZonedDateTime.now();
        Assert.assertThat(taskRecord.getAttemptsCount(), equalTo((long) attempt));
        Assert.assertThat(taskRecord.getProcessTime().isAfter(beforePickingTask.plus(expectedDelay.minus(WINDOWS_OS_DELAY))), equalTo(true));
        Assert.assertThat(taskRecord.getProcessTime().isBefore(afterPickingTask.plus(expectedDelay).plus(WINDOWS_OS_DELAY)), equalTo(true));
    }
}
 
Example 3
Project: conf4j   File: PeriodicalReloadStrategyTest.java   View source code 6 votes vote down vote up
@Test
public void testExceptionWhileCallingReloadCaught() {
    LongAdder numOfReloadCalls = new LongAdder();
    PeriodicalReloadStrategy strategy = PeriodicalReloadStrategy.builder()
            .withInterval(Duration.ofMillis(50))
            .build();

    try {
        strategy.start(() -> {
            numOfReloadCalls.increment();
            if (numOfReloadCalls.longValue() == 1) {
                throw new RuntimeException();
            }
        });

        await("Reload called more then once")
                .atMost(5, TimeUnit.SECONDS)
                .until(() -> numOfReloadCalls.longValue() > 1);
    } finally {
        strategy.stop();
    }
}
 
Example 4
Project: ndbc   File: Config.java   View source code 6 votes vote down vote up
private Config(final String dataSourceSupplierClass, final String host, final int port,
    final String user,
    final Charset charset, final Optional<String> password, final Optional<String> database,
    final Optional<Integer> poolMaxSize, final Optional<Integer> poolMaxWaiters,
    final Optional<Duration> poolValidationInterval, final Optional<Set<String>> encodingClasses,
    final Optional<Integer> nioThreads, final Optional<SSL> ssl) {
  super();
  this.dataSourceSupplierClass = dataSourceSupplierClass;
  this.charset = charset;
  this.user = user;
  this.password = password;
  this.database = database;
  this.host = host;
  this.port = port;
  this.poolMaxSize = poolMaxSize;
  this.poolMaxWaiters = poolMaxWaiters;
  this.poolValidationInterval = poolValidationInterval;
  this.encodingClasses = encodingClasses.map(Collections::unmodifiableSet);
  this.nioThreads = nioThreads;
  this.ssl = ssl;
}
 
Example 5
Project: openjdk-jdk10   File: TCKDuration.java   View source code 6 votes vote down vote up
@Test
public void test_comparisons() {
    doTest_comparisons_Duration(
        Duration.ofSeconds(-2L, 0),
        Duration.ofSeconds(-2L, 999999998),
        Duration.ofSeconds(-2L, 999999999),
        Duration.ofSeconds(-1L, 0),
        Duration.ofSeconds(-1L, 1),
        Duration.ofSeconds(-1L, 999999998),
        Duration.ofSeconds(-1L, 999999999),
        Duration.ofSeconds(0L, 0),
        Duration.ofSeconds(0L, 1),
        Duration.ofSeconds(0L, 2),
        Duration.ofSeconds(0L, 999999999),
        Duration.ofSeconds(1L, 0),
        Duration.ofSeconds(2L, 0)
    );
}
 
Example 6
Project: micrometer   File: SampleRegistries.java   View source code 6 votes vote down vote up
public static SignalFxMeterRegistry signalFx(String accessToken) {
    return new SignalFxMeterRegistry(new SignalFxConfig() {
        @Override
        public String accessToken() {
            return accessToken;
        }

        @Override
        public Duration step() {
            return Duration.ofSeconds(10);
        }

        @Override
        public String get(String k) {
            return null;
        }
    }, Clock.SYSTEM);
}
 
Example 7
Project: Riho   File: IdeActionListener.java   View source code 6 votes vote down vote up
@Override
public void beforeEditorTyping(char c, DataContext dataContext) {
    Instant now = Instant.now();
    Duration between = Duration.between(lastInputTime, now);
    lastInputTime = now;

    if (between.getSeconds() < comboCoolTimeSec) {
        comboCount++;
    } else {
        comboCount = 0;
        return;
    }

    RihoReactionNotifier publisher = project.getMessageBus().syncPublisher(RihoReactionNotifier.REACTION_NOTIFIER);
    switch (comboCount) {
        case 5: publisher.reaction(Reaction.of(FacePattern.SMILE1, Duration.ofSeconds(3))); break;
        case 10: publisher.reaction(Reaction.of(FacePattern.SMILE2, Duration.ofSeconds(3))); break;
        case 15: publisher.reaction(Reaction.of(FacePattern.SURPRISE, Duration.ofSeconds(5))); break;
        case 20:
        case 30: publisher.reaction(Reaction.of(FacePattern.AWAWA, Duration.ofSeconds(3))); break;
    }
}
 
Example 8
Project: ProjectAres   File: TimeLimitCountdown.java   View source code 6 votes vote down vote up
@Override
public void onTick(Duration remaining, Duration total) {
    super.onTick(remaining, total);

    if(this.timeLimit.getShow()) {
        long secondsLeft = remaining.getSeconds();
        if(secondsLeft > 30) {
            if(this.shouldBeep()) {
                this.getMatch().playSound(NOTICE_SOUND);
            }
        }
        else if(secondsLeft > 0) {
            // Tick for the last 30 seconds
            this.getMatch().playSound(IMMINENT_SOUND);
        }
        if(secondsLeft == 5) {
            // Play the portal crescendo sound up to the last moment
            this.getMatch().playSound(CRESCENDO_SOUND);
        }
    }
}
 
Example 9
Project: ProjectAres   File: FilterDefinitionParser.java   View source code 6 votes vote down vote up
@MethodParser("time")
public Filter parseTimeFilter(Element el) throws InvalidXMLException {
    final Duration duration = XMLUtils.parseDuration(el, (Duration) null);
    if(Comparables.greaterThan(duration, Duration.ZERO)) {
        return new AllFilter(
            MatchStateFilter.started(),
            new MonostableFilter(
                duration,
                MatchStateFilter.running(),
                Optional.empty()
            ).not()
        );
    } else {
        return new MatchStateFilter(MatchState.Running, MatchState.Finished);
    }
}
 
Example 10
Project: rskj   File: HashRateCalculatorTest.java   View source code 6 votes vote down vote up
@Test
public void calculateNetHashRate() {
    long ts = System.currentTimeMillis() / 1000L;
    Mockito.when(blockHeader.getTimestamp()).thenReturn(ts);

    Mockito.when(blockHeader.getCoinbase())
            .thenReturn(NOT_MY_COINBASE)
            .thenReturn(FAKE_COINBASE)
            .thenReturn(FAKE_COINBASE)
            .thenReturn(NOT_MY_COINBASE);

    Mockito.when(block.getCumulativeDifficulty()).thenReturn(BigInteger.ONE);

    HashRateCalculator hashRateCalculator = new HashRateCalculatorMining(blockStore, new RskCustomCache<>(1000L), FAKE_COINBASE);
    BigInteger hashRate = hashRateCalculator.calculateNetHashRate(Duration.ofHours(1));

    Assert.assertEquals(hashRate, new BigInteger("+4"));
}
 
Example 11
Project: db-queue   File: QueueActorDaoTest.java   View source code 6 votes vote down vote up
@Test
public void reenqueue_should_reset_attempts() throws Exception {
    QueueLocation location = generateUniqueLocation();
    String actor = "abc123";
    Long enqueueId = executeInTransaction(() ->
            queueDao.enqueue(location, new EnqueueParams<String>().withActor(actor)));
    executeInTransaction(() -> {
        jdbcTemplate.update("update " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " set attempt=10 where id=" + enqueueId);
    });

    jdbcTemplate.query("select * from " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " where id=" + enqueueId, rs -> {
        Assert.assertThat(rs.next(), equalTo(true));
        Assert.assertThat(rs.getLong("attempt"), equalTo(10L));
        return new Object();
    });

    Boolean reenqueueResult = executeInTransaction(() ->
            queueActorDao.reenqueue(location, actor, Duration.ofHours(1L)));

    Assert.assertThat(reenqueueResult, equalTo(true));
    jdbcTemplate.query("select * from " + QueueDatabaseInitializer.DEFAULT_TABLE_NAME + " where id=" + enqueueId, rs -> {
        Assert.assertThat(rs.next(), equalTo(true));
        Assert.assertThat(rs.getLong("attempt"), equalTo(0L));
        return new Object();
    });
}
 
Example 12
Project: future   File: TraneIOFutureBenchmark.java   View source code 5 votes vote down vote up
@Benchmark
public Void ensureConstN() throws CheckedFutureException {
  Future<Void> f = constVoidFuture;
  for (int i = 0; i < N.n; i++)
    f = f.ensure(ensureF);
  return f.get(Duration.ofMillis(Long.MAX_VALUE));
}
 
Example 13
Project: db-queue   File: QueueConfigsReaderTest.java   View source code 5 votes vote down vote up
@Test
public void should_read_full_config() throws Exception {
    QueueConfigsReader queueConfigsReader = new QueueConfigsReader("q");
    Collection<QueueConfig> configs = queueConfigsReader.parse(fileSystem.write(
            "q.testQueue.table=foo",
            "q.testQueue.between-task-timeout=PT0.1S",
            "q.testQueue.no-task-timeout=PT5S",
            "q.testQueue.fatal-crash-timeout=PT1H",
            "q.testQueue.thread-count=3",
            "q.testQueue.retry-type=linear",
            "q.testQueue.retry-interval=PT30S",
            "q.testQueue.processing-mode=use-external-executor",
            "q.testQueue.additional-settings.custom=val1"
    ));
    assertThat(configs, equalTo(Collections.singletonList(
            createConfig("foo", "testQueue",
                    QueueSettings.builder()
                            .withBetweenTaskTimeout(Duration.ofMillis(100L))
                            .withNoTaskTimeout(Duration.ofSeconds(5L))
                            .withThreadCount(3)
                            .withFatalCrashTimeout(Duration.ofHours(1))
                            .withRetryType(TaskRetryType.LINEAR_BACKOFF)
                            .withRetryInterval(Duration.ofSeconds(30))
                            .withProcessingMode(ProcessingMode.USE_EXTERNAL_EXECUTOR)
                            .withAdditionalSettings(new LinkedHashMap<String, String>() {{
                                put("custom", "val1");
                            }})
                            .build()))));
}
 
Example 14
Project: micrometer   File: FunctionTimerSample.java   View source code 5 votes vote down vote up
/**
 * For Atlas: http://localhost:7101/api/v1/graph?q=name,ftimer,:eq,:dist-avg,name,timer,:eq,:dist-avg,1,:axis&s=e-5m&l=0
 */
public static void main(String[] args) {
    MeterRegistry registry = SampleConfig.myMonitoringSystem();

    Timer timer = Timer.builder("timer")
        .publishPercentiles(0.5, 0.95)
        .register(registry);

    Object placeholder = new Object();
    AtomicLong totalTimeNanos = new AtomicLong(0);
    AtomicLong totalCount = new AtomicLong(0);

    FunctionTimer.builder("ftimer", placeholder, p -> totalCount.get(), p -> totalTimeNanos.get(), TimeUnit.NANOSECONDS)
        .register(registry);

    RandomEngine r = new MersenneTwister64(0);
    Normal incomingRequests = new Normal(0, 1, r);
    Normal duration = new Normal(250, 50, r);

    AtomicInteger latencyForThisSecond = new AtomicInteger(duration.nextInt());
    Flux.interval(Duration.ofSeconds(1))
        .doOnEach(d -> latencyForThisSecond.set(duration.nextInt()))
        .subscribe();

    // the potential for an "incoming request" every 10 ms
    Flux.interval(Duration.ofMillis(10))
        .doOnEach(d -> {
            if (incomingRequests.nextDouble() + 0.4 > 0) {
                // pretend the request took some amount of time, such that the time is
                // distributed normally with a mean of 250ms
                timer.record(latencyForThisSecond.get(), TimeUnit.MILLISECONDS);
                totalCount.incrementAndGet();
                totalTimeNanos.addAndGet((long) TimeUtils.millisToUnit(latencyForThisSecond.get(), TimeUnit.NANOSECONDS));
            }
        })
        .blockLast();
}
 
Example 15
Project: reactive-spring5-example   File: CircuitBreakerConfiguration.java   View source code 5 votes vote down vote up
@Bean
public CircuitBreaker ipServiceCircuitBreaker() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .waitDurationInOpenState(Duration.ofMinutes(5))
            .ringBufferSizeInClosedState(100)
            .ringBufferSizeInHalfOpenState(30)
            .failureRateThreshold(10)
            .build();
    return CircuitBreaker.of("ipService", config);
}
 
Example 16
Project: bluemix-liberty-microprofile-demo   File: HashMapReservationDaoTest.java   View source code 5 votes vote down vote up
@Test
public void testGetReservationsShiftLeftByDurationAndRightByDoubleDuration() throws Exception {
	Reservation reservation = createAndSaveTestReservation(BASIC_RESERVATION_START_TIME, BASIC_RESERVATION_DURATION);
	
	// the requested start time is BASIC_RESERVATION_DURATION early
	LocalTime requestedTime = BASIC_RESERVATION_START_TIME.minus(BASIC_RESERVATION_DURATION);
	// the requested duration is tripled BASIC_RESERVATION_DURATION
	Duration requestedDuration = BASIC_RESERVATION_DURATION.multipliedBy(3);
	Set<Reservation> reservations = reservationDao.getReservations(RESERVATION_VENUE, BASIC_RESERVATION_DATE,
			requestedTime, requestedDuration);
	assertNotNull(reservations);
	assertEquals(1, reservations.size());
	assertTrue(reservations.contains(reservation));
}
 
Example 17
Project: rskj   File: BlockProcessResult.java   View source code 5 votes vote down vote up
public BlockProcessResult(boolean additionalValidations, Map<ByteArrayWrapper, ImportResult> result, String blockHash, Duration processingTime) {
    this.additionalValidationsOk = additionalValidations;
    this.result = result;
    if (processingTime.compareTo(LOG_TIME_LIMIT) >= 0) {
        logResult(blockHash, processingTime);
    }
}
 
Example 18
Project: jdk8u-jdk   File: TCKDuration.java   View source code 5 votes vote down vote up
@Test(dataProvider="MinusMillis")
public void minusMillis_long(long seconds, int nanos, long amount, long expectedSeconds, int expectedNanoOfSecond) {
    Duration t = Duration.ofSeconds(seconds, nanos);
    t = t.minusMillis(amount);
    assertEquals(t.getSeconds(), expectedSeconds);
    assertEquals(t.getNano(), expectedNanoOfSecond);
}
 
Example 19
Project: CalendarFX   File: DayViewEditController.java   View source code 5 votes vote down vote up
private boolean isMinimumDuration(Entry<?> entry, LocalDateTime timeA,
                                  LocalDateTime timeB) {
    Duration minDuration = entry.getMinimumDuration().abs();
    if (minDuration != null) {
        Duration duration = Duration.between(timeA, timeB).abs();
        if (duration.minus(minDuration).isNegative()) {
            return false;
        }
    }

    return true;
}
 
Example 20
Project: athena   File: LatencyConstraintTest.java   View source code 5 votes vote down vote up
/**
 * Tests the path latency is less than the supplied constraint.
 */
@Test
public void testLessThanLatency() {
    sut = new LatencyConstraint(Duration.of(10, ChronoUnit.MICROS));

    assertThat(sut.validate(path, resourceContext), is(true));
}
 
Example 21
Project: jtier-ctx   File: Life.java   View source code 5 votes vote down vote up
Optional<Duration> timeRemaining() {
    this.lock.lock();
    try {
        final Timeout t = this.timeout.get();
        if (t == null) {
            return Optional.empty();
        }
        else {
            return Optional.of(Duration.between(Instant.now(), t.finishAt()));
        }
    } finally {
        this.lock.unlock();
    }
}
 
Example 22
Project: micrometer   File: TimerTest.java   View source code 5 votes vote down vote up
@Test
@DisplayName("record durations")
default void recordDuration(MeterRegistry registry) {
    Timer t = registry.timer("myTimer");
    t.record(Duration.ofMillis(42));
    clock(registry).add(step());

    assertAll(() -> assertEquals(1L, t.count()),
        () -> assertEquals(42, t.totalTime(TimeUnit.MILLISECONDS), 1.0e-12));
}
 
Example 23
Project: Mastering-Java-9   File: DumpProcessToLog.java   View source code 5 votes vote down vote up
public static void dump(ProcessHandle handle) {
    ProcessHandle.Info info = handle.info();
    StringBuffer sb = new StringBuffer();
    sb.append("Command: " + info.command().orElse("??") + "\n");
    sb.append("Command Line: " + info.commandLine().orElse("not present") + "\n");
    sb.append("Arguments: " + String.join(" ", info.arguments().orElse(new String[0])) + "\n");
    sb.append("Number of commandLine: " + info.arguments().orElse(new String[0]).length + "\n");
    sb.append("CPU: " + info.totalCpuDuration().orElse(Duration.ZERO) + "\n");
    sb.append("Start time: " + info.startInstant().orElse(Instant.EPOCH) + "\n");
    sb.append("User: " + info.user().orElse("??") + "\n");
    sb.append("Pid: " + handle.getPid() + "\n");
    sb.append("Children" + "\n");
    handle.children().forEach(child -> sb.append("child pid:" + child.getPid() + "\n"));
    sb.append("Descendants" + "\n");
    handle.descendants().forEach(descendant -> sb.append("descendant pid:" + descendant.getPid() + "\n"));

    handle.parent().ifPresentOrElse(parent -> sb.append("Parent: " + parent.info()), () -> sb.append("no parent\n"));

    if (handle.parent().isPresent() &&
            handle.parent().get().info().startInstant().isPresent() &&
            handle.info().startInstant().isPresent()) {
        sb.append("Parent started me after " +
                Duration.between(handle.parent().get().info().startInstant().get(),
                        handle.info().startInstant().get()).toMillis() + "ms" + "\n");
    }
    sb.append("toString " + handle.info().toString() + "\n");

    log.log(DEBUG, sb.toString());
}
 
Example 24
Project: openjdk-jdk10   File: TCKDuration.java   View source code 5 votes vote down vote up
@Test
public void factory_seconds_long() {
    for (long i = -2; i <= 2; i++) {
        Duration t = Duration.ofSeconds(i);
        assertEquals(t.getSeconds(), i);
        assertEquals(t.getNano(), 0);
    }
}
 
Example 25
Project: async-sqs   File: MessageAcknowledger.java   View source code 5 votes vote down vote up
public MessageAcknowledger(SqsQueue<T> sqsQueue, String receiptId, Instant expirationTime) {
    this.expirationTime = expirationTime;
    this.sqsQueue = sqsQueue;
    this.receiptId = receiptId;
    this.ackModeSingle = SingleSubject.create();
    this.ackingComplete = CompletableSubject.create();

    Duration duration = Duration.between(Instant.now(), expirationTime);
    Completable.timer(duration.toMillis(), TimeUnit.MILLISECONDS).subscribe(this::ignore);
}
 
Example 26
Project: aws-sdk-java-v2   File: ValidationUtils.java   View source code 5 votes vote down vote up
/**
 * Asserts that the given duration is positive (non-negative and non-zero).
 *
 * @param duration Number to validate
 * @param fieldName Field name to display in exception message if not positive.
 * @return Duration if positive.
 */
public static Duration assertIsPositive(Duration duration, String fieldName) {
    assertNotNull(duration, fieldName);
    if (duration.isNegative() || duration.isZero()) {
        throw new IllegalArgumentException(String.format("%s must be positive", fieldName));
    }
    return duration;
}
 
Example 27
Project: CraftoDB   File: Row.java   View source code 5 votes vote down vote up
/** TODO: Documentation */
public Duration getDuration(Column column, DurationUnit unit) throws NoSuchColumnException, NoSuchElementException {
	DBUtil.notNull(unit, "The unit must not be null: " + unit);

	DBUtil.notNull(column, "The column must not be null: " + column);
	return this.getDuration(column.getName(), unit);
}
 
Example 28
Project: ProjectAres   File: TimeUtils.java   View source code 5 votes vote down vote up
public static long toUnit(TemporalUnit unit, Duration duration) {
    switch((ChronoUnit) unit) {
        case NANOS:     return duration.toNanos();
        case MICROS:    return toMicros(duration);
        case MILLIS:    return duration.toMillis();
        case SECONDS:   return duration.getSeconds();
    }

    if(unit.getDuration().getNano() == 0) {
        return duration.getSeconds() / unit.getDuration().getSeconds();
    }

    throw new IllegalArgumentException("Unsupported sub-second unit " + unit);
}
 
Example 29
Project: aws-sdk-java-v2   File: ConnectionPoolMaxConnectionsIntegrationTest.java   View source code 5 votes vote down vote up
@Test(timeout = 60 * 1000)
public void leasing_a_new_connection_fails_with_connection_pool_timeout() throws Exception {

    String localhostEndpoint = "http://localhost:" + server.getPort();

    AmazonHttpClient httpClient = HttpTestUtils.testClientBuilder()
                                               .clientExecutionTimeout(null)
                                               .retryPolicy(RetryPolicy.NONE)
                                               .httpClient(ApacheSdkHttpClientFactory.builder()
                                                                                     .connectionTimeout(
                                                                                             Duration.ofMillis(100))
                                                                                     .maxConnections(1)
                                                                                     .build()
                                                                                     .createHttpClient())
                                               .build();

    Request<?> request = new EmptyHttpRequest(localhostEndpoint, HttpMethodName.GET);

    // Block the first connection in the pool with this request.
    httpClient.requestExecutionBuilder()
              .request(request)
              .originalRequest(NoopTestAwsRequest.builder().build())
              .executionContext(executionContext(SdkHttpFullRequestAdapter.toHttpFullRequest(request)))
              .execute(new EmptyAWSResponseHandler());

    try {
        // A new connection will be leased here which would fail in
        // ConnectionPoolTimeoutException.
        httpClient.requestExecutionBuilder()
                  .request(request)
                  .originalRequest(NoopTestAwsRequest.builder().build())
                  .executionContext(executionContext(SdkHttpFullRequestAdapter.toHttpFullRequest(request)))
                  .execute();
        Assert.fail("Connection pool timeout exception is expected!");
    } catch (SdkClientException e) {
        Assert.assertTrue(e.getCause() instanceof ConnectionPoolTimeoutException);
    }
}
 
Example 30
Project: micrometer   File: StringToDurationConverter.java   View source code 5 votes vote down vote up
private static Optional<Duration> tryParse(String time, String unit, Function<Long, Duration> toDuration) {
    if (time.endsWith(unit)) {
        String trim = time.substring(0, time.lastIndexOf(unit)).trim();
        try {
            return Optional.of(toDuration.apply(Long.parseLong(trim)));
        } catch(NumberFormatException ignore) {
            return Optional.empty();
        }
    }
    return Optional.empty();
}
 
Example 31
Project: stail   File: Stail.java   View source code 5 votes vote down vote up
private static String getShardIterator(AmazonKinesis client, String stream, Shard shard, String start) {
    GetShardIteratorRequest getShardIteratorRequest = new GetShardIteratorRequest();
    getShardIteratorRequest.setStreamName(stream);
    getShardIteratorRequest.setShardId(shard.getShardId());

    if (!Strings.isNullOrEmpty(start)) {
        getShardIteratorRequest.setShardIteratorType(ShardIteratorType.AT_TIMESTAMP);
        getShardIteratorRequest.setTimestamp(new Date(System.currentTimeMillis() - Duration.parse(start).toMillis()));
    } else {
        getShardIteratorRequest.setShardIteratorType(ShardIteratorType.LATEST);
    }

    GetShardIteratorResult getShardIteratorResult = client.getShardIterator(getShardIteratorRequest);
    return getShardIteratorResult.getShardIterator();
}
 
Example 32
Project: ProjectAres   File: FlagParser.java   View source code 5 votes vote down vote up
public Post parsePost(Element el) throws InvalidXMLException {
    checkDeprecatedFilter(el);

    final Optional<TeamFactory> owner = teamParser.property(el, "owner").optional();
    boolean sequential = XMLUtils.parseBoolean(el.getAttribute("sequential"), false);
    boolean permanent = XMLUtils.parseBoolean(el.getAttribute("permanent"), false);
    double pointsPerSecond = XMLUtils.parseNumber(el.getAttribute("points-rate"), Double.class, 0D);
    Filter pickupFilter = filterParser.property(el, "pickup-filter").optional(StaticFilter.ALLOW);

    Duration recoverTime = XMLUtils.parseDuration(Node.fromAttr(el, "recover-time", "return-time"), Post.DEFAULT_RETURN_TIME);
    Duration respawnTime = XMLUtils.parseDuration(el.getAttribute("respawn-time"), null);
    Double respawnSpeed = XMLUtils.parseNumber(el.getAttribute("respawn-speed"), Double.class, (Double) null);
    ImmutableList<PointProvider> returnPoints = ImmutableList.copyOf(pointParser.parse(el, new PointProviderAttributes()));

    if(respawnTime == null && respawnSpeed == null) {
        respawnSpeed = Post.DEFAULT_RESPAWN_SPEED;
    }

    if(respawnTime != null && respawnSpeed != null) {
        throw new InvalidXMLException("post cannot have both respawn-time and respawn-speed", el);
    }

    if(returnPoints.isEmpty()) {
        throw new InvalidXMLException("post must have at least one point provider", el);
    }

    return context.features().define(el, Post.class, new PostImpl(owner, recoverTime, respawnTime, respawnSpeed, returnPoints, sequential, permanent, pointsPerSecond, pickupFilter));
}
 
Example 33
Project: dcos2humio   File: ElasticBeatConfigurationGenerator.java   View source code 5 votes vote down vote up
private boolean wasTaskRecentlyRunning(Task task) {
    if (task.getState().equals("TASK_RUNNING")) {
        return true;
    }
    final Instant deadline = clock.instant().minus(Duration.ofHours(1));
    return Instant.ofEpochSecond(task.getStatuses().get(task.getStatuses().size() - 1).getTimestamp().longValue()).isAfter(deadline);

}
 
Example 34
Project: sqs-utils   File: VisibilityTimeoutExtenderTest.java   View source code 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    HashMap<String, Object> headerMap = new HashMap<>();
    headerMap.put("ReceiptHandle", "rhd");
    GenericMessage<Object> message = new GenericMessage<>(new Object(), new MessageHeaders(
            headerMap));
    uut = new VisibilityTimeoutExtender(sqsClient, Duration.ofMinutes(10), message, "queue");
}
 
Example 35
Project: jspare-vertx-ms-blueprint   File: Stopwatch.java   View source code 5 votes vote down vote up
public Stopwatch print() {
	if (log.isDebugEnabled()) {
		log.debug("Started at: {}", start.toString());
		log.debug("Stoped at: {}", stop.toString());
		log.debug("Time elapssed: {}ms", Duration.between(start, stop).toMillis());
	}
	return this;
}
 
Example 36
Project: micrometer   File: PrometheusTimer.java   View source code 5 votes vote down vote up
PrometheusTimer(Id id, Clock clock, HistogramConfig histogramConfig, PauseDetector pauseDetector) {
    super(id, clock, histogramConfig, pauseDetector, TimeUnit.SECONDS);
    this.max = new TimeDecayingMax(clock, histogramConfig);

    this.percentilesHistogram = new TimeWindowLatencyHistogram(clock,
        HistogramConfig.builder()
            .histogramExpiry(Duration.ofDays(1825)) // effectively never roll over
            .histogramBufferLength(1)
            .build()
            .merge(histogramConfig), pauseDetector);
}
 
Example 37
Project: tableschema-java   File: FieldConstraintsTest.java   View source code 5 votes vote down vote up
@Test
public void testMinimumAndMaximumDuration(){
    Map<String, Object> violatedConstraints = null;
    
    final String DURATION_STRING_MINIMUM = "P2DT3H4M";
    final String DURATION_STRING_MAXIMUM = "P2DT5H4M";
    
    Duration durationMin = Duration.parse(DURATION_STRING_MINIMUM);
    Duration durationMax = Duration.parse(DURATION_STRING_MAXIMUM);
    
    Map<String, Object> constraints = new HashMap();
    constraints.put(Field.CONSTRAINT_KEY_MINIMUM, durationMin);
    constraints.put(Field.CONSTRAINT_KEY_MAXIMUM, durationMax);
    
    Field field = new Field("test", Field.FIELD_TYPE_DURATION, null, null, null, constraints);
    
    Duration duration = Duration.parse("P2DT4H4M");
    violatedConstraints = field.checkConstraintViolations(duration);
    Assert.assertTrue(violatedConstraints.isEmpty());
    
    Duration durationEqualMin = Duration.parse(DURATION_STRING_MINIMUM);
    violatedConstraints = field.checkConstraintViolations(durationEqualMin);
    Assert.assertTrue(violatedConstraints.isEmpty());
    
    Duration durationEqualMax = Duration.parse(DURATION_STRING_MAXIMUM);
    violatedConstraints = field.checkConstraintViolations(durationEqualMax);
    Assert.assertTrue(violatedConstraints.isEmpty());
    
    Duration durationLesserThanMinBy1Min = Duration.parse("P2DT3H3M");
    violatedConstraints = field.checkConstraintViolations(durationLesserThanMinBy1Min);
    Assert.assertTrue(violatedConstraints.containsKey(Field.CONSTRAINT_KEY_MINIMUM));
    
    Duration durationGreaterThanMaxBy1Min = Duration.parse("P2DT5H5M");
    violatedConstraints = field.checkConstraintViolations(durationGreaterThanMaxBy1Min);
    Assert.assertTrue(violatedConstraints.containsKey(Field.CONSTRAINT_KEY_MAXIMUM));
}
 
Example 38
Project: Spring-5.0-Cookbook   File: EmployeeBatchStreamServiceImpl.java   View source code 5 votes vote down vote up
@Override
public Flux<String> getTimedFirstNames() {
	Function<Employee, String> firstNames = (e) -> e.getFirstName();
	Supplier<Flux<String>> deferredTask = ()->Flux.fromIterable(employeeDaoImpl.getEmployees()).map(firstNames);
    Flux<String> timedDefer = Flux.defer(deferredTask).log().timeout(Duration.ofMillis(320));
	return timedDefer;
}
 
Example 39
Project: VoxelGamesLibv2   File: AbstractGame.java   View source code 5 votes vote down vote up
@Override
public void endGame(@Nullable Team winnerTeam, @Nullable User winnerUser) {
    // stop timer
    duration = Duration.between(startTime, LocalDateTime.now());

    log.finer("end game");

    handleElo(winnerTeam, winnerUser);
    //TODO handle stats
    if (winnerTeam != null) {
        Bukkit.getPluginManager()
                .callEvent(new GameEndEvent(this, winnerTeam.getPlayers(), duration, aborted));
    } else if (winnerUser != null) {
        List<User> winningUsers = new ArrayList<>();
        winningUsers.add(winnerUser);

        Bukkit.getPluginManager().callEvent(new GameEndEvent(this, winningUsers, duration, aborted));
    } else {
        Bukkit.getPluginManager()
                .callEvent(new GameEndEvent(this, new ArrayList<>(), duration, aborted));
    }

    if (!aborted) {
        broadcastMessage(LangKey.GAME_END);
    }

    end();
}
 
Example 40
Project: yggdrasil-mock   File: RateLimiter.java   View source code 4 votes vote down vote up
public void setLimitDuration(Duration limitDuration) {
	this.limitDuration = limitDuration;
}