java.time.Clock.offset()方法的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(13.8k)|赞(0)|评价(0)|浏览(174)

本文整理了Java中java.time.Clock.offset()方法的一些代码示例,展示了Clock.offset()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Clock.offset()方法的具体详情如下:
包路径:java.time.Clock
类名称:Clock
方法名:offset

Clock.offset介绍

[英]Obtains a clock that returns instants from the specified clock with the specified duration added

This clock wraps another clock, returning instants that are later by the specified duration. If the duration is negative, the instants will be earlier than the current date and time. The main use case for this is to simulate running in the future or in the past.

A duration of zero would have no offsetting effect. Passing zero will return the underlying clock.

The returned implementation is immutable, thread-safe and Serializableproviding that the base clock is.
[中]获取一个时钟,该时钟返回添加了指定持续时间的指定时钟的瞬间
此时钟包装另一个时钟,返回指定持续时间之后的瞬间。如果持续时间为负数,则瞬间将早于当前日期和时间。这方面的主要用例是模拟将来或过去的运行。
持续时间为零不会产生抵消效应。超过零将返回基础时钟。
返回的实现是不可变的、线程安全的和可序列化的,前提是基本时钟为。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Test
public void expirationCheckPeriod() {
  DirectFieldAccessor accessor = new DirectFieldAccessor(this.store);
  Map<?,?> sessions = (Map<?, ?>) accessor.getPropertyValue("sessions");
  assertNotNull(sessions);
  // Create 100 sessions
  IntStream.range(0, 100).forEach(i -> insertSession());
  assertEquals(100, sessions.size());
  // Force a new clock (31 min later), don't use setter which would clean expired sessions
  accessor.setPropertyValue("clock", Clock.offset(this.store.getClock(), Duration.ofMinutes(31)));
  assertEquals(100, sessions.size());
  // Create 1 more which forces a time-based check (clock moved forward)
  insertSession();
  assertEquals(1, sessions.size());
}

代码示例来源:origin: spring-projects/spring-framework

@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);
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void lastAccessTimeIsUpdatedOnRetrieve() {
  WebSession session1 = this.store.createWebSession().block();
  assertNotNull(session1);
  String id = session1.getId();
  Instant time1 = session1.getLastAccessTime();
  session1.start();
  session1.save().block();
  // Fast-forward a few seconds
  this.store.setClock(Clock.offset(this.store.getClock(), Duration.ofSeconds(5)));
  WebSession session2 = this.store.retrieveSession(id).block();
  assertNotNull(session2);
  assertSame(session1, session2);
  Instant time2 = session2.getLastAccessTime();
  assertTrue(time1.isBefore(time2));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void expiredSessionEnds() throws Exception {
  // First request: no session yet, new session created
  RequestEntity<Void> request = RequestEntity.get(createUri()).build();
  ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  String id = extractSessionId(response.getHeaders());
  assertNotNull(id);
  // Now fast-forward by 31 minutes
  InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore();
  store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31)));
  // Second request: session expires
  URI uri = new URI("http://localhost:" + this.port + "/?expire");
  request = RequestEntity.get(uri).header("Cookie", "SESSION=" + id).build();
  response = this.restTemplate.exchange(request, Void.class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  String value = response.getHeaders().getFirst("Set-Cookie");
  assertNotNull(value);
  assertTrue("Actual value: " + value, value.contains("Max-Age=0"));
}

代码示例来源:origin: spring-projects/spring-framework

@Test
public void expiredSessionIsRecreated() throws Exception {
  // First request: no session yet, new session created
  RequestEntity<Void> request = RequestEntity.get(createUri()).build();
  ResponseEntity<Void> response = this.restTemplate.exchange(request, Void.class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  String id = extractSessionId(response.getHeaders());
  assertNotNull(id);
  assertEquals(1, this.handler.getSessionRequestCount());
  // Second request: same session
  request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
  response = this.restTemplate.exchange(request, Void.class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  assertNull(response.getHeaders().get("Set-Cookie"));
  assertEquals(2, this.handler.getSessionRequestCount());
  // Now fast-forward by 31 minutes
  InMemoryWebSessionStore store = (InMemoryWebSessionStore) this.sessionManager.getSessionStore();
  WebSession session = store.retrieveSession(id).block();
  assertNotNull(session);
  store.setClock(Clock.offset(store.getClock(), Duration.ofMinutes(31)));
  // Third request: expired session, new session created
  request = RequestEntity.get(createUri()).header("Cookie", "SESSION=" + id).build();
  response = this.restTemplate.exchange(request, Void.class);
  assertEquals(HttpStatus.OK, response.getStatusCode());
  id = extractSessionId(response.getHeaders());
  assertNotNull("Expected new session id", id);
  assertEquals(1, this.handler.getSessionRequestCount());
}

代码示例来源:origin: EvoSuite/evosuite

public static Clock offset(Clock baseClock, Duration offsetDuration) {
  return Clock.offset(baseClock, offsetDuration);
}

代码示例来源:origin: Baqend/Orestes-Bloomfilter

public Clock getClock() {
  List<String> time = this.safelyReturn(Jedis::time);
  Instant local = Instant.now();
  //Format: [0]: unix ts [1]: microseconds
  Instant redis = Instant.ofEpochSecond(Long.valueOf(time.get(0)), Long.valueOf(time.get(1)) * 1000);
  return Clock.offset(Clock.systemDefaultZone(), Duration.between(local, redis));
}

代码示例来源:origin: org.hibernate.validator/hibernate-validator

@Override
public void initialize(ConstraintDescriptor<C> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
  try {
    this.referenceClock  = Clock.offset(
        initializationContext.getClockProvider().getClock(),
        getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
    );
  }
  catch (Exception e) {
    throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
  }
}

代码示例来源:origin: org.hibernate.validator/hibernate-validator

@Override
public void initialize(ConstraintDescriptor<C> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
  try {
    this.referenceClock  = Clock.offset(
        initializationContext.getClockProvider().getClock(),
        getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
    );
  }
  catch (Exception e) {
    throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
  }
}

代码示例来源:origin: org.hibernate.validator/hibernate-validator

@Override
public void initialize(ConstraintDescriptor<C> constraintDescriptor, HibernateConstraintValidatorInitializationContext initializationContext) {
  try {
    this.referenceClock  = Clock.offset(
        initializationContext.getClockProvider().getClock(),
        getEffectiveTemporalValidationTolerance( initializationContext.getTemporalValidationTolerance() )
    );
  }
  catch (Exception e) {
    throw LOG.getUnableToGetCurrentTimeFromClockProvider( e );
  }
}

代码示例来源:origin: Johnnei/JavaTorrent

@Test
public void testGetDownloadRate() throws IOException {
  MessageFactory messageFactoryMock = mock(MessageFactory.class);
  ISocket socketMock = mock(ISocket.class);
  SocketChannel channelMock = mock(SocketChannel.class);
  when(socketMock.getReadableChannel()).thenReturn(channelMock);
  mockReadMessage(messageFactoryMock, mock(IMessage.class), channelMock);
  Clock fixedClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
  TestClock clock = new TestClock(fixedClock);
  BitTorrentSocket cut = new BitTorrentSocket(messageFactoryMock, socketMock, clock);
  clock.setClock(Clock.offset(fixedClock, Duration.ofSeconds(1)));
  cut.canReadMessage();
  cut.pollRates();
  assertThat("Incorrect speed", cut.getDownloadRate(), equalTo(5));
}

代码示例来源:origin: Johnnei/JavaTorrent

@Test
public void testGetRate() {
  Clock fixedClock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
  TestClock clock = new TestClock(fixedClock);
  TransferRate cut = new TransferRate(clock);
  cut.addTransferredBytes(5);
  clock.setClock(Clock.offset(fixedClock, Duration.ofSeconds(1)));
  cut.pollRate();
  assertThat("Rate should be exactly 5 bytes/s", cut.getRate(), equalTo(5));
}

代码示例来源:origin: Johnnei/JavaTorrent

@Test
@DisplayName("testSendMessage() -> Keep alive")
public void testSendMessage() throws Exception {
  Clock clock = Clock.fixed(Clock.offset(Clock.systemDefaultZone(), Duration.ofSeconds(1)).instant(), Clock.systemDefaultZone().getZone());
  MessageFactory messageFactoryMock = mock(MessageFactory.class);
  ISocket socketMock = mock(ISocket.class);
  SocketChannel channelMock = mock(SocketChannel.class);
  when(socketMock.getReadableChannel()).thenReturn(channelMock);
  when(socketMock.getWritableChannel()).thenReturn(channelMock);
  IMessage messageMock = mock(MessageKeepAlive.class);
  // KeepAlive
  when(messageMock.getLength()).thenReturn(0);
  BitTorrentSocket cut = new BitTorrentSocket(messageFactoryMock, socketMock, clock);
  cut.enqueueMessage(messageMock);
  cut.sendMessages();
  ArgumentCaptor<ByteBuffer> bufferCaptor = ArgumentCaptor.forClass(ByteBuffer.class);
  verify(channelMock).write(bufferCaptor.capture());
  assertArrayEquals(new byte[4], ByteBufferUtils.getBytes(bufferCaptor.getValue(), 4), "Incorrect keep alive output.");
}

代码示例来源:origin: Johnnei/JavaTorrent

@Test
public void testDegradeConnection() throws Exception {
  TestClock clock = new TestClock(Clock.systemDefaultZone());
  cut = new NioPeerConnector(clock, torrentClient, 4);
  BitTorrentHandshakeHandler handshakeHandler = mock(BitTorrentHandshakeHandler.class);
  when(torrentClient.getHandshakeHandler()).thenReturn(handshakeHandler);
  PeerConnectInfo infoOne = mock(PeerConnectInfo.class);
  when(infoOne.getAddress())
    .thenReturn(InetSocketAddress.createUnresolved("localhost", DummyEntity.findAvailableTcpPort()));
  cut.enqueuePeer(infoOne);
  cut.pollReadyConnections();
  verify(socketTypeOne).connect(notNull());
  clock.setClock(Clock.offset(Clock.systemDefaultZone(), Duration.ofSeconds(15)));
  cut.pollReadyConnections();
  verify(socketTypeOne).close();
  verify(socketTypeTwo).connect(notNull());
}

代码示例来源:origin: otto-de/edison-microservice

@Test
public void shouldStopJob() {
  OffsetDateTime now = OffsetDateTime.now(clock);
  Clock earlierClock = offset(clock, Duration.of(-1, MINUTES));
  JobInfo jobInfo = JobInfo.newJobInfo("superId", "superType", earlierClock, HOSTNAME);
  when(jobRepository.findOne("superId")).thenReturn(Optional.of(jobInfo));
  jobService.stopJob("superId");
  JobInfo expected = jobInfo.copy().setStatus(JobInfo.JobStatus.OK).setStopped(now).setLastUpdated(now).build();
  verify(jobMetaService).releaseRunLock("superType");
  verify(jobRepository).createOrUpdate(expected);
}

代码示例来源:origin: kaif-open/kaif

@Test
public void oauthDirectAuthorizeToken_skip_expired() throws Exception {
 Account account = savedAccountCitizen("oauthTest");
 service.setClock(Clock.offset(Clock.systemDefaultZone(), Duration.ofHours(-2)));
 AccountOnceToken token = service.createOauthDirectAuthorizeToken(account);
 service.setClock(Clock.systemDefaultZone());
 assertFalse("expired token should be invalid",
   service.oauthDirectAuthorize(token.getToken()).isPresent());
}

代码示例来源:origin: kaif-open/kaif

@Test
public void activate_skip_token_expired() throws Exception {
 service.setClock(Clock.offset(Clock.systemDefaultZone(), Duration.ofDays(-2)));
 Account account = service.createViaEmail("xyz", "xyz@gmail.com", "595959", lc);
 AccountOnceToken token = accountDao.listOnceTokens().get(0);
 service.setClock(Clock.systemDefaultZone());
 assertFalse("expired token should invalid", service.activate(token.getToken()));
 Account loaded = accountDao.findById(account.getAccountId()).get();
 assertFalse(loaded.isActivated());
}

代码示例来源:origin: Johnnei/JavaTorrent

@Test
public void testSetInfoAnnounce() {
  Torrent torrent = DummyEntity.createUniqueTorrent();
  Clock baseClock = Clock.fixed(Clock.systemDefaultZone().instant(), Clock.systemDefaultZone().getZone());
  Clock offsetClock = Clock.offset(baseClock, Duration.ofSeconds(3));
  TestClock testClock = new TestClock(baseClock);
  TorrentInfo cut = new TorrentInfo(torrent, testClock);
  testClock.setClock(offsetClock);
  cut.setInfo(15, 42);
  assertEquals(15, cut.getSeeders(), "Seeder count should have been 15");
  assertEquals(42, cut.getLeechers(), "Leechers count should have been 42");
  assertEquals(Duration.ZERO, cut.getTimeSinceLastAnnounce(), "Duration since last announce should have been zero");
}

代码示例来源:origin: kaif-open/kaif

@Test
public void deleteArticle_author_can_not_after_10_minutes() throws Exception {
 service.setClock(Clock.offset(Clock.systemDefaultZone(), Duration.ofMinutes(-11)));
 Article article = service.createSpeak(citizen, zoneInfo.getZone(), "titleFoo", "contentFoo");
 try {
  service.setClock(Clock.systemDefaultZone());
  assertFalse(service.canDeleteArticle(citizen.getUsername(), article.getArticleId()));
  service.deleteArticle(citizen, article.getArticleId());
  fail("AccessDeniedException expected");
 } catch (AccessDeniedException expected) {
 }
 assertFalse(service.loadArticle(article.getArticleId()).isDeleted());
}

代码示例来源:origin: kaif-open/kaif

@Test
public void deleteArticle_zone_admin() throws Exception {
 Account admin = savedAccountCitizen("admin");
 accountDao.changeTotalVotedDebate(admin.getAccountId(), 1000, 0);
 ZoneInfo aZone = zoneService.createByUser("a-zone", "a-zone", admin);
 service.setClock(Clock.offset(Clock.systemDefaultZone(), Duration.ofMinutes(11)));
 Article article = service.createSpeak(citizen, aZone.getZone(), "titleFoo", "contentFoo");
 service.setClock(Clock.systemDefaultZone());
 assertTrue(service.canDeleteArticle(admin.getUsername(), article.getArticleId()));
 //admin can delete article without time constraint
 service.deleteArticle(admin, article.getArticleId());
 assertTrue(service.loadArticle(article.getArticleId()).isDeleted());
}

相关文章