package net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import java.util.StringTokenizer;
import java.util.TimeZone;
public class AtomicClock {
public static BufferedReader getReader()
throws UnknownHostException,
IOException {
Socket s = new Socket(
"time-A.timefreq.bldrdoc.gov", 13);
return new BufferedReader(
new InputStreamReader(
s.getInputStream()));
}
public static void setSystemTime(GregorianCalendar c)
throws IOException {
Runtime rt = Runtime.getRuntime();
StringTokenizer st = new StringTokenizer(
c.getTime().toString(), " ");
for (int i = 0; i < 3; i++)
st.nextToken();
String[] execArgArray = new String[2];
execArgArray[0] = "c:\\SW409\\settime.bat";
execArgArray[1] = st.nextToken();
rt.exec(execArgArray);
}
public static GregorianCalendar parseDate(String line) {
StringTokenizer sTok =
new StringTokenizer(line, " ");
sTok.nextToken();
String sDate = sTok.nextToken();
String sTime = sTok.nextToken();
SimpleDateFormat df =
new SimpleDateFormat("yy-MM-dd hh:mm:ss");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
GregorianCalendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
try {
cal.setTime(df.parse(sDate + " " + sTime));
} catch (ParseException e) {
System.out.println(e.getMessage());
}
System.out.println(cal.getTime());
return cal;
}
public static void processLine(String s)
throws IOException {
if (s.length() == 0) return;
System.out.println(s);
setSystemTime(parseDate(s));
sleep();
}
public static void getTime()
throws UnknownHostException, IOException {
BufferedReader br = getReader();
String s = null;
while ((s = br.readLine()) != null)
processLine(s);
}
public static void sleep() {
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
public static void main(String[] args) {
try {
AtomicClock.getTime();
} catch (Exception e) {
e.printStackTrace();
}
}
}