NTPServerTimeProvider extends AbstractScheduledService implements PhysicalTimeProvider { TimeStamp getTimestamp() throws TimeoutException { if (timestamp == null) { throw new TimeoutException(); } TimeStamp ts = new TimeStamp(timestamp.ntpValue()); long fraction = ts.getFraction(); long seconds = ts.getSeconds(); long nanoTime = System.nanoTime(); long l = (nanoTime - nano) / 1_000_000_000; double v = (nanoTime - nano) / 1_000_000_000.0 - l; long i = (long) (v * 1_000_000_000); long fraction_ = fraction + i; if (fraction_ >= 1_000_000_000) { fraction_ -= 1_000_000_000; l++; } return new TimeStamp((seconds + l) << 32 | fraction_); } NTPServerTimeProvider();  NTPServerTimeProvider(String[] ntpServers); @Override @SneakyThrows long getPhysicalTime(); static final int SO_TIMEOUT; }
@Test(successPercentage = 99, dataProvider = "delays") public void secondsPassed(int delay) throws UnknownHostException, InterruptedException, TimeoutException { TimeStamp ts1 = provider.getTimestamp(); Thread.sleep(delay); TimeStamp ts2 = provider.getTimestamp(); long seconds = delay / 1000; assertEquals("Delay=" + delay + " time_diff=" + (ts2.getTime() - ts1.getTime()), seconds, (ts2.getTime() - ts1.getTime()) / 1000); }
@SneakyThrows @Test(timeOut = 5000) public void unavailableTimeServer() { NTPServerTimeProvider timeProvider = new NTPServerTimeProvider(new String[]{"255.255.255.255"}); timeProvider.startAsync().awaitRunning(); try { timeProvider.getTimestamp(); assertEquals("Should throw TimeoutException", true, false); } catch (TimeoutException e) { return; } timeProvider.stopAsync().awaitTerminated(); }