-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSimployHttpServer.java
90 lines (68 loc) · 2.21 KB
/
SimployHttpServer.java
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
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimployHttpServer {
private static String _password;
private static ServerSocket _serverSocket;
private static final int REQUEST_TIMEOUT = 1000;
private static final String REPLY_HEADER =
"HTTP/1.1 200 OK\r\n" +
"Content-Type: text/plain\r\n" +
"\r\n";
private static final PrintStream OUT = System.out;
static void start(int port, String password) throws IOException {
_password = password;
_serverSocket = new ServerSocket(port);
OUT.println("Listening for requests on port " + port);
new Thread() { @Override public void run() {
while (true)
acceptRequest();
}}.start();
}
private static void acceptRequest() {
try {
tryToAcceptRequest();
} catch (Exception e) {
OUT.println(e.getMessage());
}
}
private static void tryToAcceptRequest() throws Exception {
Socket socket = _serverSocket.accept();
OUT.println("Request Received");
sendReport(socket);
try {
validateBuildRequest(socket);
} finally {
socket.close();
}
new Thread() { @Override public void run() {
SimployCore.runCommand();
}}.start();
}
private static void sendReport(Socket socket) throws Exception {
OutputStream output = socket.getOutputStream();
String reply = REPLY_HEADER + SimployCore.report();
output.write(reply.getBytes("UTF-8"));
output.flush();
}
private static void validateBuildRequest(Socket socket) throws Exception {
if (_password == null) throwInvalid("Build requests are not being accepted.");
socket.setSoTimeout(REQUEST_TIMEOUT);
long t0 = System.currentTimeMillis();
InputStream inputStream = socket.getInputStream();
String request = "";
while (!request.contains(_password)) {
int read = inputStream.read();
if (read == -1) throwInvalid(request);
request += (char)read;
if (System.currentTimeMillis() - t0 > REQUEST_TIMEOUT) throwInvalid(request);
if (request.length() > 2000) throwInvalid("<Request too large>");
}
}
private static void throwInvalid(String request) throws Exception {
throw new Exception("Invalid Request: " + request);
}
}