-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBox.java
More file actions
98 lines (87 loc) · 2.71 KB
/
Box.java
File metadata and controls
98 lines (87 loc) · 2.71 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.UUID;
final class Box {
private final UUID id;
private final InetSocketAddress controllerAddress;
private final Duration connectTimeout;
private Socket connection;
private Box(
UUID id,
InetSocketAddress controllerAddress,
Duration connectTimeout
) {
this.id = id;
this.connectTimeout = connectTimeout;
this.controllerAddress = controllerAddress;
}
public void start() throws IOException {
connect();
try {
advertise();
accept();
} finally {
connection.close();
}
}
private void connect() throws IOException {
connection = new Socket();
connection.connect(controllerAddress, (int) connectTimeout.toMillis());
}
public void advertise() throws IOException {
var bytes = ByteBuffer.allocate(Long.SIZE * 2);
bytes.putLong(id.getMostSignificantBits());
bytes.putLong(id.getLeastSignificantBits());
connection.getOutputStream().write(bytes.flip().array());
}
public void accept() throws IOException {
var input = connection.getInputStream();
byte[] buffer = new byte[4096];
while (!Thread.currentThread().isInterrupted() && connection.isConnected()) {
int read = input.read(buffer);
if (read == -1) {
return;
}
if (read != 0) {
System.out.write(buffer, 0, read);
}
}
}
public static void main(String[] arguments) {
validateArguments(arguments);
var box = createBoxFromArguments(arguments);
try {
box.start();
} catch (IOException failure) {
System.err.println("error occurred while running box");
failure.printStackTrace();
}
}
private static void validateArguments(String[] arguments) {
if (arguments.length != addressIndex + 1) {
System.out.println("usage: box <id> <controllerAddress>");
System.exit(-1);
}
}
private static final int idIndex = 0;
private static final int addressIndex = 1;
private static Box createBoxFromArguments(String[] arguments) {
var id = UUID.fromString(arguments[idIndex]);
var address = parseAddress(arguments[addressIndex]);
return new Box(id, address, Duration.ofMillis(5000));
}
private static InetSocketAddress parseAddress(String input) {
int portSeparator = input.indexOf(':');
if (portSeparator == -1) {
throw new IllegalArgumentException("port missing: " + input);
}
int port = Integer.parseInt(input.substring(portSeparator + 1));
var host = input.substring(0, portSeparator);
return host.isEmpty()
? new InetSocketAddress(port)
: new InetSocketAddress(host, port);
}
}