java.time.Clock Java Examples

The following examples show how to use java.time.Clock. 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: TCKThaiBuddhistChronology.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_dateNow(){
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now()) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(ZoneId.systemDefault())) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(Clock.systemDefaultZone())) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistDate.now(Clock.systemDefaultZone().getZone())) ;

    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ;

    ZoneId zoneId = ZoneId.of("Europe/Paris");
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId))) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistDate.now(Clock.system(zoneId))) ;
    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(zoneId), ThaiBuddhistDate.now(Clock.system(zoneId).getZone())) ;

    assertEquals(ThaiBuddhistChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), ThaiBuddhistChronology.INSTANCE.dateNow(Clock.systemUTC())) ;
}
 
Example #2
Source File: TCKClock_Tick.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void test__equals() {
    Clock a = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500));
    Clock b = Clock.tick(Clock.system(PARIS), Duration.ofMillis(500));
    assertEquals(a.equals(a), true);
    assertEquals(a.equals(b), true);
    assertEquals(b.equals(a), true);
    assertEquals(b.equals(b), true);

    Clock c = Clock.tick(Clock.system(MOSCOW), Duration.ofMillis(500));
    assertEquals(a.equals(c), false);

    Clock d = Clock.tick(Clock.system(PARIS), Duration.ofMillis(499));
    assertEquals(a.equals(d), false);

    assertEquals(a.equals(null), false);
    assertEquals(a.equals("other type"), false);
    assertEquals(a.equals(Clock.systemUTC()), false);
}
 
Example #3
Source File: TCKMinguoChronology.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void test_dateNow(){
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now()) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(ZoneId.systemDefault())) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone())) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoDate.now(Clock.systemDefaultZone().getZone())) ;

    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(ZoneId.systemDefault())) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone())) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(), MinguoChronology.INSTANCE.dateNow(Clock.systemDefaultZone().getZone())) ;

    ZoneId zoneId = ZoneId.of("Europe/Paris");
    assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId))) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoChronology.INSTANCE.dateNow(Clock.system(zoneId).getZone())) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId))) ;
    assertEquals(MinguoChronology.INSTANCE.dateNow(zoneId), MinguoDate.now(Clock.system(zoneId).getZone())) ;

    assertEquals(MinguoChronology.INSTANCE.dateNow(ZoneId.of(ZoneOffset.UTC.getId())), MinguoChronology.INSTANCE.dateNow(Clock.systemUTC())) ;
}
 
Example #4
Source File: StatusHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRespondHttp200OkWithExpectedBody() throws JsonProcessingException {
    // given
    final ZonedDateTime testTime = ZonedDateTime.now(Clock.systemUTC());
    statusHandler = new StatusHandler(Arrays.asList(healthCheck, healthCheck, healthCheck), jacksonMapper);

    given(routingContext.response()).willReturn(httpResponse);
    given(healthCheck.name()).willReturn("application", "db", "other");
    given(healthCheck.status()).willReturn(StatusResponse.of("ready", null),
            StatusResponse.of("UP", testTime), StatusResponse.of("DOWN", testTime));

    // when
    statusHandler.handle(routingContext);

    // then
    final Map<String, StatusResponse> expectedMap = new TreeMap<>();
    expectedMap.put("application", StatusResponse.of("ready", null));
    expectedMap.put("db", StatusResponse.of("UP", testTime));
    expectedMap.put("other", StatusResponse.of("DOWN", testTime));

    verify(httpResponse).end(eq(mapper.writeValueAsString(expectedMap)));
}
 
Example #5
Source File: ScanParticipationService.java    From emodb with Apache License 2.0 6 votes vote down vote up
@Inject
public ScanParticipationService(List<ScheduledDailyScanUpload> scheduledScans, final StashStateListener stashStateListener,
                                LifeCycleRegistry lifeCycleRegistry, Clock clock) {
    _scheduledScans = scheduledScans;
    _clock = clock;

    // Create a runnable which announces scan participation when called
    _notificationRunnable = new Runnable() {
        @Override
        public void run() {
            stashStateListener.announceStashParticipation();
        }
    };

    lifeCycleRegistry.manage(this);
}
 
Example #6
Source File: InMemoryWebSessionStoreTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void retrieveExpiredSession() {
	WebSession session = this.store.createWebSession().block();
	assertNotNull(session);
	session.getAttributes().put("foo", "bar");
	session.save().block();

	String id = session.getId();
	WebSession retrieved = this.store.retrieveSession(id).block();
	assertNotNull(retrieved);
	assertSame(session, retrieved);

	// Fast-forward 31 minutes
	this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofMinutes(31)));
	WebSession retrievedAgain = this.store.retrieveSession(id).block();
	assertNull(retrievedAgain);
}
 
Example #7
Source File: TCKZonedDateTime.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
public void now_Clock_allSecsInDay_utc() {
    for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
        Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
        ZonedDateTime test = ZonedDateTime.now(clock);
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonth(), Month.JANUARY);
        assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2));
        assertEquals(test.getHour(), (i / (60 * 60)) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
        assertEquals(test.getNano(), 123456789);
        assertEquals(test.getOffset(), ZoneOffset.UTC);
        assertEquals(test.getZone(), ZoneOffset.UTC);
    }
}
 
Example #8
Source File: TCKZonedDateTime.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_ZoneId() {
    ZoneId zone = ZoneId.of("UTC+01:02:03");
    ZonedDateTime expected = ZonedDateTime.now(Clock.system(zone));
    ZonedDateTime test = ZonedDateTime.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = ZonedDateTime.now(Clock.system(zone));
        test = ZonedDateTime.now(zone);
    }
    assertEquals(test, expected);
}
 
Example #9
Source File: KinesisMessageLogReceiverEndpointFactory.java    From synapse with Apache License 2.0 5 votes vote down vote up
public KinesisMessageLogReceiverEndpointFactory(final MessageInterceptorRegistry interceptorRegistry,
                                                final KinesisAsyncClient kinesisClient,
                                                final ExecutorService kinesisMessageLogExecutorService,
                                                final ApplicationEventPublisher eventPublisher,
                                                final Clock clock,
                                                final Marker marker) {
    this.interceptorRegistry = interceptorRegistry;
    this.kinesisClient = kinesisClient;
    this.executorService = kinesisMessageLogExecutorService;
    this.eventPublisher = eventPublisher;
    this.clock = clock;
    this.marker = marker;
}
 
Example #10
Source File: BackoffBuilder.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
BackoffBuilder() {
    this.initial = 0;
    this.max = 0;
    this.mandatoryStop = 0;
    this.clock = Clock.systemDefaultZone();
    this.backoffIntervalNanos = 0;
    this.maxBackoffIntervalNanos = 0;
}
 
Example #11
Source File: CuratorDatabaseClient.java    From vespa with Apache License 2.0 5 votes vote down vote up
public CuratorDatabaseClient(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, boolean useCache) {
    this.nodeSerializer = new NodeSerializer(flavors);
    this.zone = zone;
    this.db = new CuratorDatabase(curator, root, useCache);
    this.clock = clock;
    this.provisionIndexCounter = new CuratorCounter(curator, root.append("provisionIndexCounter").getAbsolute());
    initZK();
}
 
Example #12
Source File: ProtectedStorageEntryTest.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void isValidForAddOperation_BadSignature() throws NoSuchAlgorithmException {
    KeyPair ownerKeys = TestUtils.generateKeyPair();

    ProtectedStoragePayload protectedStoragePayload = new ProtectedStoragePayloadStub(ownerKeys.getPublic());
    ProtectedStorageEntry protectedStorageEntry =
            new ProtectedStorageEntry(protectedStoragePayload, ownerKeys.getPublic(),
                    1, new byte[] { 0 }, Clock.systemDefaultZone());

    Assert.assertFalse(protectedStorageEntry.isValidForAddOperation());
}
 
Example #13
Source File: TCKLocalDateTime.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_Clock_allSecsInDay_offset() {
    for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i).plusNanos(123456789L);
        Clock clock = Clock.fixed(instant.minusSeconds(OFFSET_PONE.getTotalSeconds()), OFFSET_PONE);
        LocalDateTime test = LocalDateTime.now(clock);
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonth(), Month.JANUARY);
        assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60) ? 1 : 2);
        assertEquals(test.getHour(), (i / (60 * 60)) % 24);
        assertEquals(test.getMinute(), (i / 60) % 60);
        assertEquals(test.getSecond(), i % 60);
        assertEquals(test.getNano(), 123456789);
    }
}
 
Example #14
Source File: GraphqlCheckRunProvider.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
GraphqlCheckRunProvider(GraphqlProvider graphqlProvider, Clock clock,
                        GithubApplicationAuthenticationProvider githubApplicationAuthenticationProvider,
                        Server server) {
    super();
    this.graphqlProvider = graphqlProvider;
    this.clock = clock;
    this.githubApplicationAuthenticationProvider = githubApplicationAuthenticationProvider;
    this.server = server;
}
 
Example #15
Source File: TCKMonthDay.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void now_ZoneId() {
    ZoneId zone = ZoneId.of("UTC+01:02:03");
    MonthDay expected = MonthDay.now(Clock.system(zone));
    MonthDay test = MonthDay.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = MonthDay.now(Clock.system(zone));
        test = MonthDay.now(zone);
    }
    assertEquals(test, expected);
}
 
Example #16
Source File: CircuitBreakerSecuredJdbcClient.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
public CircuitBreakerSecuredJdbcClient(Vertx vertx, JdbcClient jdbcClient, Metrics metrics,
                                       int openingThreshold, long openingIntervalMs, long closingIntervalMs,
                                       Clock clock) {

    breaker = new CircuitBreaker("jdbc-client-circuit-breaker", Objects.requireNonNull(vertx),
            openingThreshold, openingIntervalMs, closingIntervalMs, Objects.requireNonNull(clock))
            .openHandler(ignored -> circuitOpened())
            .halfOpenHandler(ignored -> circuitHalfOpened())
            .closeHandler(ignored -> circuitClosed());

    this.jdbcClient = Objects.requireNonNull(jdbcClient);
    this.metrics = Objects.requireNonNull(metrics);

    logger.info("Initialized JDBC client with Circuit Breaker");
}
 
Example #17
Source File: PersonGenerator.java    From immutables with Apache License 2.0 5 votes vote down vote up
public PersonGenerator(Clock clock) {
  Preconditions.checkState(FIRST_NAMES.size() == LAST_NAMES.size(), "%s != %s",
          FIRST_NAMES.size(), LAST_NAMES.size());
  this.index = new AtomicLong();
  this.clock = clock;
  this.size = FIRST_NAMES.size();
}
 
Example #18
Source File: TCKLocalTime.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_ZoneId() {
    ZoneId zone = ZoneId.of("UTC+01:02:03");
    LocalTime expected = LocalTime.now(Clock.system(zone));
    LocalTime test = LocalTime.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = LocalTime.now(Clock.system(zone));
        test = LocalTime.now(zone);
    }
    assertEquals(test.truncatedTo(ChronoUnit.SECONDS),
                 expected.truncatedTo(ChronoUnit.SECONDS));
}
 
Example #19
Source File: TCKChronology.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_IsoChronology_dateNow() {
    ZoneId zoneId_paris = ZoneId.of("Europe/Paris");
    Clock clock = Clock.system(zoneId_paris);

    Chronology chrono = Chronology.of("ISO");
    assertEquals(chrono.dateNow(), IsoChronology.INSTANCE.dateNow());
    assertEquals(chrono.dateNow(zoneId_paris), IsoChronology.INSTANCE.dateNow(zoneId_paris));
    assertEquals(chrono.dateNow(clock), IsoChronology.INSTANCE.dateNow(clock));
}
 
Example #20
Source File: TCKLocalDate.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void now_Clock_allSecsInDay_utc() {
    for (int i = 0; i < (2 * 24 * 60 * 60); i++) {
        Instant instant = Instant.ofEpochSecond(i);
        Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
        LocalDate test = LocalDate.now(clock);
        assertEquals(test.getYear(), 1970);
        assertEquals(test.getMonth(), Month.JANUARY);
        assertEquals(test.getDayOfMonth(), (i < 24 * 60 * 60 ? 1 : 2));
    }
}
 
Example #21
Source File: TCKLocalDate.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Test
public void now_Clock_allSecsInDay_beforeEpoch() {
    for (int i =-1; i >= -(2 * 24 * 60 * 60); i--) {
        Instant instant = Instant.ofEpochSecond(i);
        Clock clock = Clock.fixed(instant, ZoneOffset.UTC);
        LocalDate test = LocalDate.now(clock);
        assertEquals(test.getYear(), 1969);
        assertEquals(test.getMonth(), Month.DECEMBER);
        assertEquals(test.getDayOfMonth(), (i >= -24 * 60 * 60 ? 31 : 30));
    }
}
 
Example #22
Source File: TCKChronology.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_IsoChronology_dateNow() {
    ZoneId zoneId_paris = ZoneId.of("Europe/Paris");
    Clock clock = Clock.system(zoneId_paris);

    Chronology chrono = Chronology.of("ISO");
    assertEquals(chrono.dateNow(), IsoChronology.INSTANCE.dateNow());
    assertEquals(chrono.dateNow(zoneId_paris), IsoChronology.INSTANCE.dateNow(zoneId_paris));
    assertEquals(chrono.dateNow(clock), IsoChronology.INSTANCE.dateNow(clock));
}
 
Example #23
Source File: TCKChronology.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void test_JapaneseChronology_dateNow() {
    ZoneId zoneId_paris = ZoneId.of("Europe/Paris");
    Clock clock = Clock.system(zoneId_paris);

    Chronology chrono = Chronology.of("Japanese");
    assertEquals(chrono.dateNow(), JapaneseChronology.INSTANCE.dateNow());
    assertEquals(chrono.dateNow(zoneId_paris), JapaneseChronology.INSTANCE.dateNow(zoneId_paris));
    assertEquals(chrono.dateNow(clock), JapaneseChronology.INSTANCE.dateNow(clock));
}
 
Example #24
Source File: TCKClock_Offset.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public void test_offset_ClockDuration() {
    Clock test = Clock.offset(Clock.fixed(INSTANT, PARIS), OFFSET);
    //System.out.println(test.instant());
    //System.out.println(INSTANT.plus(OFFSET));
    assertEquals(test.instant(), INSTANT.plus(OFFSET));
    assertEquals(test.getZone(), PARIS);
}
 
Example #25
Source File: KafkaConsumerSpoutTest.java    From storm-dynamic-spout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This happens once before every test method.
 * Create a new empty namespace with randomly generated name.
 */
@BeforeEach
public void beforeTest() throws InterruptedException {
    // Generate namespace name
    topicName = KafkaConsumerSpoutTest.class.getSimpleName() + Clock.systemUTC().millis();

    // Create namespace
    getKafkaTestUtils().createTopic(topicName, 1, (short) 1);
}
 
Example #26
Source File: SchedulerTest.java    From dynein with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
  ObjectMapper mapper = new ObjectMapper();
  jobSpecTransformer = new JacksonJobSpecTransformer(mapper);
  TokenManager tokenManager = new JacksonTokenManager(mapper);
  scheduler =
      new Scheduler(
          asyncClient,
          "inbound-test",
          jobSpecTransformer,
          tokenManager,
          scheduleManager,
          Clock.fixed(Instant.now(), ZoneId.of("UTC")),
          new NoOpMetricsImpl());
}
 
Example #27
Source File: SessionRepository.java    From vespa with Apache License 2.0 5 votes vote down vote up
private LocalSession createSessionFromApplication(ApplicationPackage applicationPackage,
                                                  long sessionId,
                                                  TimeoutBudget timeoutBudget,
                                                  Clock clock) {
    log.log(Level.FINE, TenantRepository.logPre(tenantName) + "Creating session " + sessionId + " in ZooKeeper");
    SessionZooKeeperClient sessionZKClient = createSessionZooKeeperClient(sessionId);
    sessionZKClient.createNewSession(clock.instant());
    Curator.CompletionWaiter waiter = sessionZKClient.getUploadWaiter();
    LocalSession session = new LocalSession(tenantName, sessionId, applicationPackage, sessionZKClient, applicationRepo);
    waiter.awaitCompletion(timeoutBudget.timeLeft());
    return session;
}
 
Example #28
Source File: PDTWebDateHelper.java    From ph-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @return The current date time formatted using RFC 822
 */
@Nonnull
public static String getCurrentDateTimeAsStringRFC822 ()
{
  // Important to use date time zone GMT as this is what the standard
  // printer emits!
  // Use no milliseconds as the standard printer does not print them!
  final ZonedDateTime aNow = ZonedDateTime.now (Clock.systemUTC ()).withNano (0);
  return getAsStringRFC822 (aNow);
}
 
Example #29
Source File: StashRequestManager.java    From emodb with Apache License 2.0 5 votes vote down vote up
@Inject
public StashRequestManager(StashRequestDAO stashRequestDAO, List<ScheduledDailyScanUpload> scheduledScans, Clock clock) {
    _stashRequestDAO = checkNotNull(stashRequestDAO, "stashRequestDAO");
    _scheduledScans = Maps.uniqueIndex(
            checkNotNull(scheduledScans, "scheduledScans"),
            ScheduledDailyScanUpload::getId);
    _clock = checkNotNull(clock, "clock");
}
 
Example #30
Source File: BackgroundRunnerTest.java    From timbuctoo with GNU General Public License v3.0 5 votes vote down vote up
@Test
public void returnsNonEmptyAfterRunReturnedRegardlessOfExecutorService() throws Exception {
  final BackgroundRunner<String> instance = new BackgroundRunner<>(
    0,
    Clock.systemUTC(),
    mock(ScheduledExecutorService.class)
  );

  instance.start(() -> "yeey!");
  assertThat(instance.getMostRecentResult().get(), is("yeey!"));
}