-
Notifications
You must be signed in to change notification settings - Fork 18
/
SubmissionResultParser.java
82 lines (64 loc) · 3.09 KB
/
SubmissionResultParser.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
package fi.helsinki.cs.tmc.core.communication.serialization;
import fi.helsinki.cs.tmc.core.domain.submission.SubmissionResult;
import fi.helsinki.cs.tmc.stylerunner.validation.CheckstyleResult;
import fi.helsinki.cs.tmc.testrunner.StackTraceSerializer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.lang.reflect.Type;
public class SubmissionResultParser {
private static final Logger logger = LoggerFactory.getLogger(SubmissionResultParser.class);
public SubmissionResult parseFromJson(final String json) {
if (json.trim().isEmpty()) {
logger.info("Attempted to parse empty string as JSON");
throw new IllegalArgumentException("Empty input");
}
try {
Gson gson =
new GsonBuilder()
.registerTypeAdapter(
SubmissionResult.Status.class, new StatusDeserializer())
.registerTypeAdapter(
StackTraceElement.class, new StackTraceSerializer())
.create();
SubmissionResult result = gson.fromJson(json, SubmissionResult.class);
// Parse validations field from JSON
JsonObject output = new JsonParser().parse(json).getAsJsonObject();
JsonElement validationElement = output.get("validations");
if (validationElement != null) {
result.setValidationResult(CheckstyleResult.build(validationElement.toString()));
} else {
result.setValidationResult(CheckstyleResult.build("{}"));
}
return result;
} catch (RuntimeException | IOException runtimeException) {
logger.warn("Failed to parse submission result", runtimeException);
throw new RuntimeException(
"Failed to parse submission result: " + runtimeException.getMessage(),
runtimeException);
}
}
private static class StatusDeserializer implements JsonDeserializer<SubmissionResult.Status> {
private static final Logger logger = LoggerFactory.getLogger(StatusDeserializer.class);
@Override
public SubmissionResult.Status deserialize(
JsonElement json, Type typeOfT, JsonDeserializationContext context)
throws JsonParseException {
String str = json.getAsJsonPrimitive().getAsString();
try {
return SubmissionResult.Status.valueOf(str.toUpperCase());
} catch (IllegalArgumentException e) {
logger.warn("Attempted to parse unknown submission status " + str);
throw new JsonParseException("Unknown submission status: " + str);
}
}
}
}