Java 类java.time.Duration 实例源码

项目:spydra    文件:PoolingTest.java   
@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));
}
项目:db-queue    文件:PickTaskDaoTest.java   
@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));
    }
}
项目:conf4j    文件:PeriodicalReloadStrategyTest.java   
@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();
    }
}
项目:ndbc    文件:Config.java   
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;
}
项目:openjdk-jdk10    文件:TCKDuration.java   
@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)
    );
}
项目:micrometer    文件:SampleRegistries.java   
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);
}
项目:Riho    文件:IdeActionListener.java   
@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;
    }
}
项目:ProjectAres    文件:TimeLimitCountdown.java   
@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);
        }
    }
}
项目:ProjectAres    文件:FilterDefinitionParser.java   
@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);
    }
}
项目:rskj    文件:HashRateCalculatorTest.java   
@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"));
}
项目:db-queue    文件:QueueActorDaoTest.java   
@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();
    });
}
项目:future    文件:TraneIOFutureBenchmark.java   
@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));
}
项目:db-queue    文件:QueueConfigsReaderTest.java   
@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()))));
}
项目:micrometer    文件:FunctionTimerSample.java   
/**
 * 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();
}
项目:reactive-spring5-example    文件:CircuitBreakerConfiguration.java   
@Bean
public CircuitBreaker ipServiceCircuitBreaker() {
    CircuitBreakerConfig config = CircuitBreakerConfig.custom()
            .waitDurationInOpenState(Duration.ofMinutes(5))
            .ringBufferSizeInClosedState(100)
            .ringBufferSizeInHalfOpenState(30)
            .failureRateThreshold(10)
            .build();
    return CircuitBreaker.of("ipService", config);
}
项目:bluemix-liberty-microprofile-demo    文件:HashMapReservationDaoTest.java   
@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));
}
项目:rskj    文件:BlockProcessResult.java   
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);
    }
}
项目:jdk8u-jdk    文件:TCKDuration.java   
@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);
}
项目:CalendarFX    文件:DayViewEditController.java   
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;
}
项目:athena    文件:LatencyConstraintTest.java   
/**
 * 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));
}
项目:jtier-ctx    文件:Life.java   
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();
    }
}
项目:micrometer    文件:TimerTest.java   
@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));
}
项目:Mastering-Java-9    文件:DumpProcessToLog.java   
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());
}
项目:openjdk-jdk10    文件:TCKDuration.java   
@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);
    }
}
项目:async-sqs    文件:MessageAcknowledger.java   
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);
}
项目:aws-sdk-java-v2    文件:ValidationUtils.java   
/**
 * 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;
}
项目:CraftoDB    文件:Row.java   
/** 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);
}
项目:ProjectAres    文件:TimeUtils.java   
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);
}
项目:aws-sdk-java-v2    文件:ConnectionPoolMaxConnectionsIntegrationTest.java   
@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);
    }
}
项目:micrometer    文件:StringToDurationConverter.java   
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();
}
项目:stail    文件:Stail.java   
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();
}
项目:ProjectAres    文件:FlagParser.java   
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));
}
项目:dcos2humio    文件:ElasticBeatConfigurationGenerator.java   
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);

}
项目:sqs-utils    文件:VisibilityTimeoutExtenderTest.java   
@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");
}
项目:jspare-vertx-ms-blueprint    文件:Stopwatch.java   
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;
}
项目:micrometer    文件:PrometheusTimer.java   
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);
}
项目:tableschema-java    文件:FieldConstraintsTest.java   
@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));
}
项目:Spring-5.0-Cookbook    文件:EmployeeBatchStreamServiceImpl.java   
@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;
}
项目:VoxelGamesLibv2    文件:AbstractGame.java   
@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();
}
项目:yggdrasil-mock    文件:RateLimiter.java   
public void setLimitDuration(Duration limitDuration) {
    this.limitDuration = limitDuration;
}