-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathSubmit.java
More file actions
568 lines (530 loc) · 22.8 KB
/
Submit.java
File metadata and controls
568 lines (530 loc) · 22.8 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
// Version: 20220920
import java.io.*;
import java.net.*;
import java.util.*;
public class Submit {
private static final boolean intellij = false;
public static void main(String[] args) {
// ONLY USED FOR THE INTELLIJ ENVIROMENT
// For BlueJ, ignore these comments
// Add call to the test method here, to test the implementation
// Uncomment the following line, and add the needed task id, username and password
// to submit the code to the server
// submit("<id>", "<username>", "<password>");
}
private static void debug(String m) { /*System.out.println(m);*/ }
private static final String host = "https://domjudge.cs.au.dk";
private static final String data_filename = "submit_data.txt";
private static final String extension = "java";
private static final String contest = null;
private String task;
private String username;
private String password;
private String mainClass;
// 0: not a multi task; i >= 1: part i (out of "variants") of a multi task.
private int multiTask;
private int variants;
// Delimiter used between the problem id and the number of variants.
private static final char DELIMITER = '-';
public static void submit(String taskID, String username, String password) {
try {
try(Writer file = new FileWriter(data_filename)) {
try(PrintWriter out = new PrintWriter(file)) {
out.println(taskID);
out.println(username);
out.println(password);
out.println("");
out.println("This file contains the Task ID, username and password");
out.println("last used when submitting a solution.");
out.println("This file is used when you call Submit.submit() with no arguments.");
}
}
submit();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static void submit() {
try {
Submit s = new Submit();
String task;
System.out.println(
"============================================================");
if (!s.validateFilenames()) return;
try {
try(Reader file = new FileReader(data_filename)) {
BufferedReader in = new BufferedReader(file);
task = in.readLine();
s.username = in.readLine();
s.password = in.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("No password saved. " +
"Run submit(taskID, username, password) instead.");
return;
}
s.ensureLoginCookie();
int delimiter = task.indexOf(DELIMITER);
if (delimiter == -1) {
s.task = task;
s.multiTask = 0;
s.variants = 1;
s.outputFeedback(s.doSubmit());
} else {
s.variants = Integer.parseInt(task.substring(delimiter+1));
task = task.substring(0, delimiter);
String judging = null;
for (int i = 1; i <= s.variants; i += 1) {
s.task = task + i;
s.multiTask = i;
judging = s.doSubmit();
if (!"correct".equals(judging)) break;
}
s.outputFeedback(judging);
}
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private String cookie;
private String boundary;
private byte[] boundaryBytes;
private byte[] finishBoundaryBytes;
public Submit() throws IOException {
boundary = UUID.randomUUID().toString();
boundaryBytes =
("--" + boundary + "\r\n").getBytes("UTF-8");
finishBoundaryBytes =
("--" + boundary + "--").getBytes("UTF-8");
}
public String doSubmit() throws IOException {
int contestId = getContestId();
int problemId = getProblemId(contestId);
if (problemId == -1) {
System.out.println("Could not find any task of name " + task + ".");
if (multiTask > 1) {
System.out.println("Maybe this problem only has " + (multiTask-1) + " parts.");
}
return null;
}
String submissionResult;
HttpURLConnection http = makePostSubmissionRequest(contestId);
sendSubmissionForm(http, problemId);
if (getResponseCode(http) == 401) {
System.out.println("Wrong username or password. " +
"Please run submit(taskID, username, password) again.");
return null;
}
submissionResult = readResponse(http);
if (submissionResult.startsWith("error: ")) {
System.out.println(submissionResult);
System.out.println(
"Check your Task ID and call " +
"submit(taskID, username, password) again.");
if (multiTask > 1) {
System.out.println("Maybe this problem only has " + (multiTask-1) + " parts.");
}
return null;
}
String submissionId = getJsonNaive(submissionResult, "id", 0);
System.out.println("Submitted to " +
host + "/team/submission/" +
submissionId);
int timeout = 60;
return pollJudging(submissionId, timeout);
}
private String getJsonNaive(String contents, String key, int startIndex) {
String needle = "\"" + key + "\":\"";
int i = contents.indexOf(needle, startIndex);
if (i == -1) return null;
int j = contents.indexOf("\"", i + needle.length());
return contents.substring(i + needle.length(), j);
}
private int getContestId() throws IOException {
URL url = new URL(host + "/api/v4/contests");
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
http.setDoOutput(true);
String contents = readResponse(http);
return Integer.parseInt(getJsonNaive(contents, "id", 0));
}
private int getProblemId(int contestId) throws IOException {
URL url = new URL(host + "/api/v4/contests/" + contestId + "/problems");
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
http.setDoOutput(true);
String contents = readResponse(http);
int i = contents.indexOf("{");
while (i != -1) {
String shortName = getJsonNaive(contents, "short_name", i);
if (task.equals(shortName))
return Integer.parseInt(getJsonNaive(contents, "id", i));
i = contents.indexOf("{", i+1);
}
return -1;
}
public boolean outputFeedback(String judging) {
if (judging == null) return false;
if (judging.equals("correct")) {
if (variants <= 1) {
System.out.println("Points: 1 out of 1");
System.out.println("Congratulations, your solution is correct!");
} else if (multiTask > 1) {
System.out.println("Points: " + multiTask + " out of " + variants);
System.out.println("Congratulations, you get an additional point for speed!");
} else {
System.out.println("Points: " + multiTask + " out of " + variants);
System.out.println("Congratulations, your solution is correct!");
}
return true;
}
if (variants <= 1) {
System.out.println("Points: 0 out of 1");
} else {
System.out.println("Points: " + (multiTask-1) + " out of " + variants);
}
if (judging.equals("timelimit")) {
if (multiTask > 1) {
System.out.println("Your solution is correct, " +
"but you do not get extra points for speed.");
} else {
System.out.println("Sorry, but your solution is not efficient enough " +
"(time limit exceeded).");
}
} else if (judging.equals("timeout")) {
System.out.println(
"Judging is taking too long. What's going on?");
} else if (judging.equals("compiler-error")) {
System.out.println(
"Sorry, but the judge could not compile your solution!");
} else if (judging.equals("wrong-answer")) {
System.out.println(
"Sorry, but your solution gives the wrong answer on one or more of the " +
"hidden test cases.");
System.out.println(
"If you have used System.out.println() in your solution, then you must " +
"remove these lines before submitting to the judge!");
System.out.println(
"If not, you need to find and fix the errors in your solution, " +
"and try submitting again.");
} else {
System.out.println(
"Sorry, but something is wrong with your solution (" + judging + ")");
}
return false;
}
private String getLoginCsrfToken(String contents) throws IOException {
String needle = "<input type=\"hidden\" name=\"_csrf_token\" value=\"";
int pos = contents.indexOf(needle);
if (pos == -1)
throw new RuntimeException("Could not get CSRF token from login page");
int quotepos = contents.indexOf('"', pos + needle.length());
return contents.substring(pos + needle.length(), quotepos);
}
private String prepareLoginPostData(String username, String password) throws IOException {
HttpURLConnection http = makeGetLoginRequest();
String response = readResponse(http);
ensureCookie(http);
debug("Cookie: " + cookie);
String csrfToken = getLoginCsrfToken(response);
debug("CSRF: " + csrfToken);
return "_csrf_token=" + csrfToken +
"&_username=" + username +
"&_password=" + password;
}
private void ensureCookie(HttpURLConnection http) throws IOException {
String setCookie = http.getHeaderField("Set-Cookie");
if (setCookie == null) {
if (cookie == null) {
throw new RuntimeException("Did not get Set-Cookie header");
}
return;
}
int semi = setCookie.indexOf(';');
if (semi != -1)
setCookie = setCookie.substring(0, semi);
debug("Set cookie to " + setCookie);
cookie = setCookie;
}
private void ensureLoginCookie() throws IOException {
String postData = prepareLoginPostData(username, password);
HttpURLConnection http = makePostLoginRequest();
try {
try(OutputStream out = http.getOutputStream()) {
try(PrintWriter print = new PrintWriter(out)) {
print.print(postData);
}
}
// Force the HttpURLConnection to send the request:
http.getInputStream();
if (http.getResponseCode() >= 400)
throw new RuntimeException("Unexpected failure response code");
// TODO: At this point the response code should be 302 (redirect).
// We could check whether we are redirected to /login (wrong password)
// or / (correct password) and report an error here,
// instead of waiting until doSubmit() with reporting the error.
} catch (ConnectException e) {
String msg = "Could not connect. Is your internet connection working?";
System.out.println(msg);
throw new RuntimeException(msg, e);
} catch (IOException e) {
throw new RuntimeException("Failed to login", e);
}
ensureCookie(http);
debug("Obtained login cookie");
}
private String pollJudging(String submissionId, int timeout) throws IOException {
int waitTime = 0;
int polls = 0;
while (true) {
int t = Math.min(5, polls);
try {
if (t > 0) {
Thread.sleep(t * 1000);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String judging = getSubmissionJudging(submissionId);
waitTime += t;
polls += 1;
if (judging == null) {
if (waitTime >= timeout) {
return "timeout";
}
continue;
}
return judging;
}
}
private String getSubmissionJudging(String submissionId) throws IOException {
HttpURLConnection http = makeGetSubmissionRequest(submissionId);
String contents = readResponse(http);
final String notFound = "Submission not found for this team or not judged yet.";
if (contents.contains(notFound))
return null; // Try again
final String pending = "<span class=\"sol sol_queued\">";
if (contents.contains(pending))
return null; // Try again
// <p>Result: <span class="sol sol_incorrect">wrong-answer</span></p>
final String incorrect = "<span class=\"sol sol_incorrect\">";
int pos = contents.indexOf(incorrect);
if (pos != -1) {
pos += incorrect.length();
int i = contents.indexOf('<', pos);
if (i == -1) throw new RuntimeException("No </span> found");
String code = contents.substring(pos, i);
if (code.equals("correct")) throw new RuntimeException("Incorrect and correct");
return code;
}
final String correct = "<span class=\"sol sol_correct\">";
if (contents.contains(correct))
return "correct";
final String compileError = "<span class=\"badge badge-danger\">";
if (contents.contains(compileError))
return "compiler-error";
System.out.println(contents);
throw new RuntimeException("Failed to parse submission_details.php output");
}
private HttpURLConnection makeLoginRequest(boolean isPost) throws IOException {
URL url = new URL(host + "/login");
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
http.setRequestMethod(isPost ? "POST" : "GET");
http.setDoOutput(true);
if (cookie != null)
http.setRequestProperty("Cookie", cookie);
http.setInstanceFollowRedirects(false);
if (isPost) {
http.setRequestProperty(
"Content-Type",
"application/x-www-form-urlencoded");
// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);
}
return http;
}
private HttpURLConnection makeGetLoginRequest() throws IOException {
return makeLoginRequest(false);
}
private HttpURLConnection makePostLoginRequest() throws IOException {
return makeLoginRequest(true);
}
private HttpURLConnection makePostSubmissionRequest(int contestId) throws IOException {
URL url = new URL(host + "/api/v4/contests/" + contestId + "/submissions");
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
http.setRequestMethod("POST");
http.setDoOutput(true);
String authorization = username + ":" + password;
String authEncoded = Base64.getEncoder().encodeToString(authorization.getBytes("UTF-8"));
http.setRequestProperty("Authorization", "Basic " + authEncoded);
http.setRequestProperty(
"Content-Type",
"multipart/form-data; charset=UTF-8; boundary=" + boundary);
// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);
return http;
}
private HttpURLConnection makeGetSubmissionRequest(String submissionId) throws IOException {
URL url = new URL(host + "/team/submission/" + submissionId);
debug("Connect to " + url);
URLConnection conn = url.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
http.setDoOutput(true);
debug("Set cookie " + cookie);
if (cookie != null)
http.setRequestProperty("Cookie", cookie);
// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);
return http;
}
private static String join(String delimiter, Iterable<String> items) {
String s = "";
StringBuilder b = new StringBuilder();
for (String x : items) {
b.append(s);
b.append(x);
s = delimiter;
}
return b.toString();
}
private boolean validateFilenames() throws IOException {
Set<String> r = new HashSet<String>();
for (String fileName : getFilenames()) {
try(FileReader file = new FileReader(fileName)) {
BufferedReader rd = new BufferedReader(file);
while (true) {
String line = rd.readLine();
if (line == null) break;
// Note, we must break the following string into two pieces
// to avoid Submit.java detecting itself as a task file.
String needle = "public static void " + "main(String[]";
if (line.contains(needle))
r.add(fileName);
}
}
}
if (r.size() > 1) {
System.out.println("Error: Multiple task files found (" +
join(", ", r) + ").");
System.out.println(" You need to make a new " +
"BlueJ project for each task.");
return false;
}
if (r.size() == 0) {
System.out.println("Error: No task file found.");
return false;
}
String fileName = r.iterator().next();
mainClass = fileName.replace(".java", "").replace("src/", "");
return true;
}
private void sendSubmissionForm(HttpURLConnection http, int problemId) throws IOException {
try(OutputStream out = http.getOutputStream()) {
for (String filename : getFilenames()) {
try(InputStream file = new FileInputStream(filename)) {
out.write(boundaryBytes);
sendFile(out, "code[]", file, filename);
}
}
out.write(boundaryBytes);
sendField(out, "problem", problemId + "");
out.write(boundaryBytes);
sendField(out, "language", extension);
out.write(boundaryBytes);
sendField(out, "entry_point", mainClass);
out.write(finishBoundaryBytes);
}
}
private List<String> getFilenames() {
List<String> r = new ArrayList<String>();
String dir = intellij ? "./src/" : ".";
String end = intellij ? "src/" : "";
for (final File fileEntry : new File(dir).listFiles()) {
String n = fileEntry.getName();
if (n.startsWith("_") || n.startsWith(".") || n.equals("Submit.java")) {
continue;
}
if (n.endsWith(".java")) {
r.add(end + n);
}
}
return r;
}
private int getResponseCode(HttpURLConnection http) throws IOException {
int responseCode;
try {
http.getInputStream();
responseCode = http.getResponseCode();
if (responseCode >= 300)
throw new RuntimeException("Unexpected failure response code");
} catch (IOException e) {
http.getErrorStream();
responseCode = http.getResponseCode();
if (http.getResponseCode() < 300)
throw new RuntimeException("Unexpected success response code");
}
return responseCode;
}
private String readResponse(HttpURLConnection http) throws IOException {
InputStream inputStream;
try {
inputStream = http.getInputStream();
if (http.getResponseCode() >= 300)
throw new RuntimeException("Unexpected failure response code");
} catch (ConnectException e) {
String msg = "Could not connect. Is your internet connection working?";
System.out.println(msg);
throw new RuntimeException(msg, e);
} catch (IOException e) {
inputStream = http.getErrorStream();
if (inputStream == null)
throw new RuntimeException(e);
if (http.getResponseCode() < 300)
throw new RuntimeException("Unexpected success response code");
}
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = in.readLine()) != null) {
sb.append(line + "\n");
}
in.close();
String result = sb.toString();
if (http.getResponseCode() == 500 && result.startsWith("error: "))
return result;
if (http.getResponseCode() >= 300)
throw new RuntimeException(
"HTTP " + http.getResponseCode() + ": " + result);
return result;
}
private void sendFile(OutputStream out, String name, InputStream in, String filename) throws IOException {
// XXX: This doesn't strip whitespace characters such as CR and LF.
debug("Submitting " + filename);
String[] split = filename.split("/");
filename = split[split.length - 1];
String o = "Content-Disposition: form-data; name=\"" +
name.replace("\\", "\\\\").replace("\"", "\\\"") +
"\"; filename=\"" +
filename.replace("\\", "\\\\").replace("\"", "\\\"") +
"\"\r\n\r\n";
out.write(o.getBytes("UTF-8"));
byte[] buffer = new byte[2048];
for (int n = 0; n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);
out.write("\r\n".getBytes("UTF-8"));
}
private void sendField(OutputStream out, String name, String field) throws IOException {
// XXX: This doesn't strip whitespace characters such as CR and LF.
debug(name + "=" + field);
String o = "Content-Disposition: form-data; name=\"" +
name.replace("\\", "\\\\").replace("\"", "\\\"") +
"\"\r\n\r\n";
out.write(o.getBytes("UTF-8"));
out.write(URLEncoder.encode(field, "UTF-8").getBytes("UTF-8"));
out.write("\r\n".getBytes("UTF-8"));
}
}