-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathServerAccess.java
More file actions
403 lines (347 loc) · 14.5 KB
/
ServerAccess.java
File metadata and controls
403 lines (347 loc) · 14.5 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
package fi.helsinki.cs.tmc.model;
import fi.helsinki.cs.tmc.core.domain.Course;
import fi.helsinki.cs.tmc.core.domain.Exercise;
import fi.helsinki.cs.tmc.data.FeedbackAnswer;
import fi.helsinki.cs.tmc.core.domain.Review;
import fi.helsinki.cs.tmc.data.serialization.CourseInfoParser;
import fi.helsinki.cs.tmc.data.serialization.CourseListParser;
import fi.helsinki.cs.tmc.data.serialization.ReviewListParser;
import fi.helsinki.cs.tmc.spyware.LoggableEvent;
import fi.helsinki.cs.tmc.utilities.ByteArrayGsonSerializer;
import fi.helsinki.cs.tmc.utilities.CancellableCallable;
import fi.helsinki.cs.tmc.utilities.ExceptionUtils;
import fi.helsinki.cs.tmc.utilities.UriUtils;
import fi.helsinki.cs.tmc.utilities.http.FailedHttpResponseException;
import fi.helsinki.cs.tmc.utilities.http.HttpTasks;
import fi.helsinki.cs.tmc.core.TmcCore;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.openide.modules.Modules;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPOutputStream;
/**
* A frontend for the server.
*
* @deprecated Users are suggested to rely on the tmc-core instead of this implementation.
*/
@Deprecated
public class ServerAccess {
public static final int API_VERSION = 7;
private NbTmcSettings settings;
private CourseListParser courseListParser;
private CourseInfoParser courseInfoParser;
private ReviewListParser reviewListParser;
private String clientVersion;
private TmcCore tmcCore;
public ServerAccess() {
this(NbTmcSettings.getDefault());
}
public ServerAccess(NbTmcSettings settings) {
this(settings, new CourseListParser(), new CourseInfoParser(), new ReviewListParser());
}
public ServerAccess(
NbTmcSettings settings,
CourseListParser courseListParser,
CourseInfoParser courseInfoParser,
ReviewListParser reviewListParser) {
this.settings = settings;
this.courseListParser = courseListParser;
this.courseInfoParser = courseInfoParser;
this.reviewListParser = reviewListParser;
this.clientVersion = getClientVersion();
}
private static String getClientVersion() {
return Modules.getDefault()
.ownerOf(ServerAccess.class)
.getSpecificationVersion()
.toString();
}
public void setSettings(NbTmcSettings settings) {
this.settings = settings;
}
private String getCourseListUrl() {
return addApiCallQueryParameters(settings.getServerAddress() + "/courses.json");
}
public String addApiCallQueryParameters(String url) {
url = UriUtils.withQueryParam(url, "api_version", "" + API_VERSION);
url = UriUtils.withQueryParam(url, "client", "netbeans_plugin");
url = UriUtils.withQueryParam(url, "client_version", getClientVersion());
return url;
}
private HttpTasks createHttpTasks() {
return new HttpTasks().setCredentials(settings.getUsername(), settings.getPassword());
}
public boolean hasEnoughSettings() {
return !settings.getUsername().isEmpty()
&& !settings.getPassword().isEmpty()
&& !settings.getServerAddress().isEmpty();
}
public boolean needsOnlyPassword() {
return !settings.getUsername().isEmpty()
&& settings.getPassword().isEmpty()
&& !settings.getServerAddress().isEmpty();
}
@Deprecated
public CancellableCallable<List<Course>> getDownloadingCourseListTask() {
final CancellableCallable<String> download =
createHttpTasks().getForText(getCourseListUrl());
return new CancellableCallable<List<Course>>() {
@Override
public List<Course> call() throws Exception {
try {
String text = download.call();
return courseListParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
}
@Override
public boolean cancel() {
return download.cancel();
}
};
}
@Deprecated
public CancellableCallable<Course> getFullCourseInfoTask(Course courseStub) {
URI url = URI.create(addApiCallQueryParameters(courseStub.getDetailsUrl().toString()));
final CancellableCallable<String> download = createHttpTasks().getForText(url.toString());
return new CancellableCallable<Course>() {
@Override
public Course call() throws Exception {
try {
String text = download.call();
return courseInfoParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
}
@Override
public boolean cancel() {
return download.cancel();
}
};
}
public CancellableCallable<Void> getUnlockingTask(Course course) {
Map<String, String> params = Collections.emptyMap();
final CancellableCallable<String> download =
createHttpTasks().postForText(getUnlockUrl(course), params);
return new CancellableCallable<Void>() {
@Override
public Void call() throws Exception {
try {
download.call();
return null;
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
}
@Override
public boolean cancel() {
return download.cancel();
}
};
}
private String getUnlockUrl(Course course) {
return addApiCallQueryParameters(course.getUnlockUrl().toString());
}
public CancellableCallable<byte[]> getDownloadingExerciseZipTask(Exercise exercise) {
URI zipUrl = exercise.getDownloadUrl();
return createHttpTasks().getForBinary(zipUrl.toString());
}
public CancellableCallable<byte[]> getDownloadingExerciseSolutionZipTask(Exercise exercise) {
URI zipUrl = exercise.getSolutionDownloadUrl();
return createHttpTasks().getForBinary(zipUrl.toString());
}
public CancellableCallable<SubmissionResponse> getSubmittingExerciseTask(
final Exercise exercise, final byte[] sourceZip, Map<String, String> extraParams) {
final URI submitUrl = URI.create(addApiCallQueryParameters(exercise.getReturnUrl().toString()));
Map<String, String> params = new LinkedHashMap<String, String>();
params.put("client_time", "" + (System.currentTimeMillis() / 1000L));
params.put("client_nanotime", "" + System.nanoTime());
params.putAll(extraParams);
final CancellableCallable<String> upload =
createHttpTasks()
.uploadFileForTextDownload(
submitUrl.toString(), params, "submission[file]", sourceZip);
return new CancellableCallable<SubmissionResponse>() {
@Override
public SubmissionResponse call() throws Exception {
String response;
try {
response = upload.call();
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
JsonObject respJson = new JsonParser().parse(response).getAsJsonObject();
if (respJson.get("error") != null) {
throw new RuntimeException(
"Server responded with error: " + respJson.get("error"));
} else if (respJson.get("submission_url") != null) {
try {
URI submissionUrl = new URI(respJson.get("submission_url").getAsString());
URI pasteUrl = new URI(respJson.get("paste_url").getAsString());
return new SubmissionResponse(submissionUrl, pasteUrl);
} catch (Exception e) {
throw new RuntimeException(
"Server responded with malformed submission url");
}
} else {
throw new RuntimeException("Server returned unknown response");
}
}
@Override
public boolean cancel() {
return upload.cancel();
}
};
}
public static class SubmissionResponse {
public final URI submissionUrl;
public final URI pasteUrl;
public SubmissionResponse(URI submissionUrl, URI pasteUrl) {
this.submissionUrl = submissionUrl;
this.pasteUrl = pasteUrl;
}
}
public CancellableCallable<String> getSubmissionFetchTask(String submissionUrl) {
return createHttpTasks().getForText(submissionUrl);
}
public CancellableCallable<List<Review>> getDownloadingReviewListTask(Course course) {
URI url = URI.create(addApiCallQueryParameters(course.getReviewsUrl().toString()));
final CancellableCallable<String> download = createHttpTasks().getForText(url.toString());
return new CancellableCallable<List<Review>>() {
@Override
public List<Review> call() throws Exception {
try {
String text = download.call();
return reviewListParser.parseFromJson(text);
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
}
@Override
public boolean cancel() {
return download.cancel();
}
};
}
public CancellableCallable<Void> getMarkingReviewAsReadTask(Review review, boolean read) {
String url = addApiCallQueryParameters(review.getUpdateUrl() + ".json");
Map<String, String> params = new HashMap<String, String>();
params.put("_method", "put");
if (read) {
params.put("mark_as_read", "1");
} else {
params.put("mark_as_unread", "1");
}
final CancellableCallable<String> task = createHttpTasks().postForText(url, params);
return new CancellableCallable<Void>() {
@Override
public Void call() throws Exception {
task.call();
return null;
}
@Override
public boolean cancel() {
return task.cancel();
}
};
}
public CancellableCallable<String> getFeedbackAnsweringJob(
String answerUrl, List<FeedbackAnswer> answers) {
final String submitUrl = addApiCallQueryParameters(answerUrl);
Map<String, String> params = new HashMap<String, String>();
for (int i = 0; i < answers.size(); ++i) {
String keyPrefix = "answers[" + i + "]";
FeedbackAnswer answer = answers.get(i);
params.put(keyPrefix + "[question_id]", "" + answer.getQuestion().getId());
params.put(keyPrefix + "[answer]", answer.getAnswer());
}
final CancellableCallable<String> upload = createHttpTasks().postForText(submitUrl, params);
return new CancellableCallable<String>() {
@Override
public String call() throws Exception {
try {
return upload.call();
} catch (FailedHttpResponseException ex) {
return checkForObsoleteClient(ex);
}
}
@Override
public boolean cancel() {
return upload.cancel();
}
};
}
public CancellableCallable<Object> getSendEventLogJob(
String spywareServerUrl, List<LoggableEvent> events) {
String url = addApiCallQueryParameters(spywareServerUrl);
Map<String, String> extraHeaders = new LinkedHashMap<String, String>();
extraHeaders.put("X-Tmc-Version", "1");
extraHeaders.put("X-Tmc-Username", settings.getUsername());
extraHeaders.put("X-Tmc-Password", settings.getPassword());
byte[] data;
try {
data = eventListToPostBody(events);
} catch (IOException e) {
throw ExceptionUtils.toRuntimeException(e);
}
final CancellableCallable<String> upload =
createHttpTasks().rawPostForText(url, data, extraHeaders);
return new CancellableCallable<Object>() {
@Override
public Object call() throws Exception {
upload.call();
return null;
}
@Override
public boolean cancel() {
return upload.cancel();
}
};
}
public byte[] eventListToPostBody(List<LoggableEvent> events) throws IOException {
ByteArrayOutputStream bufferBos = new ByteArrayOutputStream();
GZIPOutputStream gzos = new GZIPOutputStream(bufferBos);
OutputStreamWriter bufferWriter = new OutputStreamWriter(gzos, Charset.forName("UTF-8"));
Gson gson =
new GsonBuilder()
.registerTypeAdapter(byte[].class, new ByteArrayGsonSerializer()).create();
gson.toJson(events, new TypeToken<List<LoggableEvent>>() {}.getType(), bufferWriter);
bufferWriter.close();
gzos.close();
return bufferBos.toByteArray();
}
private <T> T checkForObsoleteClient(FailedHttpResponseException ex)
throws ObsoleteClientException, FailedHttpResponseException {
if (ex.getStatusCode() == 404) {
boolean obsolete;
try {
obsolete =
new JsonParser()
.parse(ex.getEntityAsString())
.getAsJsonObject()
.get("obsolete_client")
.getAsBoolean();
} catch (Exception ex2) {
obsolete = false;
}
if (obsolete) {
throw new ObsoleteClientException();
}
}
throw ex;
}
}