This repository has been archived by the owner on Nov 9, 2023. It is now read-only.
forked from ucsd-cse15l-f22/list-examples-grader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GradeServer.java
75 lines (65 loc) · 2.2 KB
/
GradeServer.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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.stream.Stream;
class ExecHelpers {
/**
Takes an input stream, reads the full stream, and returns the result as a
string.
In Java 9 and later, new String(out.readAllBytes()) would be a better
option, but using Java 8 for compatibility with ieng6.
*/
static String streamToString(InputStream out) throws IOException {
String result = "";
while(true) {
int c = out.read();
if(c == -1) { break; }
result += (char)c;
System.out.println(System.currentTimeMillis() + "; just read: " + (char)c);
}
return result;
}
/**
Takes a command, represented as an array of strings as it would by typed at
the command line, runs it, and returns its combined stdout and stderr as a
string.
*/
static String exec(String[] cmd) throws IOException {
Process p = new ProcessBuilder()
.command(Arrays.asList(cmd))
.redirectErrorStream(true)
.start();
InputStream out = p.getInputStream();
return String.format("%s\n", streamToString(out));
}
}
class Handler implements URLHandler {
public String handleRequest(URI url) throws IOException {
if (url.getPath().equals("/grade")) {
String[] parameters = url.getQuery().split("=");
if (parameters[0].equals("repo")) {
return ExecHelpers.exec(new String[]{"bash", "grade.sh", parameters[1]});
}
else {
return "Couldn't find query parameter repo";
}
}
else {
return "Don't know how to handle that path!";
}
}
}
class GradeServer {
public static void main(String[] args) throws IOException {
if(args.length == 0){
System.out.println("Missing port number! Try any number between 1024 to 49151");
return;
}
int port = Integer.parseInt(args[0]);
Server.start(port, new Handler());
}
}