-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainTrain.java
More file actions
92 lines (77 loc) · 3.29 KB
/
Copy pathMainTrain.java
File metadata and controls
92 lines (77 loc) · 3.29 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
package test;
import java.io.*;
import java.net.Socket;
import java.util.Map;
public class MainTrain {
public static void testParseRequest() {
String request = "GET /test?name=John&age=25 HTTP/1.1\r\nHost: localhost\r\n\r\n";
try {
RequestParser.RequestInfo ri = RequestParser.parseRequest(new BufferedReader(new StringReader(request)));
if(!ri.getHttpCommand().equals("GET") ||
!ri.getUri().equals("/test") ||
!ri.getParameters().get("name").equals("John") ||
!ri.getParameters().get("age").equals("25"))
System.out.println("problem parsing the request");
} catch(Exception e) {
System.out.println("problem parsing the request (-20)");
}
}
public static void testServer() throws Exception {
MyHTTPServer server = new MyHTTPServer(8080);
int initialThreads = Thread.activeCount();
Servlet calcServlet = new Servlet() {
@Override
public void handle(RequestParser.RequestInfo ri, OutputStream out) throws IOException {
Map<String, String> params = ri.getParameters();
System.out.println("Received parameters: " + params); // Debug print
int x = Integer.parseInt(params.get("x"));
int y = Integer.parseInt(params.get("y"));
int result = x + y;
System.out.println("Calculated result: " + result); // Debug print
// Write response exactly as test expects
String responseStr = String.valueOf(result);
out.write(responseStr.getBytes());
out.flush();
}
@Override
public void close() {}
};
server.addServlet("GET", "/calc", calcServlet);
server.start();
Thread.sleep(1000);
if (Thread.activeCount() != initialThreads + 1) {
throw new Exception("Incorrect thread count");
}
Socket client = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(client.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// Detailed request logging
out.println("GET /calc?x=5&y=3 HTTP/1.1");
out.println("Host: localhost");
out.println();
out.flush();
// Read entire response
StringBuilder response = new StringBuilder();
int ch;
while ((ch = in.read()) != -1) {
response.append((char)ch);
}
System.out.println("Full response: " + response.toString());
client.close();
server.close();
Thread.sleep(2000);
if (Thread.activeCount() > initialThreads) {
throw new Exception("Threads not closed properly");
}
}
public static void main(String[] args) {
try {
testParseRequest();
testServer();
System.out.println("done");
} catch(Exception e) {
System.out.println("Test failed");
e.printStackTrace();
}
}
}