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 Project: jdk8u-dev-jdk   Author: frohoff   File: TCKClock_Tick.java    License: 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 #2
Source Project: jdk8u60   Author: chenghanpeng   File: TCKMinguoChronology.java    License: 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 #3
Source Project: prebid-server-java   Author: rubicon-project   File: StatusHandlerTest.java    License: 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 #4
Source Project: jdk8u-jdk   Author: frohoff   File: TCKThaiBuddhistChronology.java    License: 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 #5
Source Project: emodb   Author: bazaarvoice   File: ScanParticipationService.java    License: 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 Project: spring-analysis-note   Author: Vip-Augus   File: InMemoryWebSessionStoreTests.java    License: 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 Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TCKZonedDateTime.java    License: 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 Project: j2objc   Author: google   File: TCKLocalDate.java    License: 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 #9
Source Project: openjdk-8-source   Author: keerath   File: TCKLocalDate.java    License: 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");
    LocalDate expected = LocalDate.now(Clock.system(zone));
    LocalDate test = LocalDate.now(zone);
    for (int i = 0; i < 100; i++) {
        if (expected.equals(test)) {
            return;
        }
        expected = LocalDate.now(Clock.system(zone));
        test = LocalDate.now(zone);
    }
    assertEquals(test, expected);
}
 
Example #10
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TCKLocalTime.java    License: 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 #11
Source Project: bisq   Author: bisq-network   File: ProtectedStorageEntryTest.java    License: 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 #12
Source Project: synapse   Author: otto-de   File: KinesisMessageLogReceiverEndpointFactory.java    License: 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 #13
Source Project: pulsar   Author: apache   File: BackoffBuilder.java    License: 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 #14
Source Project: logbook   Author: zalando   File: CommonsLogFormatSinkTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldNotWriteRequestBeforeResponse() throws IOException {
    final Clock clock = fixed(Instant.parse("2019-08-02T08:04:27Z"), UTC);
    final Precorrelation correlation = new SimplePrecorrelation("", clock);

    new CommonsLogFormatSink(writer)
            .write(correlation, MockHttpRequest.create());

    verify(writer, never()).write(any(Precorrelation.class), any());
}
 
Example #15
Source Project: openjdk-8   Author: bpupadhyaya   File: TCKZonedDateTime.java    License: 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 #16
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: TCKLocalDateTime.java    License: 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 #17
GraphqlCheckRunProvider(GraphqlProvider graphqlProvider, Clock clock,
                        GithubApplicationAuthenticationProvider githubApplicationAuthenticationProvider,
                        Server server) {
    super();
    this.graphqlProvider = graphqlProvider;
    this.clock = clock;
    this.githubApplicationAuthenticationProvider = githubApplicationAuthenticationProvider;
    this.server = server;
}
 
Example #18
Source Project: j2objc   Author: google   File: TCKMonthDay.java    License: 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 #19
Source Project: prebid-server-java   Author: rubicon-project   File: CircuitBreakerSecuredJdbcClient.java    License: 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 #20
Source Project: immutables   Author: immutables   File: PersonGenerator.java    License: 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 #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: TCKChronology.java    License: 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 #22
Source Project: jdk8u-dev-jdk   Author: frohoff   File: TCKLocalDate.java    License: 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 #23
Source Project: vespa   Author: vespa-engine   File: CuratorDatabaseClient.java    License: 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 #24
Source Project: TencentKona-8   Author: Tencent   File: TCKChronology.java    License: 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 #25
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: TCKChronology.java    License: 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 #26
Source Project: dragonwell8_jdk   Author: alibaba   File: TCKClock_Offset.java    License: 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 #27
Source Project: storm-dynamic-spout   Author: salesforce   File: KafkaConsumerSpoutTest.java    License: 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 #28
Source Project: dynein   Author: airbnb   File: SchedulerTest.java    License: 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 #29
Source Project: vespa   Author: vespa-engine   File: SessionRepository.java    License: 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 #30
Source Project: ph-commons   Author: phax   File: PDTWebDateHelper.java    License: 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);
}