1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.net.time;
18
19 import static org.junit.jupiter.api.Assertions.assertEquals;
20 import static org.junit.jupiter.api.Assertions.assertTrue;
21 import static org.junit.jupiter.api.Assertions.fail;
22
23 import java.io.IOException;
24 import java.net.InetAddress;
25 import java.util.Calendar;
26 import java.util.TimeZone;
27
28 import org.junit.jupiter.api.Test;
29
30 class TimeTCPClientTest {
31 private TimeTestSimpleServer server1;
32
33 private int _port = 3333;
34
35 protected void closeConnections() {
36 try {
37 server1.stop();
38 Thread.sleep(1000);
39 } catch (final Exception e) {
40
41 }
42 }
43
44 protected void openConnections() throws Exception {
45 try {
46 server1 = new TimeTestSimpleServer(_port);
47 server1.connect();
48 } catch (final IOException ioe) {
49
50 _port = 4000;
51 server1 = new TimeTestSimpleServer(_port);
52 server1.connect();
53 }
54 server1.start();
55 }
56
57
58
59
60 @Test
61 void testCompareTimes() throws Exception {
62 openConnections();
63
64 final long time;
65 final long time2;
66 final long clientTime;
67 final long clientTime2;
68 final TimeTCPClient client = new TimeTCPClient();
69 try {
70
71 final InetAddress localHost = InetAddress.getByName("localhost");
72 try {
73
74 client.setDefaultTimeout(60000);
75 client.connect(localHost, _port);
76 clientTime = client.getDate().getTime();
77 time = System.currentTimeMillis();
78 } catch (final IOException e) {
79 fail("IOError <" + e + "> trying to connect to " + localHost + " " + _port);
80 throw e;
81 } finally {
82 if (client.isConnected()) {
83 client.disconnect();
84 }
85 }
86
87 try {
88
89 client.setDefaultTimeout(60000);
90 client.connect(localHost, _port);
91 clientTime2 = (client.getTime() - TimeTCPClient.SECONDS_1900_TO_1970) * 1000L;
92 time2 = System.currentTimeMillis();
93 } finally {
94 if (client.isConnected()) {
95 client.disconnect();
96 }
97 }
98 } finally {
99 closeConnections();
100 }
101
102
103 assertTrue(Math.abs(time - clientTime) < 5000);
104 assertTrue(Math.abs(time2 - clientTime2) < 5000);
105 }
106
107
108
109
110 @Test
111 void testInitial() {
112 final TimeZone utcZone = TimeZone.getTimeZone("UTC");
113 final Calendar calendar = Calendar.getInstance(utcZone);
114 calendar.set(1900, Calendar.JANUARY, 1, 0, 0, 0);
115 calendar.set(Calendar.MILLISECOND, 0);
116 final long baseTime = calendar.getTime().getTime() / 1000L;
117
118 assertEquals(-TimeTCPClient.SECONDS_1900_TO_1970, baseTime);
119 }
120 }