-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathNtpTimeProvider.java
More file actions
56 lines (45 loc) · 2 KB
/
NtpTimeProvider.java
File metadata and controls
56 lines (45 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package dev.samstevens.totp.time;
import dev.samstevens.totp.exceptions.TimeProviderException;
import org.apache.commons.net.ntp.NTPUDPClient;
import org.apache.commons.net.ntp.TimeInfo;
import java.net.InetAddress;
import java.net.UnknownHostException;
public final class NtpTimeProvider implements TimeProvider {
private final NTPUDPClient client;
private final InetAddress ntpHost;
public NtpTimeProvider(String ntpHostname) throws UnknownHostException {
// default timeout of 3 seconds
this(ntpHostname, 3000);
}
public NtpTimeProvider(String ntpHostname, int timeout) throws UnknownHostException {
this(ntpHostname, timeout, "org.apache.commons.net.ntp.NTPUDPClient");
}
// Package-private, for tests only
NtpTimeProvider(String ntpHostname, String dependentClass) throws UnknownHostException {
// default timeout of 3 seconds
this(ntpHostname, 3000, dependentClass);
}
private NtpTimeProvider(String ntpHostname, int timeout, String dependentClass) throws UnknownHostException {
// Check the optional commons-net dependency is on the classpath
checkHasDependency(dependentClass);
client = new NTPUDPClient();
client.setDefaultTimeout(timeout);
ntpHost = InetAddress.getByName(ntpHostname);
}
@Override
public long getTime() throws TimeProviderException {
try {
TimeInfo timeInfo = client.getTime(ntpHost);
return (long) Math.floor(timeInfo.getReturnTime() / 1000L);
} catch (Exception e) {
throw new TimeProviderException("Failed to provide time from NTP server. See nested exception.", e);
}
}
private void checkHasDependency(String dependentClass) {
try {
Class<?> ntpClientClass = Class.forName(dependentClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException("The Apache Commons Net library must be on the classpath to use the NtpTimeProvider.");
}
}
}