Java Code Examples for java.time.Duration#ZERO

The following examples show how to use java.time.Duration#ZERO . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: emodb   File: TestDefaultJobService.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setUp() throws Exception {
    LifeCycleRegistry lifeCycleRegistry = mock(LifeCycleRegistry.class);
    _queueService = mock(QueueService.class);
    _jobHandlerRegistry = new DefaultJobHandlerRegistry();
    _jobStatusDAO = new InMemoryJobStatusDAO();
    _testingServer = new TestingServer();
    _curator = CuratorFrameworkFactory.builder()
            .connectString(_testingServer.getConnectString())
            .retryPolicy(new RetryNTimes(3, 100))
            .build();

    _curator.start();

    _service = new DefaultJobService(
            lifeCycleRegistry, _queueService, "testqueue", _jobHandlerRegistry, _jobStatusDAO, _curator,
            1, Duration.ZERO, 100, Duration.ofHours(1));
}
 
Example 2
@Test
public void blendedDelay() {
    final Delay delay = Blended.of().add(Constant.of().delay(Duration.ofSeconds(5)).timeout(Duration.ofSeconds(20)).build())
        .add(ShiftByMultipleOf.shiftedOf().delay(Duration.ofSeconds(5)).timeout(Duration.ofSeconds(220)).build()).build();
    Duration next = Duration.ZERO;
    long accrued = 0L;
    int attempt = 1;
    while ((next = delay.nextDelay(attempt)) != Duration.ZERO) {
        attempt++;
        accrued += next.getSeconds();
    }
    assertThat(5 * 4 + 40 + 90 + 150 + 220).isEqualTo(accrued);
    assertThat(9).isEqualTo(attempt);
}
 
Example 3
@Override
public SpaceUsageCheckParams paramsFor(File dir) {
  return new SpaceUsageCheckParams(dir,
      MockSpaceUsageSource.unlimited(),
      Duration.ZERO,
      SpaceUsagePersistence.None.INSTANCE
  );
}
 
Example 4
Source Project: aws-sdk-java-v2   File: ClockSkew.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calculate the time skew between a client and server date. This value has the same semantics of
 * {@link HttpClientDependencies#timeOffset()}. Positive values imply the client clock is "fast" and negative values imply
 * the client clock is "slow".
 */
public static Duration getClockSkew(Instant clientTime, Instant serverTime) {
    if (clientTime == null || serverTime == null) {
        // If we do not have a client or server time, 0 is the safest skew to apply
        return Duration.ZERO;
    }

    return Duration.between(serverTime, clientTime);
}
 
Example 5
private Duration timeSinceFirstMsg() {

            Duration sinceFirst = Duration.ZERO;

            if (!toSend.isEmpty()) {
                Instant firstTimestamp = toSend.get(0).message.getMessage().getTimestamp();
                Instant nowTimestamp = times.getTime();

                if (firstTimestamp.compareTo(nowTimestamp) < 0) {
                    sinceFirst = Duration.between(firstTimestamp, nowTimestamp);
                }
            }

            return sinceFirst;
        }
 
Example 6
@Override
public Duration compute(TeamTask task) {
  Duration total = Duration.ZERO;
  for (Timer timer : task.getTimerList()) {
    total = total.plus(compute(timer));
  }
  return total;
}
 
Example 7
@Test
public void testNotEqualsWrongClass() {
    AmazonDuration test = new AmazonDuration(
        mockSlot,
        Period.ZERO,
        Duration.ZERO);

    assertNotEquals(test, "test");
}
 
Example 8
/** Progress toward a new controller */
private void progressCapture(Competitor dominantTeam, Duration dominantTime) {
  this.capturingTime = this.capturingTime.plus(dominantTime);
  if (!TimeUtils.isShorterThan(this.capturingTime, this.definition.getTimeToCapture())) {
    this.capturingTime = Duration.ZERO;
    this.controllingTeam = this.capturingTeam;
    this.capturingTeam = null;
    if (this.getDefinition().isPermanent()) {
      // The objective is permanent, so the first capture disables it
      this.capturable = false;
    }
  }
}
 
Example 9
Source Project: vespa   File: SessionsMaintainer.java    License: Apache License 2.0 4 votes vote down vote up
SessionsMaintainer(ApplicationRepository applicationRepository, Curator curator, Duration interval) {
    // Start this maintainer immediately. It frees disk space, so if disk goes full and config server
    // restarts this makes sure that cleanup will happen as early as possible
    super(applicationRepository, curator, Duration.ZERO, interval);
    this.hostedVespa = applicationRepository.configserverConfig().hostedVespa();
}
 
Example 10
DebouncedTask(Scheduler scheduler, Runnable runnable) {
    this(scheduler, Duration.ZERO, runnable);
}
 
Example 11
@Test
public void shouldHandleDuration() throws Exception  {
    final Duration o = Duration.ZERO;
    assertEquals(o, serializeDeserialize(mapper, o, Duration.class));
}
 
Example 12
@Override
	public void runSimulation(int steps) throws InvalidNumberOfCubesException {
		prprDrtn = Duration.ZERO;
		calcAccelDrtn = Duration.ZERO;
		calcVelDrtn = Duration.ZERO;
		calcPosDrtn = Duration.ZERO;
		//Set<NBody3DBody> newUniverse;
		long start = System.nanoTime();
		// Map<UUID, CuboidCoordinates> takenCoordiantes = new HashMap<>();
		CuboidCoordinates parentCuboid = new StockCuboidCoordinates();
		for (int i = 0; i < steps; i++) {
			// x in b=2^x, where b is the next power of 2 greater than a
			// int numCuboids = (int) Math.pow(2, 32 - Integer.numberOfLeadingZeros(maxCuboids - 1));
			int numCuboids = 4;
			Collection<CuboidCoordinates> stepCuboids = new StockCuboids(parentCuboid).setupCuboids(numCuboids);
			List<NBody3DBody> newUniverse = new ArrayList<>(universe.size());
			while (!stepCuboids.isEmpty()) {

				sharedQueue.addAll(stepCuboids);

				List<CuboidRunner> runners = new ArrayList<CuboidRunner>();
				for (int r = 0; r < numCuboids; r++) {
					CuboidRunner runner = new CuboidRunner(0.995, 0.001, sharedQueue, resultsQueue, universe);
					runners.add(runner);
				}

				List<Future<UUID>> futures = null;
				try {
					futures = runnerExecutor.invokeAll(runners);
				} catch (InterruptedException e1) {
					System.out.println("ex " + e1.getMessage());
				} finally {
					if (futures != null) {
						resultsQueue.drain(r -> {
//							boolean found = checkIds(futures, r);
//							if (!found) {
//								throw new IllegalStateException("Finished thread did not queue results");
//							}
							try {
								prprDrtn = prprDrtn.plus(r.durations().prepareDrtn());
								calcAccelDrtn = calcAccelDrtn.plus(r.durations().calcAccelDrtn());
								calcVelDrtn = calcVelDrtn.plus(r.durations().calcVelDrtn());
								calcPosDrtn = calcPosDrtn.plus(r.durations().calcPosDrtn());
								// Only count if durations are OK
								stepCuboids.remove(r.coordiantes());
								newUniverse.addAll(r.bodies());
								memSize += r.memUsed();
							} catch (RequestedDurationNotFound e) {
								// Retry
								System.out.println("ex " + e.getMessage());
							}
						});
					}
				}
			}
			universe = newUniverse;
		}
		calculatePerformance(universe.size(), steps);
		overHeadDrtn = Duration.ofNanos(System.nanoTime() - start);
		//printResults(steps);
		shutdownAndAwaitTermination(runnerExecutor);
	}
 
Example 13
Source Project: retry4j   File: NoWaitBackoffStrategy.java    License: MIT License 4 votes vote down vote up
@Override
public Duration getDurationToWait(int numberOfTriesFailed, Duration delayBetweenAttempts) {
    return Duration.ZERO;
}
 
Example 14
Source Project: salespoint   File: DefaultBusinessTime.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void reset() {
	this.duration = Duration.ZERO;
}
 
Example 15
Source Project: incubator-heron   File: TestWordSpout.java    License: Apache License 2.0 4 votes vote down vote up
public TestWordSpout() {
  this(Duration.ZERO);
}
 
Example 16
/**
 * Tests registering a session with a client session manager.
 */
public void testSessionRegisterUnregister() throws Throwable {
  ClientConnection connection = mock(ClientConnection.class);
  when(connection.reset()).thenReturn(connection);
  when(connection.servers()).thenReturn(Collections.singletonList(new Address("localhost", 5000)));
  when(connection.sendAndReceive(any(RegisterRequest.class)))
    .thenReturn(CompletableFuture.completedFuture(RegisterResponse.builder()
      .withSession(1)
      .withLeader(new Address("localhost", 5000))
      .withMembers(Arrays.asList(
        new Address("localhost", 5000),
        new Address("localhost", 5001),
        new Address("localhost", 5002)
      ))
      .withTimeout(1000)
      .build()))
    .thenReturn(CompletableFuture.completedFuture(KeepAliveResponse.builder()
      .withStatus(Response.Status.OK)
      .withLeader(new Address("localhost", 5000))
      .withMembers(Arrays.asList(
        new Address("localhost", 5000),
        new Address("localhost", 5001),
        new Address("localhost", 5002)
      )).build()));

  ClientSessionState state = new ClientSessionState(UUID.randomUUID().toString());
  ThreadContext context = mock(ThreadContext.class);
  Executor executor = new MockExecutor();
  when(context.executor()).thenReturn(executor);

  ClientSessionManager manager = new ClientSessionManager(connection, state, context, ConnectionStrategies.EXPONENTIAL_BACKOFF, Duration.ZERO);
  manager.open().join();

  assertEquals(state.getSessionId(), 1);
  assertEquals(state.getState(), Session.State.OPEN);

  verify(connection, times(2)).reset(new Address("localhost", 5000), Arrays.asList(
    new Address("localhost", 5000),
    new Address("localhost", 5001),
    new Address("localhost", 5002)
  ));

  when(connection.sendAndReceive(any(UnregisterRequest.class)))
    .thenReturn(CompletableFuture.completedFuture(UnregisterResponse.builder()
      .withStatus(Response.Status.OK)
      .build()));

  manager.close().join();

  assertEquals(state.getState(), Session.State.CLOSED);
}
 
Example 17
@Test
@Tag("TODO")
@Order(4)
public void verifyDurationCreatedUsingFluentMethods() {

    // Create a Duration instance
    // TODO: Replace the Duration.ZERO to a duration of 3 hours and 6 seconds.
    //  NOTE: Check the difference between plusSeconds and withSeconds
    //  Check: java.time.Duration.ofHours(int).plusSeconds(int))
    Duration threeHoursAndSixSeconds = Duration.ZERO;

    assertEquals(3,
            threeHoursAndSixSeconds.toHours(),
            "The time duration should include three hours.");

    assertEquals(10806,
            threeHoursAndSixSeconds.getSeconds(),
            "The time duration should include three hours and six seconds in seconds.");
    // NOTE: getSeconds gets full time.


    // Add the Duration to a LocalDateTime
    LocalDateTime tOJDateTime = LocalDateTime.now(terminatorOriginalJudgementDay);

    // TODO: Call a method on tOJDateTime to add the newly created Duration
    //  Check : java.time.LocalDateTime.plus(java.time.temporal.TemporalAmount)
    LocalDateTime calculatedThreeHoursAndSixSecondsLater =
            tOJDateTime;

    //7:14:30 GMT = 2:14:30 in (GMT-5). Adding 3h 6s = 5:14:36 in (GMT-5)
    assertEquals(5,
            calculatedThreeHoursAndSixSecondsLater.getHour(),
            "The hour after 3 hours and six seconds should be 5.");

    assertEquals(14,
            calculatedThreeHoursAndSixSecondsLater.getMinute(),
            "The minute after 3 hours and six seconds should be 14.");

    assertEquals(36,
            calculatedThreeHoursAndSixSecondsLater.getSecond(),
            "The second after 3 hours and six seconds should be 36.");
}
 
Example 18
Source Project: pikatimer   File: Result.java    License: GNU General Public License v3.0 4 votes vote down vote up
public void recalcTimeProperties(){
        if (pendingRecalc){
            
            //System.out.println("Result::recalcTimeProperties for bib " + bib.get());
//            System.out.println(" StartDuration: " + startDuration.toString());
//            System.out.println(" waveStartDuration: " + waveStartDuration.toString());
//            System.out.println(" finishDuration: " + finishDuration.toString());

            if (!startDuration.equals(startDurationProperty.get())) startDurationProperty.set(startDuration);
            if (!waveStartDuration.equals(waveStartDurationProperty.get())) waveStartDurationProperty.set(waveStartDuration);
            
            Duration startOffset = Duration.ZERO;
            if (splitMap.containsKey(0)) {
                startOffset = Duration.ofNanos(splitMap.get(0)).minus(waveStartDuration);
            }
            
            if (!startOffset.equals(startOffsetProperty.get())) startOffsetProperty.set(startOffset);
            
            if (finishDuration.isZero()) {
                finishDurationProperty.setValue(Duration.ofNanos(Long.MAX_VALUE));
                finishTODProperty.setValue(Duration.ofNanos(Long.MAX_VALUE));
            }
            else {
                finishDurationProperty.setValue(finishDuration.minus(startDuration));
                if (finishDuration.toDays()> 0) {
                    finishTODProperty.setValue(finishDuration.minus(Duration.ofDays(finishDuration.toDays())));
                } else finishTODProperty.setValue(finishDuration);
            }

            if (finishDuration.isZero()) finishGunDurationProperty.setValue(Duration.ofNanos(Long.MAX_VALUE));
            else finishGunDurationProperty.setValue(finishDuration.minus(waveStartDuration));
            
            
//            
//            System.out.println(" chipTime: " + finishDurationProperty.get().toString());
//            System.out.println(" gunTime: " + finishGunDurationProperty.get().toString());
            
            // now loop through and fix the splits...
            // missing splits are set to MAX_VALUE
            splitMap.keySet().forEach(splitID -> {
                Duration d;
                if (splitID != 0){
                    d = Duration.ofNanos(splitMap.get(splitID)).minus(startDuration);
                    if (d.isNegative()) d = Duration.ofNanos(Long.MAX_VALUE);
                } else {
                    d = Duration.ofNanos(splitMap.get(splitID));
                }
                if (splitPropertyMap.containsKey(splitID)) splitPropertyMap.get(splitID).set(d);
                else splitPropertyMap.put(splitID, new SimpleObjectProperty(d));
            });    
            
            splitPropertyMap.keySet().forEach(splitID -> {
                if (!splitMap.containsKey(splitID)) splitPropertyMap.get(splitID).set(Duration.ofNanos(Long.MAX_VALUE));
            
            });
            
            revision.set(revision.get() + 1);
            //System.out.println("Result revision is now " + revision.getValue().toString());
            pendingRecalc = false;
        }
    }
 
Example 19
/**
 * Gets the amount of daylight savings in use for the specified instant in this zone.
 * <p>
 * This provides access to historic information on how the amount of daylight
 * savings has changed over time.
 * This is the difference between the standard offset and the actual offset.
 * Typically the amount is zero during winter and one hour during summer.
 * Time-zones are second-based, so the nanosecond part of the duration will be zero.
 * <p>
 * This default implementation calculates the duration from the
 * {@link #getOffset(java.time.Instant) actual} and
 * {@link #getStandardOffset(java.time.Instant) standard} offsets.
 *
 * @param instant  the instant to find the daylight savings for, not null, but null
 *  may be ignored if the rules have a single offset for all instants
 * @return the difference between the standard and actual offset, not null
 */
public Duration getDaylightSavings(Instant instant) {
    if (savingsInstantTransitions.length == 0) {
        return Duration.ZERO;
    }
    ZoneOffset standardOffset = getStandardOffset(instant);
    ZoneOffset actualOffset = getOffset(instant);
    return Duration.ofSeconds(actualOffset.getTotalSeconds() - standardOffset.getTotalSeconds());
}
 
Example 20
Source Project: cactoos   File: Retry.java    License: MIT License 2 votes vote down vote up
/**
 * Ctor.
 * @param fnc Func original
 * @param attempts Maximum number of attempts
 */
public Retry(final Func<X, Y> fnc, final int attempts) {
    this(fnc, attempts, Duration.ZERO);
}